Skip to content

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

refactor: consolidate UI helpers into internal/cliui and modularize browser logic

Luigi Agosti59970b104697
diff --git a/cmd/pinchtab/cli_palette.go b/cmd/pinchtab/cli_palette.go
deleted file mode 100644
index f7d29d62..00000000
--- a/cmd/pinchtab/cli_palette.go
+++ /dev/null
@@ -1,47 +0,0 @@
-package main
-
-import (
- "os"
-
- "github.com/charmbracelet/lipgloss"
- "github.com/pinchtab/pinchtab/internal/cliui"
-)
-
-var (
- pinchtabColorBorder = cliui.ColorBorder
- pinchtabColorTextPrimary = cliui.ColorTextPrimary
- pinchtabColorTextMuted = cliui.ColorTextMuted
- pinchtabColorAccent = cliui.ColorAccent
- pinchtabColorAccentLight = cliui.ColorAccentLight
- pinchtabColorSuccess = cliui.ColorSuccess
- pinchtabColorWarning = cliui.ColorWarning
- pinchtabColorDanger = cliui.ColorDanger
-)
-
-var (
- cliHeadingStyle = cliui.HeadingStyle
- cliCommandStyle = cliui.CommandStyle
- cliMutedStyle = cliui.MutedStyle
- cliSuccessStyle = cliui.SuccessStyle
- cliWarningStyle = cliui.WarningStyle
- cliErrorStyle = cliui.ErrorStyle
- cliValueStyle = cliui.ValueStyle
-)
-
-func renderToWriter(w *os.File, style lipgloss.Style, text string) string {
- if w == os.Stdout {
- return cliui.RenderStdout(style, text)
- }
- if w == os.Stderr {
- return cliui.RenderStderr(style, text)
- }
- return style.Render(text)
-}
-
-func styleStdout(style lipgloss.Style, text string) string {
- return renderToWriter(os.Stdout, style, text)
-}
-
-func styleStderr(style lipgloss.Style, text string) string {
- return renderToWriter(os.Stderr, style, text)
-}
diff --git a/cmd/pinchtab/cmd_browser.go b/cmd/pinchtab/cmd_browser.go
deleted file mode 100644
index 8eab3253..00000000
--- a/cmd/pinchtab/cmd_browser.go
+++ /dev/null
@@ -1,1135 +0,0 @@
-package main
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "log"
- "net/http"
- "net/url"
- "os"
- "strconv"
- "strings"
- "time"
-)
-
-// --- navigate ---
-
-func cliNavigate(client *http.Client, base, token string, args []string) {
- if len(args) < 1 {
- fatal("Usage: pinchtab nav <url> [--new-tab] [--block-images] [--block-ads]")
- }
- body := map[string]any{"url": args[0]}
- for _, a := range args[1:] {
- switch a {
- case "--new-tab":
- body["newTab"] = true
- case "--block-images":
- body["blockImages"] = true
- case "--block-ads":
- body["blockAds"] = true
- }
- }
- result := doPost(client, base, token, "/navigate", body)
- suggestNextAction("navigate", result)
-}
-
-// --- snapshot ---
-
-func cliSnapshot(client *http.Client, base, token string, args []string) {
- params := url.Values{}
- for i := 0; i < len(args); i++ {
- switch args[i] {
- case "--interactive", "-i":
- params.Set("filter", "interactive")
- case "--compact", "-c":
- params.Set("format", "compact")
- case "--text":
- params.Set("format", "text")
- case "--diff", "-d":
- params.Set("diff", "true")
- case "--selector", "-s":
- if i+1 < len(args) {
- i++
- params.Set("selector", args[i])
- }
- case "--max-tokens":
- if i+1 < len(args) {
- i++
- params.Set("maxTokens", args[i])
- }
- case "--depth":
- if i+1 < len(args) {
- i++
- params.Set("depth", args[i])
- }
- case "--tab":
- if i+1 < len(args) {
- i++
- params.Set("tabId", args[i])
- }
- }
- }
- result := doGet(client, base, token, "/snapshot", params)
- suggestNextAction("snapshot", result)
-}
-
-// --- element actions ---
-
-func cliAction(client *http.Client, base, token, kind string, args []string) {
- body := map[string]any{"kind": kind}
-
- switch kind {
- case "click", "hover", "focus":
- var cssSelector string
- var refArg string
- for i := 0; i < len(args); i++ {
- switch args[i] {
- case "--css":
- if i+1 < len(args) {
- i++
- cssSelector = args[i]
- }
- case "--wait-nav":
- body["waitNav"] = true
- default:
- if refArg == "" {
- refArg = args[i]
- }
- }
- }
- if cssSelector != "" {
- body["selector"] = cssSelector
- } else if refArg != "" {
- body["ref"] = refArg
- } else {
- fatal("Usage: pinchtab %s <ref> [--css <selector>] [--wait-nav]", kind)
- }
- case "type":
- if len(args) < 2 {
- fatal("Usage: pinchtab type <ref> <text>")
- }
- body["ref"] = args[0]
- body["text"] = strings.Join(args[1:], " ")
- case "fill":
- if len(args) < 2 {
- fatal("Usage: pinchtab fill <ref|selector> <text>")
- }
- if strings.HasPrefix(args[0], "e") {
- body["ref"] = args[0]
- } else {
- body["selector"] = args[0]
- }
- body["text"] = strings.Join(args[1:], " ")
- case "press":
- if len(args) < 1 {
- fatal("Usage: pinchtab press <key> (e.g. Enter, Tab, Escape)")
- }
- body["key"] = args[0]
- case "scroll":
- if len(args) < 1 {
- fatal("Usage: pinchtab scroll <ref|pixels|direction> (e.g. e5, 800, or down)")
- }
- if strings.HasPrefix(args[0], "e") {
- body["ref"] = args[0]
- } else if px, err := strconv.Atoi(args[0]); err == nil {
- body["scrollY"] = px
- } else {
- switch strings.ToLower(args[0]) {
- case "down":
- body["scrollY"] = 800
- case "up":
- body["scrollY"] = -800
- case "right":
- body["scrollX"] = 800
- case "left":
- body["scrollX"] = -800
- default:
- fatal("Usage: pinchtab scroll <ref|pixels|direction> (e.g. e5, 800, or down)")
- }
- }
- case "select":
- if len(args) < 2 {
- fatal("Usage: pinchtab select <ref> <value>")
- }
- body["ref"] = args[0]
- body["value"] = args[1]
- }
-
- doPost(client, base, token, "/action", body)
-}
-
-// --- text ---
-
-func cliText(client *http.Client, base, token string, args []string) {
- params := url.Values{}
- for i := 0; i < len(args); i++ {
- switch args[i] {
- case "--raw":
- params.Set("mode", "raw")
- case "--tab":
- if i+1 < len(args) {
- i++
- params.Set("tabId", args[i])
- }
- }
- }
- doGet(client, base, token, "/text", params)
-}
-
-// --- tabs ---
-
-func cliTabs(client *http.Client, base, token string, args []string) {
- if len(args) == 0 {
- // List all tabs
- doGet(client, base, token, "/tabs", nil)
- return
- }
-
- cmd := args[0]
- subArgs := args[1:]
-
- // Check if this is a tab operation (navigate, snapshot, click, etc.)
- // Pattern: pinchtab tab <operation> <tabId> [args...]
- if isTabOperation(cmd) {
- cliTabOperation(client, base, token, cmd, subArgs)
- return
- }
-
- // Legacy: pinchtab tab new/close
- switch cmd {
- case "new":
- url := ""
- if len(subArgs) > 0 {
- url = subArgs[0]
- }
-
- // Check if any instances are running
- instances := getInstances(client, base, token)
- if len(instances) == 0 {
- fmt.Fprintln(os.Stderr, styleStderr(cliWarningStyle, "No instances running, launching default..."))
- launchInstance(client, base, token, "default")
- fmt.Fprintln(os.Stderr, styleStderr(cliSuccessStyle, "Instance launched"))
- }
-
- body := map[string]any{"action": "new"}
- if url != "" {
- body["url"] = url
- }
- doPost(client, base, token, "/tab", body)
-
- case "close":
- if len(subArgs) < 1 {
- fatal("Usage: pinchtab tab close <tabId>")
- }
- doPost(client, base, token, "/tab", map[string]any{
- "action": "close",
- "tabId": subArgs[0],
- })
-
- default:
- cliTabOperation(client, base, token, cmd, subArgs)
- }
-}
-
-func isTabOperation(op string) bool {
- ops := map[string]bool{
- "navigate": true, "snapshot": true, "screenshot": true,
- "click": true, "type": true, "press": true, "fill": true,
- "hover": true, "scroll": true, "select": true, "focus": true,
- "text": true, "eval": true, "evaluate": true, "pdf": true,
- "cookies": true, "lock": true, "unlock": true, "locks": true,
- "fingerprint": true, "info": true,
- }
- return ops[op]
-}
-
-func cliTabOperation(client *http.Client, base, token string, op string, args []string) {
- if len(args) < 1 {
- fatal("Usage: pinchtab tab %s <tabId> [args...]", op)
- }
-
- tabID := args[0]
- restArgs := args[1:]
-
- switch op {
- case "navigate":
- if len(restArgs) < 1 {
- 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++ {
- switch restArgs[i] {
- case "--timeout":
- if i+1 < len(restArgs) {
- body["timeout"] = restArgs[i+1]
- i++
- }
- case "--block-images":
- body["blockImages"] = true
- case "--block-ads":
- body["blockAds"] = true
- }
- }
- doPost(client, base, token, fmt.Sprintf("/tabs/%s/navigate", tabID), body)
-
- case "snapshot":
- params := url.Values{}
- for _, arg := range restArgs {
- switch arg {
- case "-i", "--interactive":
- params.Set("interactive", "true")
- case "-c", "--compact":
- params.Set("compact", "true")
- case "-d", "--diff":
- params.Set("diff", "true")
- }
- }
- doGet(client, base, token, fmt.Sprintf("/tabs/%s/snapshot", tabID), params)
-
- case "screenshot", "ss":
- params := url.Values{}
- outFile := ""
- for i := 0; i < len(restArgs); i++ {
- switch restArgs[i] {
- case "-o", "--output":
- if i+1 < len(restArgs) {
- outFile = restArgs[i+1]
- i++
- }
- case "-q", "--quality":
- if i+1 < len(restArgs) {
- params.Set("quality", restArgs[i+1])
- i++
- }
- }
- }
- params.Set("raw", "true")
- data := 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(styleStdout(cliSuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
- }
- }
-
- case "click", "hover", "focus":
- if len(restArgs) < 1 {
- 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)
-
- case "type":
- if len(restArgs) < 2 {
- 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)
-
- case "fill":
- if len(restArgs) < 2 {
- 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)
-
- case "press":
- if len(restArgs) < 1 {
- 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)
-
- case "scroll":
- if len(restArgs) < 1 {
- fatal("Usage: pinchtab tab scroll <tabId> <direction|pixels>")
- }
- body := map[string]any{}
- if v, err := strconv.Atoi(restArgs[0]); err == nil {
- body["kind"] = "scroll"
- body["scrollY"] = v
- } else {
- body["kind"] = "scroll"
- body["direction"] = restArgs[0]
- }
- doPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
-
- case "select":
- if len(restArgs) < 2 {
- 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)
-
- case "text":
- params := url.Values{}
- for _, arg := range restArgs {
- if arg == "--raw" {
- params.Set("raw", "true")
- }
- }
- doGet(client, base, token, fmt.Sprintf("/tabs/%s/text", tabID), params)
-
- case "eval", "evaluate":
- if len(restArgs) < 1 {
- 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)
-
- case "pdf":
- params := url.Values{}
- outFile := ""
- for i := 0; i < len(restArgs); i++ {
- switch restArgs[i] {
- case "-o", "--output":
- if i+1 < len(restArgs) {
- outFile = restArgs[i+1]
- i++
- }
- case "--landscape":
- params.Set("landscape", "true")
- case "--scale":
- if i+1 < len(restArgs) {
- params.Set("scale", restArgs[i+1])
- i++
- }
- }
- }
- params.Set("raw", "true")
- data := 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))
- }
- }
-
- case "cookies":
- doGet(client, base, token, fmt.Sprintf("/tabs/%s/cookies", tabID), nil)
-
- case "lock":
- body := map[string]any{}
- for i := 0; i < len(restArgs); i++ {
- switch restArgs[i] {
- case "--owner":
- if i+1 < len(restArgs) {
- body["owner"] = restArgs[i+1]
- i++
- }
- case "--ttl":
- if i+1 < len(restArgs) {
- if ttl, err := strconv.Atoi(restArgs[i+1]); err == nil {
- body["ttl"] = ttl
- }
- i++
- }
- }
- }
- doPost(client, base, token, fmt.Sprintf("/tabs/%s/lock", tabID), body)
-
- case "unlock":
- body := map[string]any{}
- for i := 0; i < len(restArgs); i++ {
- switch restArgs[i] {
- case "--owner":
- if i+1 < len(restArgs) {
- body["owner"] = restArgs[i+1]
- i++
- }
- }
- }
- doPost(client, base, token, fmt.Sprintf("/tabs/%s/unlock", tabID), body)
-
- case "locks":
- doGet(client, base, token, fmt.Sprintf("/tabs/%s/locks", tabID), nil)
-
- case "info":
- doGet(client, base, token, fmt.Sprintf("/tabs/%s", tabID), nil)
-
- default:
- fatal("Unknown tab operation: %s", op)
- }
-}
-
-// getInstances fetches the list of running instances
-func getInstances(client *http.Client, base, token string) []map[string]any {
- resp, err := http.NewRequest("GET", base+"/instances", nil)
- if err != nil {
- return nil
- }
- if token != "" {
- resp.Header.Set("Authorization", "Bearer "+token)
- }
-
- result, err := client.Do(resp)
- if err != nil || result.StatusCode >= 400 {
- return nil
- }
- defer func() { _ = result.Body.Close() }()
-
- var data map[string]any
- if err := json.NewDecoder(result.Body).Decode(&data); err != nil {
- log.Printf("warning: error decoding instances response: %v", err)
- }
-
- if instances, ok := data["instances"].([]interface{}); ok {
- converted := make([]map[string]any, len(instances))
- for i, inst := range instances {
- if m, ok := inst.(map[string]any); ok {
- converted[i] = m
- }
- }
- return converted
- }
- return nil
-}
-
-// 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)
-}
-
-// --- screenshot ---
-
-func cliScreenshot(client *http.Client, base, token string, args []string) {
- params := url.Values{}
- params.Set("raw", "true")
- outFile := ""
- for i := 0; i < len(args); i++ {
- switch args[i] {
- case "-o", "--output":
- if i+1 < len(args) {
- i++
- outFile = args[i]
- }
- case "--quality", "-q":
- if i+1 < len(args) {
- i++
- params.Set("quality", args[i])
- }
- case "--tab":
- if i+1 < len(args) {
- i++
- params.Set("tabId", args[i])
- }
- }
- }
-
- if outFile == "" {
- outFile = fmt.Sprintf("screenshot-%s.jpg", time.Now().Format("20060102-150405"))
- }
-
- data := doGetRaw(client, base, token, "/screenshot", params)
- if data == nil {
- return
- }
- if err := os.WriteFile(outFile, data, 0600); err != nil {
- fatal("Write failed: %v", err)
- }
- fmt.Println(styleStdout(cliSuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
-}
-
-// --- evaluate ---
-
-func cliEvaluate(client *http.Client, base, token string, args []string) {
- if len(args) < 1 {
- fatal("Usage: pinchtab eval <expression>")
- }
- expr := strings.Join(args, " ")
- doPost(client, base, token, "/evaluate", map[string]any{
- "expression": expr,
- })
-}
-
-// --- pdf ---
-
-func cliPDF(client *http.Client, base, token string, args []string) {
- params := url.Values{}
- params.Set("raw", "true")
- outFile := ""
- tabID := ""
- for i := 0; i < len(args); i++ {
- switch args[i] {
- case "-o", "--output":
- if i+1 < len(args) {
- i++
- outFile = args[i]
- }
- case "--landscape":
- params.Set("landscape", "true")
- case "--scale":
- if i+1 < len(args) {
- i++
- params.Set("scale", args[i])
- }
- case "--tab":
- if i+1 < len(args) {
- i++
- tabID = args[i]
- }
- // Paper dimensions
- case "--paper-width":
- if i+1 < len(args) {
- i++
- params.Set("paperWidth", args[i])
- }
- case "--paper-height":
- if i+1 < len(args) {
- i++
- params.Set("paperHeight", args[i])
- }
- // Margins
- case "--margin-top":
- if i+1 < len(args) {
- i++
- params.Set("marginTop", args[i])
- }
- case "--margin-bottom":
- if i+1 < len(args) {
- i++
- params.Set("marginBottom", args[i])
- }
- case "--margin-left":
- if i+1 < len(args) {
- i++
- params.Set("marginLeft", args[i])
- }
- case "--margin-right":
- if i+1 < len(args) {
- i++
- params.Set("marginRight", args[i])
- }
- // Content options
- case "--page-ranges":
- if i+1 < len(args) {
- i++
- params.Set("pageRanges", args[i])
- }
- case "--prefer-css-page-size":
- params.Set("preferCSSPageSize", "true")
- // Header/Footer
- case "--display-header-footer":
- params.Set("displayHeaderFooter", "true")
- case "--header-template":
- if i+1 < len(args) {
- i++
- params.Set("headerTemplate", args[i])
- }
- case "--footer-template":
- if i+1 < len(args) {
- i++
- params.Set("footerTemplate", args[i])
- }
- // Accessibility
- case "--generate-tagged-pdf":
- params.Set("generateTaggedPDF", "true")
- case "--generate-document-outline":
- params.Set("generateDocumentOutline", "true")
- // Output options
- case "--file-output":
- params.Del("raw")
- params.Set("output", "file")
- case "--path":
- if i+1 < len(args) {
- i++
- params.Set("path", args[i])
- }
- case "--raw":
- params.Set("raw", "true")
- }
- }
-
- if outFile == "" {
- outFile = fmt.Sprintf("page-%s.pdf", time.Now().Format("20060102-150405"))
- }
-
- var data []byte
- if tabID != "" {
- data = doGetRaw(client, base, token, fmt.Sprintf("/tabs/%s/pdf", tabID), params)
- } else {
- data = doGetRaw(client, base, token, "/pdf", params)
- }
- if data == nil {
- return
- }
- if err := os.WriteFile(outFile, data, 0600); err != nil {
- fatal("Write failed: %v", err)
- }
- fmt.Println(styleStdout(cliSuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
-}
-
-// --- quick command ---
-
-func cliQuick(client *http.Client, base, token string, args []string) {
- if len(args) < 1 {
- fatal("Usage: pinchtab quick <url>")
- }
-
- fmt.Println(styleStdout(cliHeadingStyle, 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(styleStdout(cliHeadingStyle, "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", styleStdout(cliMutedStyle, "Title:"), styleStdout(cliValueStyle, title))
- }
- if urlStr, ok := navResult["url"].(string); ok {
- fmt.Printf("%s %s\n", styleStdout(cliMutedStyle, "URL:"), styleStdout(cliValueStyle, urlStr))
- }
-
- fmt.Println()
- fmt.Println(styleStdout(cliHeadingStyle, "Quick actions"))
- fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab click <ref>"), styleStdout(cliMutedStyle, "# Click an element (use refs from above)"))
- fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab type <ref> <text>"), styleStdout(cliMutedStyle, "# Type into input field"))
- fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab screenshot"), styleStdout(cliMutedStyle, "# Take a screenshot"))
- fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab pdf --tab <id> -o output.pdf"), styleStdout(cliMutedStyle, "# Save tab as PDF"))
-}
-
-// --- health ---
-
-func cliHealth(client *http.Client, base, token string) {
- doGet(client, base, token, "/health", nil)
-}
-
-// --- instance ---
-
-func cliInstance(client *http.Client, base, token string, args []string) {
- if len(args) < 1 {
- fatal("Usage: pinchtab instance <subcommand> [options]\nSubcommands: start, launch (alias), navigate, logs, stop")
- }
-
- subCmd := args[0]
- subArgs := args[1:]
-
- switch subCmd {
- case "start", "launch": // "start" is new Phase 2 API, "launch" is legacy
- cliInstanceStart(client, base, token, subArgs)
- case "navigate":
- cliInstanceNavigate(client, base, token, subArgs)
- case "logs":
- cliInstanceLogs(client, base, token, subArgs)
- case "stop":
- cliInstanceStop(client, base, token, subArgs)
- default:
- fatal("Unknown subcommand: %s", subCmd)
- }
-}
-
-func cliInstanceStart(client *http.Client, base, token string, args []string) {
- body := map[string]any{}
-
- for i := 0; i < len(args); i++ {
- switch args[i] {
- case "--profileId":
- if i+1 < len(args) {
- body["profileId"] = args[i+1]
- i++
- }
- case "--mode":
- if i+1 < len(args) {
- body["mode"] = args[i+1]
- i++
- }
- case "--port":
- if i+1 < len(args) {
- body["port"] = args[i+1]
- i++
- }
- }
- }
-
- // Use new /instances/start endpoint if available, fall back to /instances/launch for backward compat
- endpoint := "/instances/start"
- doPost(client, base, token, endpoint, body)
-}
-
-func cliInstanceNavigate(client *http.Client, base, token string, args []string) {
- if len(args) < 2 {
- fatal("Usage: pinchtab instance navigate <instance-id> <url>")
- }
-
- instID := args[0]
- targetURL := args[1]
-
- // 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{
- "url": "about:blank",
- })
- tabID, _ := openResp["tabId"].(string)
- if tabID == "" {
- 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{
- "url": targetURL,
- })
-}
-
-func cliInstanceLogs(client *http.Client, base, token string, args []string) {
- var instID string
-
- // Support both positional argument and --id flag
- if len(args) == 0 {
- fatal("Usage: pinchtab instance logs <instance-id> OR pinchtab instance logs --id <instance-id>")
- }
-
- // Check if first arg is --id flag
- if args[0] == "--id" {
- if len(args) < 2 {
- fatal("Usage: --id requires instance ID")
- }
- instID = args[1]
- } else {
- // Positional argument (backward compat)
- instID = args[0]
- }
-
- logs := doGetRaw(client, base, token, fmt.Sprintf("/instances/%s/logs", instID), nil)
- fmt.Println(string(logs))
-}
-
-func cliInstanceStop(client *http.Client, base, token string, args []string) {
- var instID string
-
- // Support both positional argument and --id flag
- if len(args) == 0 {
- fatal("Usage: pinchtab instance stop <instance-id> OR pinchtab instance stop --id <instance-id>")
- }
-
- // Check if first arg is --id flag
- if args[0] == "--id" {
- if len(args) < 2 {
- fatal("Usage: --id requires instance ID")
- }
- instID = args[1]
- } else {
- // Positional argument (backward compat)
- instID = args[0]
- }
-
- // doPost auto-prints JSON response
- doPost(client, base, token, fmt.Sprintf("/instances/%s/stop", instID), nil)
-}
-
-// --- instances ---
-
-func cliInstances(client *http.Client, base, token string) {
- body := 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)
- }
-
- // Transform to cleaner output format
- output := make([]map[string]any, len(instances))
- for i, inst := range instances {
- id, _ := inst["id"].(string)
- port, _ := inst["port"].(string)
- headless, _ := inst["headless"].(bool)
- status, _ := inst["status"].(string)
-
- mode := "headless"
- if !headless {
- mode = "headed"
- }
-
- output[i] = map[string]any{
- "id": id,
- "port": port,
- "mode": mode,
- "status": status,
- }
- }
-
- // Output as JSON
- data, _ := json.MarshalIndent(output, "", " ")
- fmt.Println(string(data))
-}
-
-// --- profiles ---
-
-func cliProfiles(client *http.Client, base, token string) {
- result := doGet(client, base, token, "/profiles", nil)
-
- // Display profiles in a friendly format
- if profiles, ok := result["profiles"].([]interface{}); ok && len(profiles) > 0 {
- fmt.Println()
- for _, prof := range profiles {
- if m, ok := prof.(map[string]any); ok {
- name, _ := m["name"].(string)
-
- fmt.Printf("👤 %s\n", name)
- }
- }
- fmt.Println()
- } else {
- fmt.Println("No profiles available")
- }
-}
-
-// --- helpers ---
-
-func doGet(client *http.Client, base, token, path string, params url.Values) map[string]any {
- u := base + path
- if len(params) > 0 {
- u += "?" + params.Encode()
- }
- req, _ := http.NewRequest("GET", u, nil)
- if token != "" {
- req.Header.Set("Authorization", "Bearer "+token)
- }
- resp, err := client.Do(req)
- if err != nil {
- fatal("Request failed: %v", err)
- }
- defer func() { _ = resp.Body.Close() }()
- body, _ := io.ReadAll(resp.Body)
-
- if resp.StatusCode >= 400 {
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("Error %d: %s", resp.StatusCode, string(body))))
- os.Exit(1)
- }
-
- // Pretty-print JSON if possible
- var buf bytes.Buffer
- if json.Indent(&buf, body, "", " ") == nil {
- fmt.Println(buf.String())
- } else {
- fmt.Println(string(body))
- }
-
- // Parse and return result
- var result map[string]any
- if err := json.Unmarshal(body, &result); err != nil {
- log.Printf("warning: error unmarshaling response: %v", err)
- }
- return result
-}
-
-func doGetRaw(client *http.Client, base, token, path string, params url.Values) []byte {
- u := base + path
- if len(params) > 0 {
- u += "?" + params.Encode()
- }
- req, _ := http.NewRequest("GET", u, nil)
- if token != "" {
- req.Header.Set("Authorization", "Bearer "+token)
- }
- resp, err := client.Do(req)
- if err != nil {
- 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, styleStderr(cliErrorStyle, fmt.Sprintf("Error %d: %s", resp.StatusCode, string(body))))
- os.Exit(1)
- }
- return body
-}
-
-func doPost(client *http.Client, base, token, path string, body map[string]any) map[string]any {
- data, _ := json.Marshal(body)
- req, _ := http.NewRequest("POST", base+path, bytes.NewReader(data))
- req.Header.Set("Content-Type", "application/json")
- if token != "" {
- req.Header.Set("Authorization", "Bearer "+token)
- }
- resp, err := client.Do(req)
- if err != nil {
- fatal("Request failed: %v", err)
- }
- defer func() { _ = resp.Body.Close() }()
- respBody, _ := io.ReadAll(resp.Body)
-
- if resp.StatusCode >= 400 {
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("Error %d: %s", resp.StatusCode, string(respBody))))
- os.Exit(1)
- }
-
- var buf bytes.Buffer
- if json.Indent(&buf, respBody, "", " ") == nil {
- fmt.Println(buf.String())
- } else {
- fmt.Println(string(respBody))
- }
-
- // Parse and return result for suggestions
- var result map[string]any
- if err := json.Unmarshal(respBody, &result); err != nil {
- log.Printf("warning: error unmarshaling response: %v", err)
- }
- return result
-}
-
-// 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, styleStderr(cliErrorStyle, fmt.Sprintf("Pinchtab server is not running on %s", base)))
- fmt.Fprintln(os.Stderr)
- fmt.Fprintln(os.Stderr, styleStderr(cliHeadingStyle, "To start the server"))
- fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab"), styleStderr(cliMutedStyle, "# Run in foreground (recommended for beginners)"))
- fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab &"), styleStderr(cliMutedStyle, "# Run in background"))
- fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "PINCHTAB_PORT=9868 pinchtab"), styleStderr(cliMutedStyle, "# Use different port"))
- fmt.Fprintln(os.Stderr)
- fmt.Fprintln(os.Stderr, styleStderr(cliHeadingStyle, "Then try your command again"))
- fmt.Fprintf(os.Stderr, " %s\n", styleStderr(cliCommandStyle, strings.Join(os.Args, " ")))
- fmt.Fprintln(os.Stderr)
- fmt.Fprintf(os.Stderr, "%s %s\n", styleStderr(cliMutedStyle, "Learn more:"), styleStderr(cliCommandStyle, "https://github.com/pinchtab/pinchtab#quick-start"))
- return false
- }
- // Other connection errors
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("Cannot connect to Pinchtab server: %v", err)))
- return false
- }
- defer func() { _ = resp.Body.Close() }()
-
- if resp.StatusCode == 401 {
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, "Authentication required. Set PINCHTAB_TOKEN."))
- return false
- }
-
- if resp.StatusCode >= 400 {
- body, _ := io.ReadAll(resp.Body)
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, 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, styleStderr(cliHeadingStyle, "Next steps"))
- fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab snap"), styleStderr(cliMutedStyle, "# See page structure"))
- fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab screenshot"), styleStderr(cliMutedStyle, "# Capture visual"))
- fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab click <ref>"), styleStderr(cliMutedStyle, "# Click an element"))
- fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab pdf --tab <id> -o output.pdf"), styleStderr(cliMutedStyle, "# Save tab as PDF"))
-
- case "snap", "snapshot":
- refs := extractRefs(result)
- if len(refs) > 0 {
- fmt.Fprintln(os.Stderr)
- fmt.Fprintln(os.Stderr, styleStderr(cliHeadingStyle, fmt.Sprintf("Found %d interactive elements", len(refs))))
- for i, ref := range refs[:min(3, len(refs))] {
- fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, fmt.Sprintf("pinchtab click %s", ref.id)), styleStderr(cliMutedStyle, "# "+ref.desc))
- if i >= 2 {
- break
- }
- }
- if len(refs) > 3 {
- fmt.Fprintf(os.Stderr, " %s\n", styleStderr(cliMutedStyle, fmt.Sprintf("... and %d more", len(refs)-3)))
- }
- }
-
- case "click", "type", "fill":
- fmt.Fprintln(os.Stderr)
- fmt.Fprintln(os.Stderr, styleStderr(cliHeadingStyle, "Action completed"))
- fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab snap"), styleStderr(cliMutedStyle, "# See updated page"))
- fmt.Fprintf(os.Stderr, " %s %s\n", styleStderr(cliCommandStyle, "pinchtab screenshot"), styleStderr(cliMutedStyle, "# 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
-}
-
-// resolveInstanceBase fetches the named instance from the orchestrator and returns
-// a base URL pointing directly at that instance's API port.
-func resolveInstanceBase(orchBase, token, instanceID, bind string) string {
- c := &http.Client{Timeout: 10 * time.Second}
- body := doGetRaw(c, orchBase, token, fmt.Sprintf("/instances/%s", instanceID), nil)
-
- var inst struct {
- Port string `json:"port"`
- }
- if err := json.Unmarshal(body, &inst); err != nil {
- fatal("failed to parse instance %q: %v", instanceID, err)
- }
- if inst.Port == "" {
- fatal("instance %q has no port assigned (is it still starting?)", instanceID)
- }
- return fmt.Sprintf("http://%s:%s", bind, inst.Port)
-}
-
-func fatal(format string, args ...any) {
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf(format, args...)))
- os.Exit(1)
-}
diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.go
index 133f09a7..4bd91329 100644
--- a/cmd/pinchtab/cmd_cli.go
+++ b/cmd/pinchtab/cmd_cli.go
@@ -7,6 +7,7 @@ import (
"strings"
"time"
+ "github.com/pinchtab/pinchtab/internal/browsercli"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/spf13/cobra"
)
@@ -18,7 +19,7 @@ var quickCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliQuick(client, base, token, args)
+ browsercli.Quick(client, base, token, args)
})
},
}
@@ -30,7 +31,7 @@ var navCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliNavigate(client, base, token, args)
+ browsercli.Navigate(client, base, token, args)
})
},
}
@@ -41,7 +42,7 @@ var snapCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliSnapshot(client, base, token, args)
+ browsercli.Snapshot(client, base, token, args)
})
},
}
@@ -53,7 +54,7 @@ var clickCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliAction(client, base, token, "click", args)
+ browsercli.Action(client, base, token, "click", args)
})
},
}
@@ -65,7 +66,7 @@ var typeCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliAction(client, base, token, "type", args)
+ browsercli.Action(client, base, token, "type", args)
})
},
}
@@ -76,7 +77,7 @@ var screenshotCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliScreenshot(client, base, token, args)
+ browsercli.Screenshot(client, base, token, args)
})
},
}
@@ -87,7 +88,7 @@ var tabsCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliTabs(client, base, token, args)
+ browsercli.Tabs(client, base, token, args)
})
},
}
@@ -98,7 +99,7 @@ var instancesCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliInstances(client, base, token)
+ browsercli.Instances(client, base, token)
})
},
}
@@ -109,7 +110,7 @@ var healthCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliHealth(client, base, token)
+ browsercli.Health(client, base, token)
})
},
}
@@ -121,7 +122,7 @@ var pressCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliAction(client, base, token, "press", args)
+ browsercli.Action(client, base, token, "press", args)
})
},
}
@@ -133,7 +134,7 @@ var fillCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliAction(client, base, token, "fill", args)
+ browsercli.Action(client, base, token, "fill", args)
})
},
}
@@ -145,7 +146,7 @@ var hoverCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliAction(client, base, token, "hover", args)
+ browsercli.Action(client, base, token, "hover", args)
})
},
}
@@ -157,7 +158,7 @@ var scrollCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliAction(client, base, token, "scroll", args)
+ browsercli.Action(client, base, token, "scroll", args)
})
},
}
@@ -169,7 +170,7 @@ var evalCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliEvaluate(client, base, token, args)
+ browsercli.Evaluate(client, base, token, args)
})
},
}
@@ -180,7 +181,7 @@ var pdfCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliPDF(client, base, token, args)
+ browsercli.PDF(client, base, token, args)
})
},
}
@@ -191,7 +192,7 @@ var textCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliText(client, base, token, args)
+ browsercli.Text(client, base, token, args)
})
},
}
@@ -202,7 +203,7 @@ var profilesCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliProfiles(client, base, token)
+ browsercli.Profiles(client, base, token)
})
},
}
@@ -238,7 +239,7 @@ func init() {
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliInstanceStart(client, base, token, args)
+ browsercli.InstanceStart(client, base, token, args)
})
},
})
@@ -249,7 +250,7 @@ func init() {
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliInstanceNavigate(client, base, token, args)
+ browsercli.InstanceNavigate(client, base, token, args)
})
},
})
@@ -260,7 +261,7 @@ func init() {
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliInstanceStop(client, base, token, args)
+ browsercli.InstanceStop(client, base, token, args)
})
},
})
@@ -271,7 +272,7 @@ func init() {
Run: func(cmd *cobra.Command, args []string) {
cfg := config.Load()
runCLIWith(cfg, func(client *http.Client, base, token string) {
- cliInstanceLogs(client, base, token, args)
+ browsercli.InstanceLogs(client, base, token, args)
})
},
})
@@ -339,44 +340,44 @@ func runCLI(cfg *config.RuntimeConfig) {
base := orchBase
if instanceID != "" {
- base = resolveInstanceBase(orchBase, token, instanceID, cfg.Bind)
+ base = browsercli.ResolveInstanceBase(orchBase, token, instanceID, cfg.Bind)
}
client := &http.Client{Timeout: 30 * time.Second}
if cmd != "help" {
- if !checkServerAndGuide(client, base, token) {
+ if !browsercli.CheckServerAndGuide(client, base, token) {
return
}
}
switch cmd {
case "nav", "navigate":
- cliNavigate(client, base, token, args)
+ browsercli.Navigate(client, base, token, args)
case "snap", "snapshot":
- cliSnapshot(client, base, token, args)
+ browsercli.Snapshot(client, base, token, args)
case "click", "type", "press", "fill", "hover", "scroll", "select", "focus":
- cliAction(client, base, token, cmd, args)
+ browsercli.Action(client, base, token, cmd, args)
case "text":
- cliText(client, base, token, args)
+ browsercli.Text(client, base, token, args)
case "tabs", "tab":
- cliTabs(client, base, token, args)
+ browsercli.Tabs(client, base, token, args)
case "screenshot", "ss":
- cliScreenshot(client, base, token, args)
+ browsercli.Screenshot(client, base, token, args)
case "eval", "evaluate":
- cliEvaluate(client, base, token, args)
+ browsercli.Evaluate(client, base, token, args)
case "pdf":
- cliPDF(client, base, token, args)
+ browsercli.PDF(client, base, token, args)
case "health":
- cliHealth(client, base, token)
+ browsercli.Health(client, base, token)
case "instance":
- cliInstance(client, base, token, args)
+ browsercli.Instance(client, base, token, args)
case "instances":
- cliInstances(client, base, token)
+ browsercli.Instances(client, base, token)
case "profiles":
- cliProfiles(client, base, token)
+ browsercli.Profiles(client, base, token)
case "quick":
- cliQuick(client, base, token, args)
+ browsercli.Quick(client, base, token, args)
case "help":
cliHelp()
}
diff --git a/cmd/pinchtab/cmd_cli_test.go b/cmd/pinchtab/cmd_cli_test.go
index adc2ef2e..1a23b172 100644
--- a/cmd/pinchtab/cmd_cli_test.go
+++ b/cmd/pinchtab/cmd_cli_test.go
@@ -8,31 +8,9 @@ import (
"os"
"strings"
"testing"
-)
-
-func TestIsCLICommand(t *testing.T) {
- valid := []string{"nav", "navigate", "snap", "snapshot", "click", "type",
- "press", "fill", "hover", "scroll", "select", "focus",
- "text", "tabs", "tab", "screenshot", "ss", "eval", "evaluate",
- "pdf", "health", "quick"}
-
- for _, cmd := range valid {
- if !isCLICommand(cmd) {
- t.Errorf("expected %q to be a CLI command", cmd)
- }
- }
- invalid := []string{"dashboard", "connect", "config", "server", "run", ""}
- for _, cmd := range invalid {
- if isCLICommand(cmd) {
- t.Errorf("expected %q to NOT be a CLI command", cmd)
- }
- }
-}
-
-func TestPrintHelp(t *testing.T) {
- printHelp()
-}
+ "github.com/pinchtab/pinchtab/internal/browsercli"
+)
// mockServer records the last request and returns a configurable response.
type mockServer struct {
@@ -73,7 +51,7 @@ func TestCLINavigate(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliNavigate(client, m.base(), "", []string{"https://pinchtab.com"})
+ browsercli.Navigate(client, m.base(), "", []string{"https://pinchtab.com"})
if m.lastMethod != "POST" {
t.Errorf("expected POST, got %s", m.lastMethod)
}
@@ -92,7 +70,7 @@ func TestCLINavigateWithFlags(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliNavigate(client, m.base(), "", []string{"https://pinchtab.com", "--new-tab", "--block-images"})
+ 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 {
@@ -108,7 +86,7 @@ func TestCLINavigateWithBlockAds(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliNavigate(client, m.base(), "", []string{"https://pinchtab.com", "--block-ads"})
+ 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 {
@@ -122,7 +100,7 @@ func TestCLIInstanceNavigateUsesTabRoute(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliInstanceNavigate(client, m.base(), "", []string{"inst-123", "https://pinchtab.com"})
+ browsercli.InstanceNavigate(client, m.base(), "", []string{"inst-123", "https://pinchtab.com"})
if m.lastMethod != "POST" {
t.Errorf("expected POST, got %s", m.lastMethod)
@@ -146,7 +124,7 @@ func TestCLISnapshot(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliSnapshot(client, m.base(), "", []string{"-i", "-c"})
+ browsercli.Snapshot(client, m.base(), "", []string{"-i", "-c"})
if m.lastMethod != "GET" {
t.Errorf("expected GET, got %s", m.lastMethod)
}
@@ -166,7 +144,7 @@ func TestCLISnapshotDiff(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliSnapshot(client, m.base(), "", []string{"--diff", "--selector", "main", "--max-tokens", "2000", "--depth", "5"})
+ 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)
}
@@ -186,7 +164,7 @@ func TestCLISnapshotTabId(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliSnapshot(client, m.base(), "", []string{"--tab", "ABC123"})
+ browsercli.Snapshot(client, m.base(), "", []string{"--tab", "ABC123"})
if !strings.Contains(m.lastQuery, "tabId=ABC123") {
t.Errorf("expected tabId=ABC123, got %s", m.lastQuery)
}
@@ -199,7 +177,7 @@ func TestCLIClick(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliAction(client, m.base(), "", "click", []string{"e5"})
+ browsercli.Action(client, m.base(), "", "click", []string{"e5"})
if m.lastPath != "/action" {
t.Errorf("expected /action, got %s", m.lastPath)
}
@@ -218,7 +196,7 @@ func TestCLIClickWaitNav(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliAction(client, m.base(), "", "click", []string{"e5", "--wait-nav"})
+ 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 {
@@ -231,7 +209,7 @@ func TestCLIType(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliAction(client, m.base(), "", "type", []string{"e12", "hello", "world"})
+ 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" {
@@ -250,7 +228,7 @@ func TestCLIPress(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliAction(client, m.base(), "", "press", []string{"Enter"})
+ browsercli.Action(client, m.base(), "", "press", []string{"Enter"})
var body map[string]any
_ = json.Unmarshal([]byte(m.lastBody), &body)
if body["key"] != "Enter" {
@@ -265,7 +243,7 @@ func TestCLIClickWithCSS(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliAction(client, m.base(), "", "click", []string{"--css", "button.submit"})
+ 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" {
@@ -283,7 +261,7 @@ func TestCLIClickWithCSS_AndWaitNav(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliAction(client, m.base(), "", "click", []string{"--wait-nav", "--css", "#login-btn"})
+ 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" {
@@ -300,7 +278,7 @@ func TestCLIHoverWithCSS(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliAction(client, m.base(), "", "hover", []string{"--css", ".nav-item"})
+ 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" {
@@ -314,7 +292,7 @@ func TestCLIFocusWithCSS(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliAction(client, m.base(), "", "focus", []string{"--css", "input[name='email']"})
+ 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']" {
@@ -329,7 +307,7 @@ func TestCLIClickRefStillWorks(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliAction(client, m.base(), "", "click", []string{"e42"})
+ browsercli.Action(client, m.base(), "", "click", []string{"e42"})
var body map[string]any
_ = json.Unmarshal([]byte(m.lastBody), &body)
if body["ref"] != "e42" {
@@ -346,7 +324,7 @@ func TestCLIFill(t *testing.T) {
client := m.server.Client()
// Fill with ref
- cliAction(client, m.base(), "", "fill", []string{"e3", "test value"})
+ 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" {
@@ -357,7 +335,7 @@ func TestCLIFill(t *testing.T) {
}
// Fill with selector
- cliAction(client, m.base(), "", "fill", []string{"#email", "[email protected]"})
+ 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"])
@@ -370,7 +348,7 @@ func TestCLIScroll(t *testing.T) {
client := m.server.Client()
// Scroll by ref
- cliAction(client, m.base(), "", "scroll", []string{"e20"})
+ browsercli.Action(client, m.base(), "", "scroll", []string{"e20"})
var body map[string]any
_ = json.Unmarshal([]byte(m.lastBody), &body)
if body["ref"] != "e20" {
@@ -378,14 +356,14 @@ func TestCLIScroll(t *testing.T) {
}
// Scroll by pixels (now sends int, not string)
- cliAction(client, m.base(), "", "scroll", []string{"800"})
+ 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.
- cliAction(client, m.base(), "", "scroll", []string{"down"})
+ 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"])
@@ -397,7 +375,7 @@ func TestCLISelect(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliAction(client, m.base(), "", "select", []string{"e10", "option2"})
+ browsercli.Action(client, m.base(), "", "select", []string{"e10", "option2"})
var body map[string]any
_ = json.Unmarshal([]byte(m.lastBody), &body)
if body["ref"] != "e10" {
@@ -416,7 +394,7 @@ func TestCLIText(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliText(client, m.base(), "", nil)
+ browsercli.Text(client, m.base(), "", nil)
if m.lastPath != "/text" {
t.Errorf("expected /text, got %s", m.lastPath)
}
@@ -427,7 +405,7 @@ func TestCLITextRaw(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliText(client, m.base(), "", []string{"--raw"})
+ browsercli.Text(client, m.base(), "", []string{"--raw"})
if !strings.Contains(m.lastQuery, "mode=raw") {
t.Errorf("expected mode=raw, got %s", m.lastQuery)
}
@@ -438,7 +416,7 @@ func TestCLITextTab(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliText(client, m.base(), "", []string{"--tab", "TAB1"})
+ browsercli.Text(client, m.base(), "", []string{"--tab", "TAB1"})
if !strings.Contains(m.lastQuery, "tabId=TAB1") {
t.Errorf("expected tabId=TAB1, got %s", m.lastQuery)
}
@@ -452,7 +430,7 @@ func TestCLITabsList(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliTabs(client, m.base(), "", nil)
+ browsercli.Tabs(client, m.base(), "", nil)
if m.lastPath != "/tabs" {
t.Errorf("expected /tabs, got %s", m.lastPath)
}
@@ -463,7 +441,7 @@ func TestCLITabsNew(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliTabs(client, m.base(), "", []string{"new", "https://pinchtab.com"})
+ browsercli.Tabs(client, m.base(), "", []string{"new", "https://pinchtab.com"})
if m.lastPath != "/tab" {
t.Errorf("expected /tab, got %s", m.lastPath)
}
@@ -485,7 +463,7 @@ func TestCLIEvaluate(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliEvaluate(client, m.base(), "", []string{"document.title"})
+ browsercli.Evaluate(client, m.base(), "", []string{"document.title"})
if m.lastPath != "/evaluate" {
t.Errorf("expected /evaluate, got %s", m.lastPath)
}
@@ -501,7 +479,7 @@ func TestCLIEvaluateMultiWord(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliEvaluate(client, m.base(), "", []string{"1", "+", "2"})
+ browsercli.Evaluate(client, m.base(), "", []string{"1", "+", "2"})
var body map[string]any
_ = json.Unmarshal([]byte(m.lastBody), &body)
if body["expression"] != "1 + 2" {
@@ -518,7 +496,7 @@ func TestCLIScreenshot(t *testing.T) {
client := m.server.Client()
outFile := t.TempDir() + "/test.jpg"
- cliScreenshot(client, m.base(), "", []string{"-o", outFile, "-q", "50"})
+ browsercli.Screenshot(client, m.base(), "", []string{"-o", outFile, "-q", "50"})
if m.lastPath != "/screenshot" {
t.Errorf("expected /screenshot, got %s", m.lastPath)
}
@@ -543,7 +521,7 @@ func TestCLIPDF(t *testing.T) {
client := m.server.Client()
outFile := t.TempDir() + "/test.pdf"
- cliPDF(client, m.base(), "", []string{"-o", outFile, "--tab", "tab-abc", "--landscape", "--scale", "0.8"})
+ 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)
}
@@ -589,7 +567,7 @@ func TestCLIPDFAllOptions(t *testing.T) {
"--tab", "tab-123",
}
- cliPDF(client, m.base(), "", args)
+ browsercli.PDF(client, m.base(), "", args)
if m.lastPath != "/tabs/tab-123/pdf" {
t.Errorf("expected /tabs/tab-123/pdf, got %s", m.lastPath)
}
@@ -635,7 +613,7 @@ func TestCLIHealth(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliHealth(client, m.base(), "")
+ browsercli.Health(client, m.base(), "")
if m.lastPath != "/health" {
t.Errorf("expected /health, got %s", m.lastPath)
}
@@ -648,7 +626,7 @@ func TestCLIAuthHeader(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliHealth(client, m.base(), "my-secret-token")
+ 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)
@@ -660,7 +638,7 @@ func TestCLINoAuthHeader(t *testing.T) {
defer m.close()
client := m.server.Client()
- cliHealth(client, m.base(), "")
+ browsercli.Health(client, m.base(), "")
auth := m.lastHeaders.Get("Authorization")
if auth != "" {
t.Errorf("expected no auth header, got %q", auth)
@@ -676,7 +654,7 @@ func TestDoGetPrettyPrintsJSON(t *testing.T) {
client := m.server.Client()
// Just verify it doesn't panic with valid JSON
- doGet(client, m.base(), "", "/health", nil)
+ browsercli.DoGet(client, m.base(), "", "/health", nil)
}
func TestDoGetNonJSON(t *testing.T) {
@@ -686,7 +664,7 @@ func TestDoGetNonJSON(t *testing.T) {
client := m.server.Client()
// Should handle non-JSON gracefully
- doGet(client, m.base(), "", "/text", nil)
+ browsercli.DoGet(client, m.base(), "", "/text", nil)
}
func TestDoPostContentType(t *testing.T) {
@@ -694,7 +672,7 @@ func TestDoPostContentType(t *testing.T) {
defer m.close()
client := m.server.Client()
- _ = doPost(client, m.base(), "", "/action", map[string]any{"kind": "click"})
+ _ = 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)
@@ -710,7 +688,7 @@ func TestCheckServerAndGuide(t *testing.T) {
defer m.close()
client := m.server.Client()
- result := checkServerAndGuide(client, m.base(), "")
+ result := browsercli.CheckServerAndGuide(client, m.base(), "")
if !result {
t.Error("expected checkServerAndGuide to return true for working server")
}
@@ -727,7 +705,7 @@ func TestCheckServerAndGuide(t *testing.T) {
r, w, _ := os.Pipe()
os.Stderr = w
- result2 := checkServerAndGuide(client2, m2.base(), "")
+ result2 := browsercli.CheckServerAndGuide(client2, m2.base(), "")
_ = w.Close()
os.Stderr = oldStderr
@@ -751,7 +729,7 @@ func TestResolveInstanceBase(t *testing.T) {
client := orch.server.Client()
_ = client // resolveInstanceBase builds its own client
- got := resolveInstanceBase(orch.base(), "", "abc123", "127.0.0.1")
+ 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)
@@ -767,7 +745,7 @@ func TestResolveInstanceBase_ForwardsToken(t *testing.T) {
orch.response = `{"id":"xyz","port":"9902","status":"running"}`
defer orch.close()
- resolveInstanceBase(orch.base(), "my-token", "xyz", "localhost")
+ browsercli.ResolveInstanceBase(orch.base(), "my-token", "xyz", "localhost")
authHeader := orch.lastHeaders.Get("Authorization")
if authHeader != "Bearer my-token" {
diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
index 8408c90c..96ab0e87 100644
--- a/cmd/pinchtab/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -13,6 +13,7 @@ import (
"syscall"
"time"
+ "github.com/pinchtab/pinchtab/internal/cliui"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/dashboard"
"github.com/pinchtab/pinchtab/internal/handlers"
@@ -137,8 +138,8 @@ func runDashboard(cfg *config.RuntimeConfig) {
})
if IsDaemonRunning() && checkPinchTabRunning(dashPort, cfg.Token) {
- fmt.Println(styleStdout(cliWarningStyle, fmt.Sprintf(" pinchtab already running as a daemon on port %s", dashPort)))
- fmt.Println(styleStdout(cliMutedStyle, " Stop the daemon first with `pinchtab daemon stop` to run in the foreground."))
+ 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."))
fmt.Println()
os.Exit(0)
}
diff --git a/cmd/pinchtab/cmd_onboard.go b/cmd/pinchtab/cmd_onboard.go
index 7ae6bbd7..353f4dd7 100644
--- a/cmd/pinchtab/cmd_onboard.go
+++ b/cmd/pinchtab/cmd_onboard.go
@@ -8,12 +8,12 @@ import (
"os/exec"
"os/user"
"path/filepath"
- "reflect"
"runtime"
"strings"
"github.com/charmbracelet/huh"
"github.com/charmbracelet/lipgloss"
+ "github.com/pinchtab/pinchtab/internal/cliui"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/spf13/cobra"
)
@@ -23,60 +23,6 @@ const (
pinchtabLaunchdLabel = "com.pinchtab.pinchtab"
)
-type onboardOptions struct {
- force bool
- installDaemon bool
-}
-
-type onboardConfigStatus string
-
-const (
- onboardConfigCreated onboardConfigStatus = "created"
- onboardConfigRecovered onboardConfigStatus = "recovered"
- onboardConfigVerified onboardConfigStatus = "verified"
-)
-
-type commandRunner interface {
- CombinedOutput(name string, args ...string) ([]byte, error)
-}
-
-type osCommandRunner struct{}
-
-func (osCommandRunner) CombinedOutput(name string, args ...string) ([]byte, error) {
- return exec.Command(name, args...).CombinedOutput()
-}
-
-type daemonEnvironment struct {
- execPath string
- homeDir string
- osName string
- userID string
- xdgConfigHome string
-}
-
-type daemonManager interface {
- Install(execPath, configPath string) (string, error)
- ServicePath() string
- Start() (string, error)
- Restart() (string, error)
- Status() (string, error)
- Stop() (string, error)
- Uninstall() (string, error)
- ManualInstructions() string
- Pid() (string, error)
- Logs(n int) (string, error)
-}
-
-type systemdUserManager struct {
- env daemonEnvironment
- runner commandRunner
-}
-
-type launchdManager struct {
- env daemonEnvironment
- runner commandRunner
-}
-
var onboardCmd = &cobra.Command{
Use: "onboard",
Short: "Guided interactive setup (recommended first run)",
@@ -170,7 +116,7 @@ func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {
manager, err := currentDaemonManager()
if err != nil {
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, err.Error()))
+ fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, err.Error()))
os.Exit(1)
}
@@ -178,17 +124,17 @@ func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {
case "install":
configPath, _, _, err := ensureOnboardConfig(false)
if err != nil {
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))
+ fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))
os.Exit(1)
}
message, err := manager.Install(managerEnvironment(manager).execPath, configPath)
if err != nil {
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))
+ fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))
fmt.Println()
fmt.Println(manager.ManualInstructions())
os.Exit(1)
}
- fmt.Println(styleStdout(cliSuccessStyle, " [ok] ") + message)
+ fmt.Println(cliui.StyleStdout(cliui.SuccessStyle, " [ok] ") + message)
printDaemonFollowUp()
case "start":
printDaemonManagerResult(manager.Start())
@@ -199,70 +145,70 @@ func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {
case "uninstall":
message, err := manager.Uninstall()
if err != nil {
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, err.Error()))
+ fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, err.Error()))
fmt.Println()
fmt.Println(manager.ManualInstructions())
os.Exit(1)
}
- fmt.Println(styleStdout(cliSuccessStyle, " [ok] ") + message)
+ fmt.Println(cliui.StyleStdout(cliui.SuccessStyle, " [ok] ") + message)
default:
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("unknown daemon command: %s", subcommand)))
+ fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("unknown daemon command: %s", subcommand)))
daemonUsage()
os.Exit(2)
}
}
func daemonUsage() {
- fmt.Println(styleStdout(cliHeadingStyle, "Usage:") + " " + styleStdout(cliCommandStyle, "pinchtab daemon <install|start|restart|stop|uninstall>"))
+ fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Usage:") + " " + cliui.StyleStdout(cliui.CommandStyle, "pinchtab daemon <install|start|restart|stop|uninstall>"))
fmt.Println()
- fmt.Println(styleStdout(cliMutedStyle, "Manage the PinchTab user-level background service."))
+ fmt.Println(cliui.StyleStdout(cliui.MutedStyle, "Manage the PinchTab user-level background service."))
fmt.Println()
}
func printDaemonStatusSummary() {
manager, err := currentDaemonManager()
if err != nil {
- fmt.Println(styleStdout(cliErrorStyle, " Error: ")+err.Error())
+ fmt.Println(cliui.StyleStdout(cliui.ErrorStyle, " Error: ") + err.Error())
return
}
installed := IsDaemonInstalled()
running := IsDaemonRunning()
- fmt.Println(styleStdout(cliHeadingStyle, "Daemon status:"))
+ fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Daemon status:"))
- status := styleStdout(cliWarningStyle, "not installed")
+ status := cliui.StyleStdout(cliui.WarningStyle, "not installed")
if installed {
- status = styleStdout(cliSuccessStyle, "installed")
+ status = cliui.StyleStdout(cliui.SuccessStyle, "installed")
}
- fmt.Printf(" %-12s %s\n", styleStdout(cliMutedStyle, "Service:"), status)
+ fmt.Printf(" %-12s %s\n", cliui.StyleStdout(cliui.MutedStyle, "Service:"), status)
- state := styleStdout(cliMutedStyle, "stopped")
+ state := cliui.StyleStdout(cliui.MutedStyle, "stopped")
if running {
- state = styleStdout(cliSuccessStyle, "active (running)")
+ state = cliui.StyleStdout(cliui.SuccessStyle, "active (running)")
}
- fmt.Printf(" %-12s %s\n", styleStdout(cliMutedStyle, "State:"), state)
+ fmt.Printf(" %-12s %s\n", cliui.StyleStdout(cliui.MutedStyle, "State:"), state)
if running {
pid, _ := manager.Pid()
if pid != "" {
- fmt.Printf(" %-12s %s\n", styleStdout(cliMutedStyle, "PID:"), styleStdout(cliValueStyle, pid))
+ fmt.Printf(" %-12s %s\n", cliui.StyleStdout(cliui.MutedStyle, "PID:"), cliui.StyleStdout(cliui.ValueStyle, pid))
}
}
if installed {
- fmt.Printf(" %-12s %s\n", styleStdout(cliMutedStyle, "Path:"), styleStdout(cliValueStyle, manager.ServicePath()))
+ fmt.Printf(" %-12s %s\n", cliui.StyleStdout(cliui.MutedStyle, "Path:"), cliui.StyleStdout(cliui.ValueStyle, manager.ServicePath()))
}
if installed {
logs, err := manager.Logs(5)
if err == nil && strings.TrimSpace(logs) != "" {
fmt.Println()
- fmt.Println(styleStdout(cliHeadingStyle, "Recent logs:"))
+ fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Recent logs:"))
lines := strings.Split(logs, "\n")
for _, line := range lines {
if strings.TrimSpace(line) != "" {
- fmt.Printf(" %s\n", styleStdout(cliMutedStyle, line))
+ fmt.Printf(" %s\n", cliui.StyleStdout(cliui.MutedStyle, line))
}
}
}
@@ -272,11 +218,11 @@ func printDaemonStatusSummary() {
func printDaemonManagerResult(message string, err error) {
if err != nil {
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, err.Error()))
+ fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, err.Error()))
os.Exit(1)
}
if strings.HasPrefix(message, "Installed") || strings.HasPrefix(message, "Pinchtab daemon") {
- fmt.Println(styleStdout(cliSuccessStyle, " [ok] ") + message)
+ fmt.Println(cliui.StyleStdout(cliui.SuccessStyle, " [ok] ") + message)
} else {
// For status, it might be a block of text
fmt.Println(message)
@@ -284,7 +230,7 @@ func printDaemonManagerResult(message string, err error) {
}
func ensureOnboardConfig(force bool) (string, *config.RuntimeConfig, onboardConfigStatus, error) {
- fc, configPath, err := config.LoadFileConfig()
+ _, configPath, err := config.LoadFileConfig()
if err != nil {
return "", nil, "", err
}
@@ -301,317 +247,171 @@ func ensureOnboardConfig(force bool) (string, *config.RuntimeConfig, onboardConf
if err := config.SaveFileConfig(&defaults, configPath); err != nil {
return "", nil, "", err
}
- status = onboardConfigCreated
- } else {
- before := securityDefaultsSnapshot(fc)
- applyRecommendedSecurityDefaults(fc)
- after := securityDefaultsSnapshot(fc)
- if !reflect.DeepEqual(before, after) {
- if err := config.SaveFileConfig(fc, configPath); err != nil {
- return "", nil, "", err
- }
+ if !exists {
+ status = onboardConfigCreated
+ } else {
status = onboardConfigRecovered
}
}
- effectiveCfg := config.Load()
- return configPath, effectiveCfg, status, nil
+ return configPath, config.Load(), status, nil
}
-func renderOnboardGuide(configPath string, cfg *config.RuntimeConfig, configStatus onboardConfigStatus, installDaemon bool) string {
- var out bytes.Buffer
+type onboardConfigStatus string
+
+const (
+ onboardConfigCreated onboardConfigStatus = "created"
+ onboardConfigRecovered onboardConfigStatus = "recovered"
+ onboardConfigVerified onboardConfigStatus = "verified"
+)
+
+func runInteractiveOnboard(configPath string, cfg *config.RuntimeConfig, configStatus onboardConfigStatus, installDaemonOpt bool) error {
totalSteps := 6
- if installDaemon {
+ if installDaemonOpt {
totalSteps = 7
}
- fmt.Fprintf(&out, "%s\n\n", renderOnboardTitle())
- out.WriteString(renderOnboardConfigStep(1, totalSteps, configPath, configStatus))
- out.WriteString(renderOnboardAPIAccessStep(2, totalSteps, cfg))
- out.WriteString(renderOnboardSensitiveStep(3, totalSteps, cfg))
- out.WriteString(renderOnboardAttachStep(4, totalSteps, cfg))
- out.WriteString(renderOnboardIDPIStep(5, totalSteps, cfg))
+ fmt.Print("\033[H\033[2J") // Clear screen
+ fmt.Println(renderOnboardTitle())
+ fmt.Println()
- if installDaemon {
- out.WriteString(renderOnboardDaemonStep(6, totalSteps, true))
- out.WriteString(renderOnboardNextStep(7, totalSteps, true))
- return out.String()
- }
- out.WriteString(renderOnboardNextStep(6, totalSteps, false))
- return out.String()
-}
+ // Step 1: Config
+ fmt.Print(renderOnboardConfigStep(1, totalSteps, configPath, configStatus))
-func writeSecurityToggle(out *bytes.Buffer, key string, enabled bool, description string) {
- writeOnboardKV(out, key, fmt.Sprintf("%t", enabled))
- if enabled {
- writeOnboardWarning(out, "Enabled: this exposes %s to any authenticated caller.", description)
- return
- }
- writeOnboardMessage(out, true, "Disabled by default: this keeps %s off until you intentionally opt in.", description)
-}
+ // Step 2: API
+ fmt.Print(renderOnboardAPIAccessStep(2, totalSteps, cfg))
-func summarizeToken(token string) string {
- token = strings.TrimSpace(token)
- if token == "" {
- return "<empty>"
- }
- if len(token) <= 8 {
- return "<set>"
- }
- return token[:4] + "..." + token[len(token)-4:]
-}
+ // Step 3: Capabilities
+ fmt.Print(renderOnboardSensitiveStep(3, totalSteps, cfg))
-func formatStringSlice(values []string) string {
- if len(values) == 0 {
- return "<empty>"
- }
- return strings.Join(values, ", ")
-}
+ // Step 4: Attach
+ fmt.Print(renderOnboardAttachStep(4, totalSteps, cfg))
-func installDaemon(configPath string) (daemonManager, error) {
- manager, err := currentDaemonManager()
- if err != nil {
- return nil, err
- }
- message, err := manager.Install(managerEnvironment(manager).execPath, configPath)
- if err != nil {
- return nil, err
- }
- fmt.Println(message)
- printDaemonFollowUp()
- return manager, nil
-}
-
-func runInteractiveOnboard(configPath string, cfg *config.RuntimeConfig, configStatus onboardConfigStatus, installDaemonRequested bool) error {
- totalSteps := 6
- if installDaemonRequested {
- totalSteps = 7
- }
-
- installDaemonChoice := installDaemonRequested
- runtimeMode := "manual"
- if installDaemonChoice {
- runtimeMode = "daemon"
- }
- selectedSensitiveCaps := enabledSensitiveCapabilityKeys(cfg)
-
- groups := []*huh.Group{
- huh.NewGroup(
- huh.NewNote().
- Title("Config").
- Description(onboardConfigSummary(configPath, configStatus)).
- Next(true).
- NextLabel("Continue"),
- ).Title(fmt.Sprintf("Step 1/%d", totalSteps)).Description("Config and recovery"),
- huh.NewGroup(
- huh.NewNote().
- Title("API access").
- Description(onboardAPIAccessSummary(cfg)).
- Next(true).
- NextLabel("Continue"),
- ).Title(fmt.Sprintf("Step 2/%d", totalSteps)).Description("Bind and token"),
- huh.NewGroup(
- huh.NewMultiSelect[string]().
- Title("Opt in sensitive capabilities").
- Description("Leave everything unselected for the recommended default. Select only what you intentionally want to expose.").
- Options(
- huh.NewOption("evaluate", "evaluate").Selected(cfg.AllowEvaluate),
- huh.NewOption("macro", "macro").Selected(cfg.AllowMacro),
- huh.NewOption("screencast", "screencast").Selected(cfg.AllowScreencast),
- huh.NewOption("download", "download").Selected(cfg.AllowDownload),
- huh.NewOption("upload", "upload").Selected(cfg.AllowUpload),
- ).
- Value(&selectedSensitiveCaps).
- Filtering(false).
- Height(8),
- huh.NewNote().
- Description("These are high-risk endpoint families. If enabled, any authenticated caller can use them.").
- Next(true).
- NextLabel("Continue"),
- ).Title(fmt.Sprintf("Step 3/%d", totalSteps)).Description("High-risk endpoint families"),
- huh.NewGroup(
- huh.NewNote().
- Title("Attach policy").
- Description(onboardAttachSummary(cfg)).
- Next(true).
- NextLabel("Continue"),
- ).Title(fmt.Sprintf("Step 4/%d", totalSteps)).Description("External Chrome attach controls"),
- huh.NewGroup(
- huh.NewNote().
- Title("IDPI protections").
- Description(onboardIDPISummary(cfg)).
- Next(true).
- NextLabel("Continue"),
- ).Title(fmt.Sprintf("Step 5/%d", totalSteps)).Description("Indirect prompt-injection defense"),
- }
-
- modeStep := 6
-
- modeOptions := []huh.Option[string]{
- huh.NewOption("Install background service (recommended)", "daemon"),
- huh.NewOption("Start it manually when needed", "manual"),
- }
- groups = append(groups, huh.NewGroup(
- huh.NewSelect[string]().
- Title("How should PinchTab run?").
- Description("Choose whether onboarding should install a persistent user-level service.").
- Options(modeOptions...).
- Value(&runtimeMode),
- huh.NewNote().
- Title("Background service").
- Description("Daemon mode installs PinchTab once and gives you `pinchtab daemon status/start/restart/stop/uninstall`. Manual mode leaves startup under your control.").
- Next(true).
- NextLabel("Finish wizard"),
- ).Title(fmt.Sprintf("Step %d/%d", modeStep, totalSteps)).Description("Runtime mode"))
-
- form := huh.NewForm(groups...).WithTheme(pinchtabOnboardTheme()).WithWidth(68)
- if err := form.Run(); err != nil {
- if errors.Is(err, huh.ErrUserAborted) {
- fmt.Println("Onboarding stopped at your request.")
- return nil
- }
- return err
- }
-
- if err := saveSelectedSensitiveCapabilities(configPath, selectedSensitiveCaps); err != nil {
- return err
- }
+ // Step 5: IDPI
+ fmt.Print(renderOnboardIDPIStep(5, totalSteps, cfg))
- installDaemonChoice = runtimeMode == "daemon"
- if installDaemonChoice {
+ // 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 {
- return err
+ fmt.Printf("\r %s %v\n", cliui.StyleStdout(cliui.ErrorStyle, "!!"), err)
+ } else {
+ fmt.Print("\r")
+ daemonInstalled = true
+ fmt.Print(renderOnboardDaemonStep(6, totalSteps, true))
}
- fmt.Println()
- fmt.Print(renderOnboardDaemonStep(modeStep, totalSteps, true))
- fmt.Print(renderOnboardNextStep(0, 0, true))
- return nil
+ currentStep++
}
+ fmt.Print(renderOnboardNextStep(currentStep, totalSteps, daemonInstalled))
fmt.Println()
- fmt.Print(renderOnboardNextStep(0, 0, false))
+
return nil
}
-func onboardConfigSummary(configPath string, configStatus onboardConfigStatus) string {
- lines := []string{}
- switch configStatus {
- case onboardConfigCreated:
- lines = append(lines, "Created secure default config.")
- case onboardConfigRecovered:
- lines = append(lines, "Recovered secure baseline.")
- lines = append(lines, "Preserved browser, profile, port, and timeout settings.")
- default:
- lines = append(lines, "Secure defaults already in place.")
+func installDaemon(configPath string) (string, error) {
+ manager, err := currentDaemonManager()
+ if err != nil {
+ return "", err
}
- lines = append(lines, "")
- lines = append(lines, fmt.Sprintf("Path %s", configPath))
- lines = append(lines, "Override `PINCHTAB_CONFIG`")
- return strings.Join(lines, "\n")
+ return manager.Install(managerEnvironment(manager).execPath, configPath)
}
-func onboardAPIAccessSummary(cfg *config.RuntimeConfig) string {
- return strings.Join([]string{
- onboardFact("server.bind", cfg.Bind, "local-only API access when set to 127.0.0.1"),
- "",
- onboardFact("server.token", summarizeToken(cfg.Token), "required for API and CLI auth"),
- }, "\n")
-}
+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))
-func onboardSensitiveSummary(cfg *config.RuntimeConfig) string {
- lines := []string{
- onboardToggleSummary("security.allowEvaluate", cfg.AllowEvaluate, "JavaScript execution in the page context"),
- onboardToggleSummary("security.allowMacro", cfg.AllowMacro, "higher-level macro automation routes"),
- onboardToggleSummary("security.allowScreencast", cfg.AllowScreencast, "live page streaming output"),
- onboardToggleSummary("security.allowDownload", cfg.AllowDownload, "server-side download endpoints"),
- onboardToggleSummary("security.allowUpload", cfg.AllowUpload, "uploading local files through browser flows"),
+ 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 strings.Join(lines, "\n\n")
+
+ return out.String()
}
-func enabledSensitiveCapabilityKeys(cfg *config.RuntimeConfig) []string {
- if cfg == nil {
- return nil
- }
- keys := make([]string, 0, 5)
- if cfg.AllowEvaluate {
- keys = append(keys, "evaluate")
- }
- if cfg.AllowMacro {
- keys = append(keys, "macro")
- }
- if cfg.AllowScreencast {
- keys = append(keys, "screencast")
- }
- if cfg.AllowDownload {
- keys = append(keys, "download")
- }
- if cfg.AllowUpload {
- keys = append(keys, "upload")
+func summarizeToken(token string) string {
+ if len(token) <= 8 {
+ return token
}
- return keys
+ return token[:4] + "..." + token[len(token)-4:]
}
-func saveSelectedSensitiveCapabilities(configPath string, selected []string) error {
- fc, _, err := config.LoadFileConfig()
- if err != nil {
- return err
+func formatStringSlice(ss []string) string {
+ if len(ss) == 0 {
+ return "(none)"
}
+ return strings.Join(ss, ", ")
+}
- has := make(map[string]bool, len(selected))
- for _, item := range selected {
- has[item] = true
+func writeSecurityToggle(out *bytes.Buffer, key string, enabled bool, description string) {
+ val := "false"
+ if enabled {
+ val = "true"
}
+ writeOnboardKV(out, key, val)
+ writeOnboardNote(out, description)
+}
- fc.Security.AllowEvaluate = boolPtr(has["evaluate"])
- fc.Security.AllowMacro = boolPtr(has["macro"])
- fc.Security.AllowScreencast = boolPtr(has["screencast"])
- fc.Security.AllowDownload = boolPtr(has["download"])
- fc.Security.AllowUpload = boolPtr(has["upload"])
+type onboardOptions struct {
+ installDaemon bool
+ force bool
+}
- if err := config.SaveFileConfig(fc, configPath); err != nil {
- return err
- }
- return nil
+type commandRunner interface {
+ CombinedOutput(name string, arg ...string) ([]byte, error)
}
-func boolPtr(v bool) *bool {
- return &v
+type osCommandRunner struct{}
+
+func (r osCommandRunner) CombinedOutput(name string, arg ...string) ([]byte, error) {
+ return exec.Command(name, arg...).CombinedOutput()
}
-func onboardAttachSummary(cfg *config.RuntimeConfig) string {
- return strings.Join([]string{
- onboardFact("attach.enabled", fmt.Sprintf("%t", cfg.AttachEnabled), "keep off unless external Chrome attach is intentional"),
- "",
- onboardFact("attach.hosts", strings.Join(cfg.AttachAllowHosts, ", "), "limits attach targets to trusted hosts"),
- "",
- onboardFact("attach.schemes", strings.Join(cfg.AttachAllowSchemes, ", "), "websocket-only transport"),
- }, "\n")
+type daemonEnvironment struct {
+ execPath string
+ homeDir string
+ osName string
+ userID string
+ xdgConfigHome string
}
-func onboardIDPISummary(cfg *config.RuntimeConfig) string {
- return strings.Join([]string{
- onboardFact("idpi.enabled", fmt.Sprintf("%t", cfg.IDPI.Enabled), "turns on indirect prompt-injection defense"),
- "",
- onboardFact("idpi.domains", formatStringSlice(cfg.IDPI.AllowedDomains), "trusted domains for the local-default setup"),
- "",
- onboardFact("idpi.strictMode", fmt.Sprintf("%t", cfg.IDPI.StrictMode), "blocks suspicious content instead of warning only"),
- "",
- onboardFact("idpi.scanContent", fmt.Sprintf("%t", cfg.IDPI.ScanContent), "scans /text and /snapshot output"),
- "",
- onboardFact("idpi.wrapContent", fmt.Sprintf("%t", cfg.IDPI.WrapContent), "marks extracted content as untrusted data"),
- }, "\n")
+type daemonManager interface {
+ Install(execPath, configPath string) (string, error)
+ ServicePath() string
+ Start() (string, error)
+ Restart() (string, error)
+ Status() (string, error)
+ Stop() (string, error)
+ Uninstall() (string, error)
+ ManualInstructions() string
+ Pid() (string, error)
+ Logs(n int) (string, error)
}
-func onboardToggleSummary(key string, enabled bool, description string) string {
- if enabled {
- return onboardFact(key, "true", "exposes "+description+" to any authenticated caller")
- }
- return onboardFact(key, "false", "disabled by default until you explicitly opt in")
+type systemdUserManager struct {
+ env daemonEnvironment
+ runner commandRunner
}
-func onboardFact(key, value, detail string) string {
- return fmt.Sprintf("%-18s %s\n - %s", key, value, detail)
+type launchdManager struct {
+ env daemonEnvironment
+ runner commandRunner
}
func IsDaemonInstalled() bool {
@@ -640,14 +440,14 @@ func IsDaemonRunning() bool {
func pinchtabOnboardTheme() *huh.Theme {
t := huh.ThemeBase()
- textPrimary := pinchtabColorTextPrimary
+ textPrimary := cliui.ColorTextPrimary
textSecondary := lipgloss.Color("#94a3b8")
- textMuted := pinchtabColorTextMuted
- accent := pinchtabColorAccent
- accentLight := pinchtabColorAccentLight
- success := pinchtabColorSuccess
- warning := pinchtabColorWarning
- destructive := pinchtabColorDanger
+ 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).
@@ -664,7 +464,7 @@ func pinchtabOnboardTheme() *huh.Theme {
t.Focused.Base = lipgloss.NewStyle().
BorderStyle(lipgloss.NormalBorder()).
- BorderForeground(pinchtabColorBorder).
+ BorderForeground(cliui.ColorBorder).
BorderLeft(true).
PaddingLeft(1)
t.Focused.Card = t.Focused.Base
@@ -808,7 +608,7 @@ func renderOnboardNextStep(step, total int, installDaemon bool) string {
if step > 0 && total > 0 {
fmt.Fprintf(&out, "%s\n", styleOnboardStep(step, total, "Next commands"))
} else {
- fmt.Fprintf(&out, "%s\n", styleValue("Next commands"))
+ fmt.Fprintf(&out, "%s\n", cliui.ValueStyle.Render("Next commands"))
}
if installDaemon {
writeOnboardCommand(&out, "pinchtab daemon")
@@ -824,20 +624,20 @@ func renderOnboardNextStep(step, total int, installDaemon bool) string {
}
func renderOnboardTitle() string {
- return styleLogo("PinchTab") + " " + styleMode("onboarding")
+ return cliui.HeadingStyle.Render("PinchTab") + " " + cliui.CommandStyle.Render("onboarding")
}
func styleOnboardStep(step, total int, title string) string {
- prefix := styleStdout(cliHeadingStyle, fmt.Sprintf("Step %d/%d", step, total))
- return prefix + " " + styleValue(title)
+ 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", styleLabel(key), styleValue(value))
+ 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", styleStdout(cliMutedStyle, ">"), styleStdout(cliMutedStyle, fmt.Sprintf(message, args...)))
+ 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) {
@@ -849,16 +649,16 @@ func writeOnboardWarning(out *bytes.Buffer, message string, args ...any) {
}
func writeOnboardCommand(out *bytes.Buffer, command string) {
- fmt.Fprintf(out, " %s %s\n", styleStdout(cliMutedStyle, "$"), styleValue(command))
+ fmt.Fprintf(out, " %s %s\n", cliui.StyleStdout(cliui.MutedStyle, "$"), cliui.ValueStyle.Render(command))
}
func printDaemonFollowUp() {
fmt.Println()
- fmt.Println(styleStdout(cliHeadingStyle, "Follow-up commands:"))
- fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab daemon"), styleStdout(cliMutedStyle, "# Check service health and logs"))
- fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab daemon restart"), styleStdout(cliMutedStyle, "# Apply config changes"))
- fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab daemon stop"), styleStdout(cliMutedStyle, "# Stop background service"))
- fmt.Printf(" %s %s\n", styleStdout(cliCommandStyle, "pinchtab daemon uninstall"), styleStdout(cliMutedStyle, "# Remove service file"))
+ 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"))
}
func currentDaemonManager() (daemonManager, error) {
@@ -1006,16 +806,16 @@ func (m *systemdUserManager) Logs(n int) (string, error) {
func (m *systemdUserManager) ManualInstructions() string {
path := m.ServicePath()
var b strings.Builder
- fmt.Fprintln(&b, styleStdout(cliHeadingStyle, "Manual instructions (Linux/systemd):"))
- fmt.Fprintln(&b, styleStdout(cliMutedStyle, "To install manually:"))
- fmt.Fprintf(&b, " 1. Create %s\n", styleStdout(cliValueStyle, path))
- fmt.Fprintln(&b, " 2. Run: "+styleStdout(cliCommandStyle, "systemctl --user daemon-reload"))
- fmt.Fprintln(&b, " 3. Run: "+styleStdout(cliCommandStyle, "systemctl --user enable --now pinchtab.service"))
+ 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)
- fmt.Fprintln(&b, styleStdout(cliMutedStyle, "To uninstall manually:"))
- fmt.Fprintln(&b, " 1. Run: "+styleStdout(cliCommandStyle, "systemctl --user disable --now pinchtab.service"))
- fmt.Fprintf(&b, " 2. Remove: %s\n", styleStdout(cliValueStyle, path))
- fmt.Fprintln(&b, " 3. Run: "+styleStdout(cliCommandStyle, "systemctl --user daemon-reload"))
+ 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"))
return b.String()
}
@@ -1137,14 +937,14 @@ func (m *launchdManager) ManualInstructions() string {
path := m.ServicePath()
target := launchdDomainTarget(m.env)
var b strings.Builder
- fmt.Fprintln(&b, styleStdout(cliHeadingStyle, "Manual instructions (macOS/launchd):"))
- fmt.Fprintln(&b, styleStdout(cliMutedStyle, "To install manually:"))
- fmt.Fprintf(&b, " 1. Create %s\n", styleStdout(cliValueStyle, path))
- fmt.Fprintln(&b, " 2. Run: "+styleStdout(cliCommandStyle, fmt.Sprintf("launchctl bootstrap %s %s", target, path)))
+ 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)
- fmt.Fprintln(&b, styleStdout(cliMutedStyle, "To uninstall manually:"))
- fmt.Fprintln(&b, " 1. Run: "+styleStdout(cliCommandStyle, fmt.Sprintf("launchctl bootout %s %s", target, path)))
- fmt.Fprintf(&b, " 2. Remove: %s\n", styleStdout(cliValueStyle, path))
+ 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))
return b.String()
}
@@ -1218,3 +1018,15 @@ func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
+
+func isInteractiveTerminal() bool {
+ in, err := os.Stdin.Stat()
+ if err != nil || (in.Mode()&os.ModeCharDevice) == 0 {
+ return false
+ }
+ out, err := os.Stdout.Stat()
+ if err != nil || (out.Mode()&os.ModeCharDevice) == 0 {
+ return false
+ }
+ return true
+}
diff --git a/cmd/pinchtab/cmd_onboard_test.go b/cmd/pinchtab/cmd_onboard_test.go
index 78f7208a..8b06218f 100644
--- a/cmd/pinchtab/cmd_onboard_test.go
+++ b/cmd/pinchtab/cmd_onboard_test.go
@@ -107,43 +107,6 @@ func TestEnsureOnboardConfigRecoversExistingSecuritySettings(t *testing.T) {
}
}
-func TestSaveSelectedSensitiveCapabilities(t *testing.T) {
- configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")
- t.Setenv("PINCHTAB_CONFIG", configPath)
-
- fc := config.DefaultFileConfig()
- token := "test-token"
- fc.Server.Token = token
- if err := config.SaveFileConfig(&fc, configPath); err != nil {
- t.Fatalf("SaveFileConfig returned error: %v", err)
- }
-
- if err := saveSelectedSensitiveCapabilities(configPath, []string{"evaluate", "download"}); err != nil {
- t.Fatalf("saveSelectedSensitiveCapabilities returned error: %v", err)
- }
-
- got, _, err := config.LoadFileConfig()
- if err != nil {
- t.Fatalf("LoadFileConfig returned error: %v", err)
- }
-
- if got.Security.AllowEvaluate == nil || !*got.Security.AllowEvaluate {
- t.Fatal("expected allowEvaluate to be true")
- }
- if got.Security.AllowDownload == nil || !*got.Security.AllowDownload {
- t.Fatal("expected allowDownload to be true")
- }
- if got.Security.AllowMacro == nil || *got.Security.AllowMacro {
- t.Fatal("expected allowMacro to be false")
- }
- if got.Security.AllowScreencast == nil || *got.Security.AllowScreencast {
- t.Fatal("expected allowScreencast to be false")
- }
- if got.Security.AllowUpload == nil || *got.Security.AllowUpload {
- t.Fatal("expected allowUpload to be false")
- }
-}
-
func TestRenderOnboardGuideIncludesSecurityValues(t *testing.T) {
cfg := testRuntimeConfig()
output := renderOnboardGuide("/tmp/pinchtab/config.json", cfg, onboardConfigCreated, true)
diff --git a/cmd/pinchtab/cmd_security.go b/cmd/pinchtab/cmd_security.go
index f79c101d..682e7f88 100644
--- a/cmd/pinchtab/cmd_security.go
+++ b/cmd/pinchtab/cmd_security.go
@@ -7,6 +7,7 @@ import (
"reflect"
"strings"
+ "github.com/pinchtab/pinchtab/internal/cliui"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/spf13/cobra"
)
@@ -29,67 +30,67 @@ func handleSecurityCommand(cfg *config.RuntimeConfig) {
warnings := assessSecurityWarnings(cfg)
recommended := recommendedSecurityDefaultLines(cfg)
- fmt.Println(styleStdout(cliHeadingStyle, "Security posture"))
+ fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Security posture"))
fmt.Println()
printSecuritySummary(os.Stdout, cfg, " ")
if len(warnings) == 0 {
- fmt.Println(styleStdout(cliHeadingStyle, "Warnings"))
+ fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Warnings"))
fmt.Println()
- fmt.Println(" " + styleStdout(cliMutedStyle, "none"))
+ fmt.Println(" " + cliui.StyleStdout(cliui.MutedStyle, "none"))
} else {
- fmt.Println(styleStdout(cliHeadingStyle, "Warnings"))
+ fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Warnings"))
fmt.Println()
for _, warning := range warnings {
- fmt.Printf(" - %s\n", styleStdout(cliWarningStyle, warning.Message))
+ 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
}
- fmt.Printf(" %s: %s\n", styleStdout(cliMutedStyle, key), styleStdout(cliValueStyle, 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", styleStdout(cliMutedStyle, "hint"), styleStdout(cliValueStyle, formatSecurityValue(warning.Attrs[i+1])))
+ fmt.Printf(" %s: %s\n", cliui.StyleStdout(cliui.MutedStyle, "hint"), cliui.StyleStdout(cliui.ValueStyle, formatSecurityValue(warning.Attrs[i+1])))
}
}
}
}
fmt.Println()
- fmt.Println(styleStdout(cliHeadingStyle, "Recommended security defaults"))
+ fmt.Println(cliui.StyleStdout(cliui.HeadingStyle, "Recommended security defaults"))
fmt.Println()
if len(recommended) == 0 {
- fmt.Println(" " + styleStdout(cliMutedStyle, "none"))
+ fmt.Println(" " + cliui.StyleStdout(cliui.MutedStyle, "none"))
} else {
printRecommendedSecurityDefaults(recommended)
}
fmt.Println()
if !isInteractiveTerminal() {
- fmt.Println(styleStdout(cliMutedStyle, "Interactive restore skipped because stdin/stdout is not a terminal."))
+ fmt.Println(cliui.StyleStdout(cliui.MutedStyle, "Interactive restore skipped because stdin/stdout is not a terminal."))
return
}
if !promptRestoreDefaults() {
- fmt.Println(styleStdout(cliMutedStyle, "No changes made."))
+ fmt.Println(cliui.StyleStdout(cliui.MutedStyle, "No changes made."))
return
}
configPath, changed, err := restoreSecurityDefaults()
if err != nil {
- fmt.Fprintln(os.Stderr, styleStderr(cliErrorStyle, fmt.Sprintf("Error restoring defaults: %v", err)))
+ fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.ErrorStyle, fmt.Sprintf("Error restoring defaults: %v", err)))
os.Exit(1)
}
if !changed {
- fmt.Println(styleStdout(cliMutedStyle, fmt.Sprintf("Security defaults already match %s", configPath)))
+ fmt.Println(cliui.StyleStdout(cliui.MutedStyle, fmt.Sprintf("Security defaults already match %s", configPath)))
return
}
- fmt.Println(styleStdout(cliSuccessStyle, fmt.Sprintf("Security defaults restored in %s", configPath)))
- fmt.Println(styleStdout(cliMutedStyle, "Restart PinchTab to apply file-based changes."))
+ 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 {
@@ -103,7 +104,7 @@ func formatSecurityValue(value any) string {
func printRecommendedSecurityDefaults(lines []string) {
for _, line := range lines {
- fmt.Printf(" - %s\n", styleStdout(cliValueStyle, line))
+ fmt.Printf(" - %s\n", cliui.StyleStdout(cliui.ValueStyle, line))
}
}
@@ -166,7 +167,7 @@ func recommendedSecurityDefaultLines(cfg *config.RuntimeConfig) []string {
}
func promptRestoreDefaults() bool {
- fmt.Print(styleStdout(cliHeadingStyle, "Restore recommended security defaults in config?") + " " + styleStdout(cliMutedStyle, "(y/N): "))
+ 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) == "" {
@@ -180,18 +181,6 @@ func promptRestoreDefaults() bool {
}
}
-func isInteractiveTerminal() bool {
- in, err := os.Stdin.Stat()
- if err != nil || (in.Mode()&os.ModeCharDevice) == 0 {
- return false
- }
- out, err := os.Stdout.Stat()
- if err != nil || (out.Mode()&os.ModeCharDevice) == 0 {
- return false
- }
- return true
-}
-
func restoreSecurityDefaults() (string, bool, error) {
fc, configPath, err := config.LoadFileConfig()
if err != nil {
diff --git a/cmd/pinchtab/main_test.go b/cmd/pinchtab/main_test.go
index d85d9466..5a9a3253 100644
--- a/cmd/pinchtab/main_test.go
+++ b/cmd/pinchtab/main_test.go
@@ -23,4 +23,3 @@ func TestServerTimeoutOrdering(t *testing.T) {
t.Errorf("WriteTimeout (%v) should be less than IdleTimeout (%v)", write, idle)
}
}
-
diff --git a/cmd/pinchtab/root.go b/cmd/pinchtab/root.go
index 5e9f767b..d5973625 100644
--- a/cmd/pinchtab/root.go
+++ b/cmd/pinchtab/root.go
@@ -12,7 +12,7 @@ var version = "dev"
var rootCmd = &cobra.Command{
Use: "pinchtab",
- Short: "PinchTab - Browser control for AI agents",
+ Short: "PinchTab - Browser for AI agents",
Long: `PinchTab provides a lightweight, API-driven way for AI agents to control
browsers, manage tabs, and perform interactive tasks.`,
Run: func(cmd *cobra.Command, args []string) {
diff --git a/cmd/pinchtab/security_warnings.go b/cmd/pinchtab/security_warnings.go
index 9e617bc5..59168394 100644
--- a/cmd/pinchtab/security_warnings.go
+++ b/cmd/pinchtab/security_warnings.go
@@ -25,6 +25,7 @@ type securityPosture struct {
Passed int
Total int
Level string
+ Bar string
}
func assessSecurityPosture(cfg *config.RuntimeConfig) securityPosture {
@@ -95,9 +96,24 @@ func assessSecurityPosture(cfg *config.RuntimeConfig) securityPosture {
Passed: passed,
Total: len(checks),
Level: securityPostureLevel(passed, len(checks)),
+ Bar: securityPostureBar(passed, len(checks)),
}
}
+func securityPostureBar(passed, total int) string {
+ if total == 0 {
+ return "[ ]"
+ }
+ const width = 10
+ pct := float64(passed) / float64(total)
+ filled := int(pct * width)
+ if filled > width {
+ filled = width
+ }
+ bar := "[" + strings.Repeat("■", filled) + strings.Repeat(" ", width-filled) + "]"
+ return bar
+}
+
func assessSecurityWarnings(cfg *config.RuntimeConfig) []securityWarning {
if cfg == nil {
return nil
diff --git a/cmd/pinchtab/startup_output.go b/cmd/pinchtab/startup_output.go
index e1de04ad..adb141b9 100644
--- a/cmd/pinchtab/startup_output.go
+++ b/cmd/pinchtab/startup_output.go
@@ -2,12 +2,12 @@ package main
import (
"fmt"
+ "github.com/pinchtab/pinchtab/internal/cliui"
"io"
"os"
"strings"
"github.com/charmbracelet/lipgloss"
- "github.com/pinchtab/pinchtab/internal/cliui"
"github.com/pinchtab/pinchtab/internal/config"
)
@@ -30,9 +30,9 @@ func printStartupBanner(cfg *config.RuntimeConfig, opts startupBannerOptions) {
alloc := blankIfEmpty(opts.Allocation, "none")
writeBannerf(" %s %s\n", styleLabel("str,plc"), styleValue(fmt.Sprintf("%s,%s", strat, alloc)))
- daemonStatus := styleStdout(cliWarningStyle, "not installed")
+ daemonStatus := cliui.StyleStdout(cliui.WarningStyle, "not installed")
if IsDaemonInstalled() {
- daemonStatus = styleStdout(cliSuccessStyle, "ok")
+ daemonStatus = cliui.StyleStdout(cliui.SuccessStyle, "ok")
}
writeBannerf(" %s %s\n", styleLabel("daemon"), daemonStatus)
@@ -45,44 +45,13 @@ func printStartupBanner(cfg *config.RuntimeConfig, opts startupBannerOptions) {
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))
- writeSummaryf(
- w,
- "%s%s %s %s\n",
- prefix,
- styleLabel("security"),
- styleSecurityLevel(posture.Level),
- styleSecurityBar(posture.Level, renderPostureBar(posture.Passed, posture.Total)),
- )
for _, check := range posture.Checks {
- writeSummaryf(
- w,
- "%s [%s] %s %s\n",
- prefix,
- styleMarker(check.Passed),
- styleCheckLabel(check.Label),
- styleCheckDetail(check.Passed, check.Detail),
- )
+ writeSummaryf(w, "%s %s %s %s\n", prefix, styleMarker(check.Passed), styleCheckLabel(check.Label), styleCheckDetail(check.Passed, check.Detail))
}
}
-func renderPostureBar(passed, total int) string {
- if total <= 0 {
- return "[--------]"
- }
- var b strings.Builder
- b.WriteByte('[')
- for i := 0; i < total; i++ {
- if i < passed {
- b.WriteByte('#')
- } else {
- b.WriteByte('-')
- }
- }
- b.WriteByte(']')
- return b.String()
-}
-
func blankIfEmpty(value, fallback string) string {
if strings.TrimSpace(value) == "" {
return fallback
@@ -106,38 +75,62 @@ 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, lipgloss.NewStyle().Foreground(cliui.ColorAccent).Bold(true))
+ return applyStyle(text, cliui.HeadingStyle)
}
func styleMode(text string) string {
- return applyStyle(text, lipgloss.NewStyle().Foreground(cliui.ColorTextMuted))
+ return applyStyle(text, cliui.CommandStyle)
}
func styleLabel(text string) string {
- return applyStyle(fmt.Sprintf("%-8s", text), lipgloss.NewStyle().Foreground(cliui.ColorTextMuted))
+ return applyStyle(fmt.Sprintf("%-8s", text), cliui.MutedStyle)
}
func styleValue(text string) string {
- return applyStyle(text, lipgloss.NewStyle().Foreground(cliui.ColorTextPrimary).Bold(true))
+ return applyStyle(text, cliui.ValueStyle)
}
func styleCheckLabel(text string) string {
- return applyStyle(fmt.Sprintf("%-20s", text), lipgloss.NewStyle().Foreground(cliui.ColorTextMuted))
+ return applyStyle(fmt.Sprintf("%-20s", text), cliui.MutedStyle)
}
func styleCheckDetail(passed bool, text string) string {
if passed {
- return applyStyle(text, lipgloss.NewStyle().Foreground(cliui.ColorSuccess))
+ return applyStyle(text, cliui.SuccessStyle)
}
- return applyStyle(text, lipgloss.NewStyle().Foreground(cliui.ColorWarning))
+ return applyStyle(text, cliui.WarningStyle)
}
func styleMarker(passed bool) string {
if passed {
- return applyStyle("ok", lipgloss.NewStyle().Foreground(cliui.ColorSuccess).Bold(true))
+ return applyStyle("ok", cliui.SuccessStyle)
}
- return applyStyle("!!", lipgloss.NewStyle().Foreground(cliui.ColorDanger).Bold(true))
+ return applyStyle("!!", cliui.ErrorStyle)
}
func styleSecurityLevel(level string) string {
diff --git a/cmd/pinchtab/startup_output_test.go b/cmd/pinchtab/startup_output_test.go
index ace06161..f53006e3 100644
--- a/cmd/pinchtab/startup_output_test.go
+++ b/cmd/pinchtab/startup_output_test.go
@@ -1,9 +1,8 @@
package main
import (
- "testing"
-
"github.com/pinchtab/pinchtab/internal/cliui"
+ "testing"
)
func TestSecurityLevelColor(t *testing.T) {
diff --git a/cmd/promptdemo/main.go b/cmd/promptdemo/main.go
deleted file mode 100644
index c04aabc5..00000000
--- a/cmd/promptdemo/main.go
+++ /dev/null
@@ -1,96 +0,0 @@
-package main
-
-import (
- "fmt"
- "os"
- "strings"
-
- prompt "github.com/c-bata/go-prompt"
-)
-
-var demoRefs = []prompt.Suggest{
- {Text: "e12", Description: "button Login"},
- {Text: "e18", Description: "input Email"},
- {Text: "e24", Description: "link Forgot password"},
-}
-
-var rootSuggestions = []prompt.Suggest{
- {Text: "help", Description: "Show the available commands"},
- {Text: "nav", Description: "Navigate to a URL"},
- {Text: "snap", Description: "Capture a page snapshot"},
- {Text: "click", Description: "Click an element from the last snapshot"},
- {Text: "type", Description: "Type into an element from the last snapshot"},
- {Text: "pdf", Description: "Export the current page as PDF"},
- {Text: "exit", Description: "Quit the demo"},
-}
-
-func main() {
- fmt.Println("PinchTab prompt demo")
- fmt.Println("Tab completes commands and a few cached refs from a fake snapshot.")
- fmt.Println("Try: nav https://example.com, snap -i, click e12, type e18 hello")
-
- p := prompt.New(
- executor,
- completer,
- prompt.OptionPrefix("pinchtab> "),
- prompt.OptionTitle("PinchTab Prompt Demo"),
- )
- p.Run()
-}
-
-func executor(in string) {
- line := strings.TrimSpace(in)
- if line == "" {
- return
- }
-
- switch {
- case line == "exit" || line == "quit":
- fmt.Println("bye")
- os.Exit(0)
- case line == "help":
- fmt.Println("commands: nav, snap, click, type, pdf, exit")
- case strings.HasPrefix(line, "nav "):
- fmt.Printf("navigate -> %s\n", strings.TrimSpace(strings.TrimPrefix(line, "nav ")))
- case strings.HasPrefix(line, "snap"):
- fmt.Println("snapshot -> cached refs: e12(Login), e18(Email), e24(Forgot password)")
- case strings.HasPrefix(line, "click "):
- fmt.Printf("click -> %s\n", strings.TrimSpace(strings.TrimPrefix(line, "click ")))
- case strings.HasPrefix(line, "type "):
- fmt.Printf("type -> %s\n", strings.TrimSpace(strings.TrimPrefix(line, "type ")))
- case strings.HasPrefix(line, "pdf"):
- fmt.Println("pdf -> /tmp/example.pdf")
- default:
- fmt.Printf("unknown command: %s\n", line)
- }
-}
-
-func completer(d prompt.Document) []prompt.Suggest {
- words := strings.Fields(d.TextBeforeCursor())
- if len(words) == 0 {
- return prompt.FilterHasPrefix(rootSuggestions, d.GetWordBeforeCursor(), true)
- }
-
- switch words[0] {
- case "nav":
- return prompt.FilterHasPrefix([]prompt.Suggest{
- {Text: "https://example.com", Description: "demo URL"},
- {Text: "https://pinchtab.com", Description: "PinchTab website"},
- }, d.GetWordBeforeCursor(), true)
- case "snap":
- return prompt.FilterHasPrefix([]prompt.Suggest{
- {Text: "-i", Description: "interactive elements only"},
- {Text: "-c", Description: "compact format"},
- {Text: "--diff", Description: "only changes since last snapshot"},
- }, d.GetWordBeforeCursor(), true)
- case "click", "type":
- return prompt.FilterHasPrefix(demoRefs, d.GetWordBeforeCursor(), true)
- case "pdf":
- return prompt.FilterHasPrefix([]prompt.Suggest{
- {Text: "-o", Description: "output file"},
- {Text: "--tab", Description: "target tab"},
- }, d.GetWordBeforeCursor(), true)
- default:
- return prompt.FilterHasPrefix(rootSuggestions, d.GetWordBeforeCursor(), true)
- }
-}
diff --git a/internal/browsercli/actions_element.go b/internal/browsercli/actions_element.go
new file mode 100644
index 00000000..b462a2e0
--- /dev/null
+++ b/internal/browsercli/actions_element.go
@@ -0,0 +1,91 @@
+package browsercli
+
+import (
+ "github.com/pinchtab/pinchtab/internal/cliui"
+ "net/http"
+ "strconv"
+ "strings"
+)
+
+func Action(client *http.Client, base, token, kind string, args []string) {
+ body := map[string]any{"kind": kind}
+
+ switch kind {
+ case "click", "hover", "focus":
+ var cssSelector string
+ var refArg string
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "--css":
+ if i+1 < len(args) {
+ i++
+ cssSelector = args[i]
+ }
+ case "--wait-nav":
+ body["waitNav"] = true
+ default:
+ if refArg == "" {
+ refArg = args[i]
+ }
+ }
+ }
+ if cssSelector != "" {
+ body["selector"] = cssSelector
+ } else if refArg != "" {
+ body["ref"] = refArg
+ } else {
+ cliui.Fatal("Usage: pinchtab %s <ref> [--css <selector>] [--wait-nav]", kind)
+ }
+ case "type":
+ if len(args) < 2 {
+ cliui.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>")
+ }
+ if strings.HasPrefix(args[0], "e") {
+ body["ref"] = args[0]
+ } else {
+ body["selector"] = args[0]
+ }
+ body["text"] = strings.Join(args[1:], " ")
+ case "press":
+ if len(args) < 1 {
+ cliui.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)")
+ }
+ if strings.HasPrefix(args[0], "e") {
+ body["ref"] = args[0]
+ } else if px, err := strconv.Atoi(args[0]); err == nil {
+ body["scrollY"] = px
+ } else {
+ switch strings.ToLower(args[0]) {
+ case "down":
+ body["scrollY"] = 800
+ case "up":
+ body["scrollY"] = -800
+ case "right":
+ body["scrollX"] = 800
+ case "left":
+ body["scrollX"] = -800
+ default:
+ cliui.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>")
+ }
+ body["ref"] = args[0]
+ body["value"] = args[1]
+ }
+
+ DoPost(client, base, token, "/action", body)
+}
diff --git a/internal/browsercli/actions_evaluate.go b/internal/browsercli/actions_evaluate.go
new file mode 100644
index 00000000..443cffa9
--- /dev/null
+++ b/internal/browsercli/actions_evaluate.go
@@ -0,0 +1,17 @@
+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_instance.go b/internal/browsercli/actions_instance.go
new file mode 100644
index 00000000..5451eb65
--- /dev/null
+++ b/internal/browsercli/actions_instance.go
@@ -0,0 +1,120 @@
+package browsercli
+
+import (
+ "fmt"
+ "github.com/pinchtab/pinchtab/internal/cliui"
+ "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")
+ }
+
+ subCmd := args[0]
+ subArgs := args[1:]
+
+ switch subCmd {
+ case "start", "launch": // "start" is new Phase 2 API, "launch" is legacy
+ InstanceStart(client, base, token, subArgs)
+ case "navigate":
+ InstanceNavigate(client, base, token, subArgs)
+ case "logs":
+ InstanceLogs(client, base, token, subArgs)
+ case "stop":
+ InstanceStop(client, base, token, subArgs)
+ default:
+ cliui.Fatal("Unknown subcommand: %s", subCmd)
+ }
+}
+
+func InstanceStart(client *http.Client, base, token string, args []string) {
+ body := map[string]any{}
+
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "--profileId":
+ if i+1 < len(args) {
+ body["profileId"] = args[i+1]
+ i++
+ }
+ case "--mode":
+ if i+1 < len(args) {
+ body["mode"] = args[i+1]
+ i++
+ }
+ case "--port":
+ if i+1 < len(args) {
+ body["port"] = args[i+1]
+ i++
+ }
+ }
+ }
+
+ // Use new /instances/start endpoint if available, fall back to /instances/launch for backward compat
+ endpoint := "/instances/start"
+ 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>")
+ }
+
+ instID := args[0]
+ targetURL := args[1]
+
+ // 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{
+ "url": "about:blank",
+ })
+ tabID, _ := openResp["tabId"].(string)
+ if tabID == "" {
+ cliui.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{
+ "url": targetURL,
+ })
+}
+
+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>")
+ }
+
+ if args[0] == "--id" {
+ if len(args) < 2 {
+ cliui.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)
+ fmt.Println(string(logs))
+}
+
+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>")
+ }
+
+ if args[0] == "--id" {
+ if len(args) < 2 {
+ cliui.Fatal("Usage: --id requires instance ID")
+ }
+ instID = args[1]
+ } else {
+ instID = args[0]
+ }
+
+ DoPost(client, base, token, fmt.Sprintf("/instances/%s/stop", instID), nil)
+}
diff --git a/internal/browsercli/actions_navigate.go b/internal/browsercli/actions_navigate.go
new file mode 100644
index 00000000..1674b006
--- /dev/null
+++ b/internal/browsercli/actions_navigate.go
@@ -0,0 +1,25 @@
+package browsercli
+
+import (
+ "github.com/pinchtab/pinchtab/internal/cliui"
+ "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]")
+ }
+ body := map[string]any{"url": args[0]}
+ for _, a := range args[1:] {
+ switch a {
+ case "--new-tab":
+ body["newTab"] = true
+ case "--block-images":
+ body["blockImages"] = true
+ case "--block-ads":
+ body["blockAds"] = true
+ }
+ }
+ result := DoPost(client, base, token, "/navigate", body)
+ SuggestNextAction("navigate", result)
+}
diff --git a/internal/browsercli/actions_pdf.go b/internal/browsercli/actions_pdf.go
new file mode 100644
index 00000000..51371826
--- /dev/null
+++ b/internal/browsercli/actions_pdf.go
@@ -0,0 +1,125 @@
+package browsercli
+
+import (
+ "fmt"
+ "github.com/pinchtab/pinchtab/internal/cliui"
+ "net/http"
+ "net/url"
+ "os"
+ "time"
+)
+
+func PDF(client *http.Client, base, token string, args []string) {
+ params := url.Values{}
+ params.Set("raw", "true")
+ outFile := ""
+ tabID := ""
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "-o", "--output":
+ if i+1 < len(args) {
+ i++
+ outFile = args[i]
+ }
+ case "--landscape":
+ params.Set("landscape", "true")
+ case "--scale":
+ if i+1 < len(args) {
+ i++
+ params.Set("scale", args[i])
+ }
+ case "--tab":
+ if i+1 < len(args) {
+ i++
+ tabID = args[i]
+ }
+ // Paper dimensions
+ case "--paper-width":
+ if i+1 < len(args) {
+ i++
+ params.Set("paperWidth", args[i])
+ }
+ case "--paper-height":
+ if i+1 < len(args) {
+ i++
+ params.Set("paperHeight", args[i])
+ }
+ // Margins
+ case "--margin-top":
+ if i+1 < len(args) {
+ i++
+ params.Set("marginTop", args[i])
+ }
+ case "--margin-bottom":
+ if i+1 < len(args) {
+ i++
+ params.Set("marginBottom", args[i])
+ }
+ case "--margin-left":
+ if i+1 < len(args) {
+ i++
+ params.Set("marginLeft", args[i])
+ }
+ case "--margin-right":
+ if i+1 < len(args) {
+ i++
+ params.Set("marginRight", args[i])
+ }
+ // Content options
+ case "--page-ranges":
+ if i+1 < len(args) {
+ i++
+ params.Set("pageRanges", args[i])
+ }
+ case "--prefer-css-page-size":
+ params.Set("preferCSSPageSize", "true")
+ // Header/Footer
+ case "--display-header-footer":
+ params.Set("displayHeaderFooter", "true")
+ case "--header-template":
+ if i+1 < len(args) {
+ i++
+ params.Set("headerTemplate", args[i])
+ }
+ case "--footer-template":
+ if i+1 < len(args) {
+ i++
+ params.Set("footerTemplate", args[i])
+ }
+ // Accessibility
+ case "--generate-tagged-pdf":
+ params.Set("generateTaggedPDF", "true")
+ case "--generate-document-outline":
+ params.Set("generateDocumentOutline", "true")
+ // Output options
+ case "--file-output":
+ params.Del("raw")
+ params.Set("output", "file")
+ case "--path":
+ if i+1 < len(args) {
+ i++
+ params.Set("path", args[i])
+ }
+ case "--raw":
+ params.Set("raw", "true")
+ }
+ }
+
+ if outFile == "" {
+ outFile = fmt.Sprintf("page-%s.pdf", time.Now().Format("20060102-150405"))
+ }
+
+ var data []byte
+ if tabID != "" {
+ data = DoGetRaw(client, base, token, fmt.Sprintf("/tabs/%s/pdf", tabID), params)
+ } else {
+ data = 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)
+ }
+ fmt.Println(cliui.StyleStdout(cliui.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
+}
diff --git a/internal/browsercli/actions_quick.go b/internal/browsercli/actions_quick.go
new file mode 100644
index 00000000..9d0384d7
--- /dev/null
+++ b/internal/browsercli/actions_quick.go
@@ -0,0 +1,49 @@
+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/actions_screenshot.go b/internal/browsercli/actions_screenshot.go
new file mode 100644
index 00000000..60211954
--- /dev/null
+++ b/internal/browsercli/actions_screenshot.go
@@ -0,0 +1,48 @@
+package browsercli
+
+import (
+ "fmt"
+ "github.com/pinchtab/pinchtab/internal/cliui"
+ "net/http"
+ "net/url"
+ "os"
+ "time"
+)
+
+func Screenshot(client *http.Client, base, token string, args []string) {
+ params := url.Values{}
+ params.Set("raw", "true")
+ outFile := ""
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "-o", "--output":
+ if i+1 < len(args) {
+ i++
+ outFile = args[i]
+ }
+ case "--quality", "-q":
+ if i+1 < len(args) {
+ i++
+ params.Set("quality", args[i])
+ }
+ case "--tab":
+ if i+1 < len(args) {
+ i++
+ params.Set("tabId", args[i])
+ }
+ }
+ }
+
+ if outFile == "" {
+ outFile = fmt.Sprintf("screenshot-%s.jpg", time.Now().Format("20060102-150405"))
+ }
+
+ data := 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)
+ }
+ fmt.Println(cliui.StyleStdout(cliui.SuccessStyle, fmt.Sprintf("Saved %s (%d bytes)", outFile, len(data))))
+}
diff --git a/internal/browsercli/actions_snapshot.go b/internal/browsercli/actions_snapshot.go
new file mode 100644
index 00000000..f28dcccb
--- /dev/null
+++ b/internal/browsercli/actions_snapshot.go
@@ -0,0 +1,44 @@
+package browsercli
+
+import (
+ "net/http"
+ "net/url"
+)
+
+func Snapshot(client *http.Client, base, token string, args []string) {
+ params := url.Values{}
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "--interactive", "-i":
+ params.Set("filter", "interactive")
+ case "--compact", "-c":
+ params.Set("format", "compact")
+ case "--text":
+ params.Set("format", "text")
+ case "--diff", "-d":
+ params.Set("diff", "true")
+ case "--selector", "-s":
+ if i+1 < len(args) {
+ i++
+ params.Set("selector", args[i])
+ }
+ case "--max-tokens":
+ if i+1 < len(args) {
+ i++
+ params.Set("maxTokens", args[i])
+ }
+ case "--depth":
+ if i+1 < len(args) {
+ i++
+ params.Set("depth", args[i])
+ }
+ case "--tab":
+ if i+1 < len(args) {
+ i++
+ params.Set("tabId", args[i])
+ }
+ }
+ }
+ result := DoGet(client, base, token, "/snapshot", params)
+ SuggestNextAction("snapshot", result)
+}
diff --git a/internal/browsercli/actions_system.go b/internal/browsercli/actions_system.go
new file mode 100644
index 00000000..b8949937
--- /dev/null
+++ b/internal/browsercli/actions_system.go
@@ -0,0 +1,111 @@
+package browsercli
+
+import (
+ "encoding/json"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+)
+
+func Health(client *http.Client, base, token string) {
+ DoGet(client, base, token, "/health", nil)
+}
+
+func Instances(client *http.Client, base, token string) {
+ body := 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)
+ }
+
+ // Transform to cleaner output format
+ output := make([]map[string]any, len(instances))
+ for i, inst := range instances {
+ id, _ := inst["id"].(string)
+ port, _ := inst["port"].(string)
+ headless, _ := inst["headless"].(bool)
+ status, _ := inst["status"].(string)
+
+ mode := "headless"
+ if !headless {
+ mode = "headed"
+ }
+
+ output[i] = map[string]any{
+ "id": id,
+ "port": port,
+ "mode": mode,
+ "status": status,
+ }
+ }
+
+ // Output as JSON
+ data, _ := json.MarshalIndent(output, "", " ")
+ fmt.Println(string(data))
+}
+
+// --- profiles ---
+
+func Profiles(client *http.Client, base, token string) {
+ result := DoGet(client, base, token, "/profiles", nil)
+
+ // Display profiles in a friendly format
+ if profiles, ok := result["profiles"].([]interface{}); ok && len(profiles) > 0 {
+ fmt.Println()
+ for _, prof := range profiles {
+ if m, ok := prof.(map[string]any); ok {
+ name, _ := m["name"].(string)
+
+ fmt.Printf("👤 %s\n", name)
+ }
+ }
+ fmt.Println()
+ } else {
+ fmt.Println("No profiles available")
+ }
+}
+
+// --- internal helpers ---
+
+// getInstances fetches the list of running instances
+func getInstances(client *http.Client, base, token string) []map[string]any {
+ resp, err := http.NewRequest("GET", base+"/instances", nil)
+ if err != nil {
+ return nil
+ }
+ if token != "" {
+ resp.Header.Set("Authorization", "Bearer "+token)
+ }
+
+ result, err := client.Do(resp)
+ if err != nil || result.StatusCode >= 400 {
+ return nil
+ }
+ defer func() { _ = result.Body.Close() }()
+
+ var data map[string]any
+ if err := json.NewDecoder(result.Body).Decode(&data); err != nil {
+ log.Printf("warning: error decoding instances response: %v", err)
+ }
+
+ if instances, ok := data["instances"].([]interface{}); ok {
+ converted := make([]map[string]any, len(instances))
+ for i, inst := range instances {
+ if m, ok := inst.(map[string]any); ok {
+ converted[i] = m
+ }
+ }
+ return converted
+ }
+ return nil
+}
+
+// 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)
+}
diff --git a/internal/browsercli/actions_tabs.go b/internal/browsercli/actions_tabs.go
new file mode 100644
index 00000000..66a609ed
--- /dev/null
+++ b/internal/browsercli/actions_tabs.go
@@ -0,0 +1,290 @@
+package browsercli
+
+import (
+ "fmt"
+ "github.com/pinchtab/pinchtab/internal/cliui"
+ "net/http"
+ "net/url"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+)
+
+func Tabs(client *http.Client, base, token string, args []string) {
+ if len(args) == 0 {
+ // List all tabs
+ DoGet(client, base, token, "/tabs", nil)
+ return
+ }
+
+ cmd := args[0]
+ subArgs := args[1:]
+
+ // Check if this is a tab operation (navigate, snapshot, click, etc.)
+ // Pattern: pinchtab tab <operation> <tabId> [args...]
+ if isTabOperation(cmd) {
+ TabOperation(client, base, token, cmd, subArgs)
+ return
+ }
+
+ // Legacy: pinchtab tab new/close
+ switch cmd {
+ case "new":
+ url := ""
+ if len(subArgs) > 0 {
+ url = subArgs[0]
+ }
+
+ // 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..."))
+ launchInstance(client, base, token, "default")
+ fmt.Fprintln(os.Stderr, cliui.StyleStderr(cliui.SuccessStyle, "Instance launched"))
+ }
+
+ body := map[string]any{"action": "new"}
+ if url != "" {
+ body["url"] = url
+ }
+ DoPost(client, base, token, "/tab", body)
+
+ case "close":
+ if len(subArgs) < 1 {
+ cliui.Fatal("Usage: pinchtab tab close <tabId>")
+ }
+ DoPost(client, base, token, "/tab", map[string]any{
+ "action": "close",
+ "tabId": subArgs[0],
+ })
+
+ default:
+ TabOperation(client, base, token, cmd, subArgs)
+ }
+}
+
+func isTabOperation(op string) bool {
+ ops := map[string]bool{
+ "navigate": true, "snapshot": true, "screenshot": true,
+ "click": true, "type": true, "press": true, "fill": true,
+ "hover": true, "scroll": true, "select": true, "focus": true,
+ "text": true, "eval": true, "evaluate": true, "pdf": true,
+ "cookies": true, "lock": true, "unlock": true, "locks": true,
+ "fingerprint": true, "info": true,
+ }
+ return ops[op]
+}
+
+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)
+ }
+
+ tabID := args[0]
+ restArgs := args[1:]
+
+ switch op {
+ case "navigate":
+ if len(restArgs) < 1 {
+ cliui.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++ {
+ switch restArgs[i] {
+ case "--timeout":
+ if i+1 < len(restArgs) {
+ body["timeout"] = restArgs[i+1]
+ i++
+ }
+ case "--block-images":
+ body["blockImages"] = true
+ case "--block-ads":
+ body["blockAds"] = true
+ }
+ }
+ DoPost(client, base, token, fmt.Sprintf("/tabs/%s/navigate", tabID), body)
+
+ case "snapshot":
+ params := url.Values{}
+ for _, arg := range restArgs {
+ switch arg {
+ case "-i", "--interactive":
+ params.Set("interactive", "true")
+ case "-c", "--compact":
+ params.Set("compact", "true")
+ case "-d", "--diff":
+ params.Set("diff", "true")
+ }
+ }
+ DoGet(client, base, token, fmt.Sprintf("/tabs/%s/snapshot", tabID), params)
+
+ case "screenshot", "ss":
+ params := url.Values{}
+ outFile := ""
+ for i := 0; i < len(restArgs); i++ {
+ switch restArgs[i] {
+ case "-o", "--output":
+ if i+1 < len(restArgs) {
+ outFile = restArgs[i+1]
+ i++
+ }
+ case "-q", "--quality":
+ if i+1 < len(restArgs) {
+ params.Set("quality", restArgs[i+1])
+ i++
+ }
+ }
+ }
+ params.Set("raw", "true")
+ data := 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))))
+ }
+ }
+
+ case "click", "hover", "focus":
+ if len(restArgs) < 1 {
+ cliui.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)
+
+ case "type":
+ if len(restArgs) < 2 {
+ cliui.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)
+
+ case "fill":
+ if len(restArgs) < 2 {
+ cliui.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)
+
+ case "press":
+ if len(restArgs) < 1 {
+ cliui.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)
+
+ case "scroll":
+ if len(restArgs) < 1 {
+ cliui.Fatal("Usage: pinchtab tab scroll <tabId> <direction|pixels>")
+ }
+ body := map[string]any{}
+ if v, err := strconv.Atoi(restArgs[0]); err == nil {
+ body["kind"] = "scroll"
+ body["scrollY"] = v
+ } else {
+ body["kind"] = "scroll"
+ body["direction"] = restArgs[0]
+ }
+ 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>")
+ }
+ body := map[string]any{"kind": "select", "ref": restArgs[0], "value": restArgs[1]}
+ DoPost(client, base, token, fmt.Sprintf("/tabs/%s/action", tabID), body)
+
+ case "text":
+ params := url.Values{}
+ for _, arg := range restArgs {
+ if arg == "--raw" {
+ params.Set("raw", "true")
+ }
+ }
+ 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>")
+ }
+ body := map[string]any{"expression": strings.Join(restArgs, " ")}
+ DoPost(client, base, token, fmt.Sprintf("/tabs/%s/evaluate", tabID), body)
+
+ case "pdf":
+ params := url.Values{}
+ outFile := ""
+ for i := 0; i < len(restArgs); i++ {
+ switch restArgs[i] {
+ case "-o", "--output":
+ if i+1 < len(restArgs) {
+ outFile = restArgs[i+1]
+ i++
+ }
+ case "--landscape":
+ params.Set("landscape", "true")
+ case "--scale":
+ if i+1 < len(restArgs) {
+ params.Set("scale", restArgs[i+1])
+ i++
+ }
+ }
+ }
+ params.Set("raw", "true")
+ data := 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))
+ }
+ }
+
+ case "cookies":
+ DoGet(client, base, token, fmt.Sprintf("/tabs/%s/cookies", tabID), nil)
+
+ case "lock":
+ body := map[string]any{}
+ for i := 0; i < len(restArgs); i++ {
+ switch restArgs[i] {
+ case "--owner":
+ if i+1 < len(restArgs) {
+ body["owner"] = restArgs[i+1]
+ i++
+ }
+ case "--ttl":
+ if i+1 < len(restArgs) {
+ if ttl, err := strconv.Atoi(restArgs[i+1]); err == nil {
+ body["ttl"] = ttl
+ }
+ i++
+ }
+ }
+ }
+ DoPost(client, base, token, fmt.Sprintf("/tabs/%s/lock", tabID), body)
+
+ case "unlock":
+ body := map[string]any{}
+ for i := 0; i < len(restArgs); i++ {
+ switch restArgs[i] {
+ case "--owner":
+ if i+1 < len(restArgs) {
+ body["owner"] = restArgs[i+1]
+ i++
+ }
+ }
+ }
+ DoPost(client, base, token, fmt.Sprintf("/tabs/%s/unlock", tabID), body)
+
+ case "locks":
+ DoGet(client, base, token, fmt.Sprintf("/tabs/%s/locks", tabID), nil)
+
+ case "info":
+ DoGet(client, base, token, fmt.Sprintf("/tabs/%s", tabID), nil)
+
+ default:
+ cliui.Fatal("Unknown tab operation: %s", op)
+ }
+}
diff --git a/internal/browsercli/actions_text.go b/internal/browsercli/actions_text.go
new file mode 100644
index 00000000..814075a6
--- /dev/null
+++ b/internal/browsercli/actions_text.go
@@ -0,0 +1,22 @@
+package browsercli
+
+import (
+ "net/http"
+ "net/url"
+)
+
+func Text(client *http.Client, base, token string, args []string) {
+ params := url.Values{}
+ for i := 0; i < len(args); i++ {
+ switch args[i] {
+ case "--raw":
+ params.Set("mode", "raw")
+ case "--tab":
+ if i+1 < len(args) {
+ i++
+ params.Set("tabId", args[i])
+ }
+ }
+ }
+ DoGet(client, base, token, "/text", params)
+}
diff --git a/internal/browsercli/client.go b/internal/browsercli/client.go
new file mode 100644
index 00000000..3c13bdb5
--- /dev/null
+++ b/internal/browsercli/client.go
@@ -0,0 +1,126 @@
+package browsercli
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "github.com/pinchtab/pinchtab/internal/cliui"
+ "io"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "time"
+)
+
+func DoGet(client *http.Client, base, token, path string, params url.Values) map[string]any {
+ u := base + path
+ if len(params) > 0 {
+ u += "?" + params.Encode()
+ }
+ req, _ := http.NewRequest("GET", u, nil)
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ cliui.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))))
+ os.Exit(1)
+ }
+
+ // Pretty-print JSON if possible
+ var buf bytes.Buffer
+ if json.Indent(&buf, body, "", " ") == nil {
+ fmt.Println(buf.String())
+ } else {
+ fmt.Println(string(body))
+ }
+
+ // Parse and return result
+ var result map[string]any
+ if err := json.Unmarshal(body, &result); err != nil {
+ log.Printf("warning: error unmarshaling response: %v", err)
+ }
+ return result
+}
+
+func DoGetRaw(client *http.Client, base, token, path string, params url.Values) []byte {
+ u := base + path
+ if len(params) > 0 {
+ u += "?" + params.Encode()
+ }
+ req, _ := http.NewRequest("GET", u, nil)
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ cliui.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))))
+ os.Exit(1)
+ }
+ return body
+}
+
+func DoPost(client *http.Client, base, token, path string, body map[string]any) map[string]any {
+ data, _ := json.Marshal(body)
+ req, _ := http.NewRequest("POST", base+path, bytes.NewReader(data))
+ req.Header.Set("Content-Type", "application/json")
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ cliui.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))))
+ os.Exit(1)
+ }
+
+ var buf bytes.Buffer
+ if json.Indent(&buf, respBody, "", " ") == nil {
+ fmt.Println(buf.String())
+ } else {
+ fmt.Println(string(respBody))
+ }
+
+ // Parse and return result for suggestions
+ var result map[string]any
+ if err := json.Unmarshal(respBody, &result); err != nil {
+ log.Printf("warning: error unmarshaling response: %v", err)
+ }
+ return result
+}
+
+// ResolveInstanceBase fetches the named instance from the orchestrator and returns
+// a base URL pointing directly at that instance's API port.
+func ResolveInstanceBase(orchBase, token, instanceID, bind string) string {
+ c := &http.Client{Timeout: 10 * time.Second}
+ body := DoGetRaw(c, orchBase, token, fmt.Sprintf("/instances/%s", instanceID), nil)
+
+ var inst struct {
+ Port string `json:"port"`
+ }
+ if err := json.Unmarshal(body, &inst); err != nil {
+ cliui.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)
+ }
+ return fmt.Sprintf("http://%s:%s", bind, inst.Port)
+}
diff --git a/internal/browsercli/diagnostics.go b/internal/browsercli/diagnostics.go
new file mode 100644
index 00000000..0a4bb352
--- /dev/null
+++ b/internal/browsercli/diagnostics.go
@@ -0,0 +1,130 @@
+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/cliui/styles.go b/internal/cliui/styles.go
index 224bde09..e1a066a6 100644
--- a/internal/cliui/styles.go
+++ b/internal/cliui/styles.go
@@ -1,6 +1,7 @@
package cliui
import (
+ "fmt"
"os"
"strings"
@@ -29,13 +30,26 @@ var (
)
func RenderStdout(style lipgloss.Style, text string) string {
- return renderToWriter(os.Stdout, style, text)
+ return StyleStdout(style, text)
}
func RenderStderr(style lipgloss.Style, text string) string {
+ return StyleStderr(style, text)
+}
+
+func StyleStdout(style lipgloss.Style, text string) string {
+ return renderToWriter(os.Stdout, style, text)
+}
+
+func StyleStderr(style lipgloss.Style, text string) string {
return renderToWriter(os.Stderr, style, text)
}
+func Fatal(format string, args ...any) {
+ fmt.Fprint(os.Stderr, StyleStderr(ErrorStyle, fmt.Sprintf(format, args...))+"\n")
+ os.Exit(1)
+}
+
func renderToWriter(w *os.File, style lipgloss.Style, text string) string {
if !shouldColorizeFile(w) {
return text