High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: streamline browser startup and tab reuse
Luigi Agostidc7dcf79615f
diff --git a/README.md b/README.mdindex 2cbaeade..e83ec574 100644--- a/README.md+++ b/README.md@@ -230,7 +230,12 @@ docker run -d \### Use It-**Terminal 1 — Start the server:**+**First useful command — auto-starts the local server if needed:**+```bash+pinchtab nav https://pinchtab.com --snap+```++**Or start the server explicitly when you want foreground logs:**```bashpinchtab server```@@ -245,7 +250,7 @@ That keeps PinchTab running in the background so your agent tools can reuse it w**Terminal 2 — Control the browser:**```bash-# Navigate+# Navigate; starts the server automatically if neededpinchtab nav https://pinchtab.com# Get page structurediff --git a/cmd/pinchtab/cmd_cli_autostart_test.go b/cmd/pinchtab/cmd_cli_autostart_test.gonew file mode 100644index 00000000..0b4e6b23--- /dev/null+++ b/cmd/pinchtab/cmd_cli_autostart_test.go@@ -0,0 +1,93 @@+package main++import (+ "io"+ "net/http"+ "net/http/httptest"+ "strconv"+ "testing"+)++func TestNavAutoStartsBeforeNavigateAndSnap(t *testing.T) {+ var paths []string++ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ paths = append(paths, r.URL.Path)+ switch r.URL.Path {+ case "/health":+ _, _ = io.WriteString(w, `{"status":"ok"}`)+ case "/navigate":+ _, _ = io.WriteString(w, `{"tabId":"T1","status":"ok"}`)+ case "/snapshot":+ _, _ = io.WriteString(w, `{"nodes":[]}`)+ default:+ http.NotFound(w, r)+ }+ }))+ defer ts.Close()++ oldServerURL := serverURL+ serverURL = ts.URL+ defer func() { serverURL = oldServerURL }()+ t.Setenv("XDG_STATE_HOME", t.TempDir())++ flags := navCmd.Flags()+ oldTab, _ := flags.GetString("tab")+ oldSnap, _ := flags.GetBool("snap")+ defer func() {+ _ = flags.Set("tab", oldTab)+ _ = flags.Set("snap", strconv.FormatBool(oldSnap))+ }()+ _ = flags.Set("tab", "")+ _ = flags.Set("snap", "true")++ _ = captureStdout(t, func() {+ navCmd.Run(navCmd, []string{"example.com"})+ })++ if len(paths) < 3 || paths[0] != "/health" || paths[1] != "/navigate" || paths[2] != "/snapshot" {+ t.Fatalf("request paths = %v, want /health, /navigate, /snapshot", paths)+ }+}++func TestSnapDoesNotAutoStartAndTreatsArgAsSelector(t *testing.T) {+ var paths []string+ var selector string++ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ paths = append(paths, r.URL.Path)+ switch r.URL.Path {+ case "/snapshot":+ selector = r.URL.Query().Get("selector")+ _, _ = io.WriteString(w, `{"nodes":[]}`)+ case "/health":+ t.Error("snap should not check health or auto-start")+ _, _ = io.WriteString(w, `{"status":"ok"}`)+ default:+ http.NotFound(w, r)+ }+ }))+ defer ts.Close()++ oldServerURL := serverURL+ serverURL = ts.URL+ defer func() { serverURL = oldServerURL }()++ flags := snapCmd.Flags()+ oldSelector, _ := flags.GetString("selector")+ defer func() {+ _ = flags.Set("selector", oldSelector)+ }()+ _ = flags.Set("selector", "")++ _ = captureStdout(t, func() {+ snapCmd.Run(snapCmd, []string{"#main"})+ })++ if selector != "#main" {+ t.Fatalf("snapshot selector = %q, want #main", selector)+ }+ if len(paths) != 1 || paths[0] != "/snapshot" {+ t.Fatalf("request paths = %v, want only /snapshot", paths)+ }+}diff --git a/cmd/pinchtab/cmd_cli_browser_inspect.go b/cmd/pinchtab/cmd_cli_browser_inspect.goindex 9d27597e..5f2dd65a 100644--- a/cmd/pinchtab/cmd_cli_browser_inspect.go+++ b/cmd/pinchtab/cmd_cli_browser_inspect.go@@ -7,9 +7,15 @@ import ()var snapCmd = &cobra.Command{- Use: "snap",+ Use: "snap [selector]",Short: "Snapshot accessibility tree",+ Args: cobra.MaximumNArgs(1),Run: func(cmd *cobra.Command, args []string) {+ if len(args) > 0 {+ if stringFlag(cmd, "selector") == "" {+ _ = cmd.Flags().Set("selector", args[0])+ }+ }runCLI(func(rt cliRuntime) {browseractions.Snapshot(rt.client, rt.base, rt.token, cmd)})diff --git a/cmd/pinchtab/cmd_cli_browser_nav.go b/cmd/pinchtab/cmd_cli_browser_nav.goindex 2981b56e..e4be5fc8 100644--- a/cmd/pinchtab/cmd_cli_browser_nav.go+++ b/cmd/pinchtab/cmd_cli_browser_nav.go@@ -26,7 +26,7 @@ var navCmd = &cobra.Command{Args: cobra.ExactArgs(1),Run: func(cmd *cobra.Command, args []string) {url := urls.Normalize(args[0])- runCLI(func(rt cliRuntime) {+ runCLIEnsuringServer("nav", func(rt cliRuntime) {tabID := browseractions.Navigate(rt.client, rt.base, rt.token, url, cmd)WriteTabStateFile(tabID)})@@ -74,22 +74,8 @@ var tabsCmd = &cobra.Command{browseractions.TabList(rt.client, rt.base, rt.token, cmd)return}- browseractions.TabFocus(rt.client, rt.base, rt.token, args[0], cmd)- })- },-}--var tabNewCmd = &cobra.Command{- Use: "new [url]",- Short: "Open a new tab",- Args: cobra.MaximumNArgs(1),- Run: func(cmd *cobra.Command, args []string) {- runCLI(func(rt cliRuntime) {- body := map[string]any{"action": "new"}- if len(args) > 0 {- body["url"] = urls.Normalize(args[0])- }- browseractions.TabNew(rt.client, rt.base, rt.token, body, cmd)+ tabID := browseractions.TabFocus(rt.client, rt.base, rt.token, args[0], cmd)+ WriteTabStateFile(tabID)})},}@@ -101,6 +87,7 @@ var tabCloseCmd = &cobra.Command{Run: func(cmd *cobra.Command, args []string) {runCLI(func(rt cliRuntime) {browseractions.TabClose(rt.client, rt.base, rt.token, args[0], cmd)+ ClearTabStateFileIfCurrent(args[0])})},}@@ -108,7 +95,7 @@ var tabCloseCmd = &cobra.Command{var tabHandoffCmd = &cobra.Command{Use: "handoff [id]",Short: "Pause tab automation for human handoff",- Long: "Mark a tab as paused_handoff so action routes block until resumed or timeout expires. Defaults to the current tab (PINCHTAB_TAB or state file).",+ Long: "Mark a tab as paused_handoff so action routes block until resumed or timeout expires. Defaults to the current tab from the state file.",Args: cobra.MaximumNArgs(1),Run: func(cmd *cobra.Command, args []string) {reason, _ := cmd.Flags().GetString("reason")@@ -123,7 +110,7 @@ var tabHandoffCmd = &cobra.Command{var tabResumeCmd = &cobra.Command{Use: "resume [id]",Short: "Resume a paused_handoff tab",- Long: "Resume automation on a paused tab. Defaults to the current tab (PINCHTAB_TAB or state file).",+ Long: "Resume automation on a paused tab. Defaults to the current tab from the state file.",Args: cobra.MaximumNArgs(1),Run: func(cmd *cobra.Command, args []string) {status, _ := cmd.Flags().GetString("status")@@ -137,7 +124,7 @@ var tabResumeCmd = &cobra.Command{var tabHandoffStatusCmd = &cobra.Command{Use: "handoff-status [id]",Short: "Show handoff status for a tab",- Long: "Show handoff status. Defaults to the current tab (PINCHTAB_TAB or state file).",+ Long: "Show handoff status. Defaults to the current tab from the state file.",Args: cobra.MaximumNArgs(1),Run: func(cmd *cobra.Command, args []string) {tabID := resolveTabArg(args)diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.goindex 5bd3bd6d..4dd98375 100644--- a/cmd/pinchtab/cmd_cli_register.go+++ b/cmd/pinchtab/cmd_cli_register.go@@ -61,18 +61,19 @@ func registerBrowserCommands() {cacheCmd,storageCmd,stateCmd,+ tabCloseCmd,tabHandoffCmd,tabResumeCmd,tabHandoffStatusCmd,)- // Register handoff/resume/handoff-status as subcommands of `tab` too so- // `pinchtab tab handoff <id>` keeps working alongside the top-level+ // Register close/handoff/resume/handoff-status as subcommands of `tab` too+ // so `pinchtab tab handoff <id>` keeps working alongside the top-level// `pinchtab handoff`. The commands carry GroupID="browser" (set by- // setCommandGroup above) — add the same group to tabsCmd so cobra- // accepts them without panicking.+ // setCommandGroup above) — add the same group to tabsCmd so cobra accepts+ // them without panicking.tabsCmd.AddGroup(&cobra.Group{ID: "browser", Title: "Browser"})- tabsCmd.AddCommand(tabNewCmd, tabCloseCmd, tabHandoffCmd, tabResumeCmd, tabHandoffStatusCmd)+ tabsCmd.AddCommand(tabCloseCmd, tabHandoffCmd, tabResumeCmd, tabHandoffStatusCmd)clipboardCmd.AddCommand(clipboardReadCmd, clipboardWriteCmd, clipboardCopyCmd, clipboardPasteCmd)keyboardCmd.AddCommand(keyboardTypeCmd, keyboardInsertTextCmd)dialogCmd.AddCommand(dialogAcceptCmd, dialogDismissCmd)@@ -350,7 +351,6 @@ func configureBrowserFlags() {findCmd,evalCmd,tabsCmd,- tabNewCmd,tabCloseCmd,tabHandoffCmd,tabResumeCmd,@@ -414,35 +414,28 @@ func addRootCommands(cmds ...*cobra.Command) {rootCmd.AddCommand(cmds...)}-// addTabFlag wires a --tab flag onto the given commands and defaults its-// value from (in priority order): $PINCHTAB_TAB env var, or the state file-// written by `nav`. This lets agents avoid threading `--tab "$TAB"` through-// every command:+// addTabFlag wires a --tab flag onto the given commands and defaults its value+// from the state file written by `nav`. This lets agents avoid threading+// `--tab "$TAB"` through every command://// pinchtab nav http://example.com # writes tab ID to state file// pinchtab snap -i -c # auto-reads from state file//-// Explicit --tab still wins (cobra flag precedence). If neither env var nor-// state file is set, the server picks the active tab as before.-// resolveTabArg returns the tab ID from args[0] when present, otherwise falls-// back to $PINCHTAB_TAB then the persisted state file written by `nav`.+// Explicit --tab still wins (cobra flag precedence). If no state file is set,+// the server picks the active tab as before.+// resolveTabArg returns the tab ID from args[0] when present, otherwise it+// falls back to the persisted state file written by `nav`.func resolveTabArg(args []string) string {if len(args) > 0 && args[0] != "" {return args[0]}- if env := os.Getenv("PINCHTAB_TAB"); env != "" {- return env- }return readTabStateFile()}func addTabFlag(cmds ...*cobra.Command) {- defaultTab := os.Getenv("PINCHTAB_TAB")- if defaultTab == "" {- defaultTab = readTabStateFile()- }+ defaultTab := readTabStateFile()for _, cmd := range cmds {- cmd.Flags().String("tab", defaultTab, "Tab ID (env: PINCHTAB_TAB)")+ cmd.Flags().String("tab", defaultTab, "Tab ID")}}@@ -476,6 +469,15 @@ func WriteTabStateFile(tabID string) {_ = os.WriteFile(path, []byte(tabID+"\n"), 0644)}+// ClearTabStateFileIfCurrent clears the current-tab state when the saved tab is+// known to have been closed.+func ClearTabStateFileIfCurrent(tabID string) {+ if tabID == "" || readTabStateFile() != tabID {+ return+ }+ _ = os.Remove(tabStateFile())+}+func addJSONFlag(cmds ...*cobra.Command) {for _, cmd := range cmds {cmd.Flags().Bool("json", false, "Output full JSON response instead of terse status")diff --git a/cmd/pinchtab/cmd_cli_runtime.go b/cmd/pinchtab/cmd_cli_runtime.goindex c05889bd..19f25e51 100644--- a/cmd/pinchtab/cmd_cli_runtime.go+++ b/cmd/pinchtab/cmd_cli_runtime.go@@ -23,11 +23,29 @@ func runCLI(fn func(cliRuntime)) {}func runCLIWith(cfg *config.RuntimeConfig, fn func(cliRuntime)) {- fn(cliRuntime{+ rt := cliRuntime{client: newCLIHTTPClient(resolveCLIAgentID()),base: resolveCLIBase(cfg),token: resolveCLIToken(cfg),- })+ }+ fn(rt)+}++func runCLIEnsuringServer(command string, fn func(cliRuntime)) {+ runCLIWithServerCheck(loadConfig(), command, fn)+}++func runCLIWithServerCheck(cfg *config.RuntimeConfig, command string, fn func(cliRuntime)) {+ rt := cliRuntime{+ client: newCLIHTTPClient(resolveCLIAgentID()),+ base: resolveCLIBase(cfg),+ token: resolveCLIToken(cfg),+ }+ if err := ensureServer(rt.base, rt.token, command); err != nil {+ fmt.Fprintf(os.Stderr, "pinchtab: %v\n", err)+ os.Exit(1)+ }+ fn(rt)}func newCLIHTTPClient(agentID string) *http.Client {diff --git a/cmd/pinchtab/cmd_config.go b/cmd/pinchtab/cmd_config.goindex 0c3fd647..c43c8b13 100644--- a/cmd/pinchtab/cmd_config.go+++ b/cmd/pinchtab/cmd_config.go@@ -11,6 +11,7 @@ import ("github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/config/workflow""github.com/pinchtab/pinchtab/internal/server"+ configschema "github.com/pinchtab/pinchtab/schema""github.com/spf13/cobra")@@ -55,6 +56,16 @@ func init() {handleConfigValidate()},})+ configSchemaCmd := &cobra.Command{+ Use: "schema",+ Short: "Print config JSON Schema information",+ Run: func(cmd *cobra.Command, args []string) {+ printSchema, _ := cmd.Flags().GetBool("print")+ handleConfigSchema(printSchema)+ },+ }+ configSchemaCmd.Flags().Bool("print", false, "Print the bundled schema JSON instead of the schema URL")+ configCmd.AddCommand(configSchemaCmd)configCmd.AddCommand(&cobra.Command{Use: "token",Short: "Copy the API token to clipboard",@@ -422,3 +433,18 @@ func handleConfigValidate() {fmt.Printf("Config file is valid: %s\n", configPath)}++func handleConfigSchema(printSchema bool) {+ if printSchema {+ if _, err := os.Stdout.Write(configschema.ConfigJSON); err != nil {+ fmt.Printf("Error writing schema: %v\n", err)+ os.Exit(1)+ }+ if len(configschema.ConfigJSON) == 0 || configschema.ConfigJSON[len(configschema.ConfigJSON)-1] != '\n' {+ fmt.Println()+ }+ return+ }++ fmt.Println(config.ConfigSchemaURL)+}diff --git a/cmd/pinchtab/cmd_config_test.go b/cmd/pinchtab/cmd_config_test.goindex d8c1eb78..3aa057b0 100644--- a/cmd/pinchtab/cmd_config_test.go+++ b/cmd/pinchtab/cmd_config_test.go@@ -1,6 +1,7 @@package mainimport (+ "encoding/json""os""path/filepath""strings"@@ -223,6 +224,48 @@ func TestConfigTokenSubcommandCopiesToClipboard(t *testing.T) {}}+func TestConfigSchemaSubcommandPrintsURL(t *testing.T) {+ resetConfigSchemaPrintFlag(t)+ t.Cleanup(func() {+ rootCmd.SetArgs(nil)+ resetConfigSchemaPrintFlag(t)+ })++ output := captureStdout(t, func() {+ rootCmd.SetArgs([]string{"config", "schema"})+ if err := rootCmd.Execute(); err != nil {+ t.Fatalf("Execute() error = %v", err)+ }+ })++ if got := strings.TrimSpace(output); got != config.ConfigSchemaURL {+ t.Fatalf("config schema output = %q, want %q", got, config.ConfigSchemaURL)+ }+}++func TestConfigSchemaSubcommandPrintsBundledSchema(t *testing.T) {+ resetConfigSchemaPrintFlag(t)+ t.Cleanup(func() {+ rootCmd.SetArgs(nil)+ resetConfigSchemaPrintFlag(t)+ })++ output := captureStdout(t, func() {+ rootCmd.SetArgs([]string{"config", "schema", "--print"})+ if err := rootCmd.Execute(); err != nil {+ t.Fatalf("Execute() error = %v", err)+ }+ })++ var raw map[string]any+ if err := json.Unmarshal([]byte(output), &raw); err != nil {+ t.Fatalf("schema output is not valid JSON: %v\n%s", err, output)+ }+ if raw["$id"] != config.ConfigSchemaURL {+ t.Fatalf("schema $id = %q, want %q", raw["$id"], config.ConfigSchemaURL)+ }+}+func TestCopyConfigTokenReturnsErrorWhenEmpty(t *testing.T) {err := copyConfigToken("")if err == nil {@@ -233,6 +276,18 @@ func TestCopyConfigTokenReturnsErrorWhenEmpty(t *testing.T) {}}+func resetConfigSchemaPrintFlag(t *testing.T) {+ t.Helper()++ cmd, _, err := rootCmd.Find([]string{"config", "schema"})+ if err != nil {+ t.Fatalf("find config schema command: %v", err)+ }+ if err := cmd.Flags().Set("print", "false"); err != nil {+ t.Fatalf("reset schema print flag: %v", err)+ }+}+func TestConfigSetMasksServerTokenInOutput(t *testing.T) {configPath := filepath.Join(t.TempDir(), "config.json")t.Setenv("PINCHTAB_CONFIG", configPath)diff --git a/cmd/pinchtab/cmd_mcp.go b/cmd/pinchtab/cmd_mcp.goindex b6bfb148..bad8bf87 100644--- a/cmd/pinchtab/cmd_mcp.go+++ b/cmd/pinchtab/cmd_mcp.go@@ -2,11 +2,7 @@ package mainimport ("fmt"- "log/slog"- "net/http""os"- "os/exec"- "time""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/mcp"@@ -32,18 +28,9 @@ func runMCP(cfg *config.RuntimeConfig) {baseURL := resolveCLIBase(cfg)token := resolveCLIToken(cfg)- if !isServerHealthy(baseURL, token) {- slog.Info("server not running, starting automatically", "url", baseURL)- if err := autoStartServer(); err != nil {- slog.Error("failed to auto-start server", "err", err)- fmt.Fprintf(os.Stderr, "mcp: server at %s is not running and auto-start failed: %v\n", baseURL, err)- os.Exit(1)- }- if !waitForServer(baseURL, token, 30*time.Second) {- fmt.Fprintf(os.Stderr, "mcp: server did not become healthy at %s within 30s\n", baseURL)- os.Exit(1)- }- slog.Info("server started successfully")+ if err := ensureServer(baseURL, token, "mcp"); err != nil {+ fmt.Fprintf(os.Stderr, "mcp: %v\n", err)+ os.Exit(1)}mcp.Version = version@@ -53,63 +40,3 @@ func runMCP(cfg *config.RuntimeConfig) {os.Exit(1)}}--func isServerHealthy(baseURL, token string) bool {- client := &http.Client{Timeout: 3 * time.Second}- req, err := http.NewRequest(http.MethodGet, baseURL+"/health", nil)- if err != nil {- return false- }- if token != "" {- req.Header.Set("Authorization", "Bearer "+token)- }- resp, err := client.Do(req)- if err != nil {- return false- }- defer func() { _ = resp.Body.Close() }()- return resp.StatusCode < 500-}--func autoStartServer() error {- binary, err := os.Executable()- if err != nil {- return fmt.Errorf("resolve executable: %w", err)- }-- // Build args: forward --server flag if set, plus "server" subcommand- args := []string{"server"}- if serverURL != "" {- args = []string{"--server", serverURL, "server"}- }-- cmd := exec.Command(binary, args...) // #nosec G204 -- binary is our own executable from os.Executable(), args are hardcoded subcommands- cmd.Stdin = nil- cmd.Stdout = nil- cmd.Stderr = nil- // Detach from parent process group so the server survives if the- // MCP process exits.- detachProcess(cmd)-- if err := cmd.Start(); err != nil {- return fmt.Errorf("spawn server: %w", err)- }-- // Release the child so it's not reaped when we exit.- if err := cmd.Process.Release(); err != nil {- slog.Warn("failed to release server process", "err", err)- }-- return nil-}--func waitForServer(baseURL, token string, timeout time.Duration) bool {- deadline := time.Now().Add(timeout)- for time.Now().Before(deadline) {- if isServerHealthy(baseURL, token) {- return true- }- time.Sleep(500 * time.Millisecond)- }- return false-}diff --git a/cmd/pinchtab/cmd_mcp_test.go b/cmd/pinchtab/cmd_mcp_test.goindex bb0ff8b1..12d66ebf 100644--- a/cmd/pinchtab/cmd_mcp_test.go+++ b/cmd/pinchtab/cmd_mcp_test.go@@ -1,6 +1,7 @@package mainimport (+ "errors""net/http""net/http/httptest""testing"@@ -65,3 +66,79 @@ func TestWaitForServer_ImmediatelyHealthy(t *testing.T) {t.Fatal("expected immediately healthy server to return true")}}++func TestEnsureServerNoopWhenHealthy(t *testing.T) {+ started := false++ err := ensureServerWith(+ "http://127.0.0.1:9867",+ "",+ "test",+ func() error {+ started = true+ return nil+ },+ func(baseURL, token string) bool {+ return true+ },+ time.Second,+ )++ if err != nil {+ t.Fatalf("ensureServerWith() error = %v", err)+ }+ if started {+ t.Fatal("expected healthy server to skip auto-start")+ }+}++func TestEnsureServerStartsAndWaits(t *testing.T) {+ started := false+ healthChecks := 0++ err := ensureServerWith(+ "http://127.0.0.1:9867",+ "",+ "test",+ func() error {+ started = true+ return nil+ },+ func(baseURL, token string) bool {+ healthChecks+++ return started && healthChecks >= 2+ },+ time.Second,+ )++ if err != nil {+ t.Fatalf("ensureServerWith() error = %v", err)+ }+ if !started {+ t.Fatal("expected auto-start to run")+ }+ if healthChecks < 2 {+ t.Fatalf("expected health to be checked before and after start, got %d checks", healthChecks)+ }+}++func TestEnsureServerReturnsStartError(t *testing.T) {+ wantErr := errors.New("boom")++ err := ensureServerWith(+ "http://127.0.0.1:9867",+ "",+ "test",+ func() error {+ return wantErr+ },+ func(baseURL, token string) bool {+ return false+ },+ time.Second,+ )++ if !errors.Is(err, wantErr) {+ t.Fatalf("ensureServerWith() error = %v, want wrapped %v", err, wantErr)+ }+}diff --git a/cmd/pinchtab/cmd_server_ensure.go b/cmd/pinchtab/cmd_server_ensure.gonew file mode 100644index 00000000..fbc4033e--- /dev/null+++ b/cmd/pinchtab/cmd_server_ensure.go@@ -0,0 +1,98 @@+package main++import (+ "fmt"+ "log/slog"+ "net/http"+ "os"+ "os/exec"+ "time"+)++const ensureServerTimeout = 30 * time.Second++type serverStartFunc func() error+type serverHealthFunc func(baseURL, token string) bool++func ensureServer(baseURL, token, command string) error {+ return ensureServerWith(baseURL, token, command, autoStartServer, isServerHealthy, ensureServerTimeout)+}++func ensureServerWith(baseURL, token, command string, start serverStartFunc, healthy serverHealthFunc, timeout time.Duration) error {+ if healthy(baseURL, token) {+ return nil+ }++ slog.Info("server not running, starting automatically", "url", baseURL, "command", command)+ if err := start(); err != nil {+ slog.Error("failed to auto-start server", "err", err, "command", command)+ return fmt.Errorf("server at %s is not running and auto-start failed: %w", baseURL, err)+ }++ if !waitForServerWith(baseURL, token, timeout, healthy) {+ return fmt.Errorf("server did not become healthy at %s within %s", baseURL, timeout)+ }++ slog.Info("server started successfully", "url", baseURL, "command", command)+ return nil+}++func isServerHealthy(baseURL, token string) bool {+ client := &http.Client{Timeout: 3 * time.Second}+ req, err := http.NewRequest(http.MethodGet, baseURL+"/health", nil)+ if err != nil {+ return false+ }+ if token != "" {+ req.Header.Set("Authorization", "Bearer "+token)+ }+ resp, err := client.Do(req)+ if err != nil {+ return false+ }+ defer func() { _ = resp.Body.Close() }()+ return resp.StatusCode < 500+}++func autoStartServer() error {+ binary, err := os.Executable()+ if err != nil {+ return fmt.Errorf("resolve executable: %w", err)+ }++ args := []string{"server"}+ if serverURL != "" {+ args = []string{"--server", serverURL, "server"}+ }++ cmd := exec.Command(binary, args...) // #nosec G204 -- binary is our own executable from os.Executable(), args are hardcoded subcommands+ cmd.Stdin = nil+ cmd.Stdout = nil+ cmd.Stderr = nil+ detachProcess(cmd)++ if err := cmd.Start(); err != nil {+ return fmt.Errorf("spawn server: %w", err)+ }++ if err := cmd.Process.Release(); err != nil {+ slog.Warn("failed to release server process", "err", err)+ }++ return nil+}++func waitForServer(baseURL, token string, timeout time.Duration) bool {+ return waitForServerWith(baseURL, token, timeout, isServerHealthy)+}++func waitForServerWith(baseURL, token string, timeout time.Duration, healthy serverHealthFunc) bool {+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ if healthy(baseURL, token) {+ return true+ }+ time.Sleep(500 * time.Millisecond)+ }+ return false+}diff --git a/dashboard/src/pages/settings/DefaultsSettingsSection.tsx b/dashboard/src/pages/settings/DefaultsSettingsSection.tsxindex e6dbecf0..212d2cb3 100644--- a/dashboard/src/pages/settings/DefaultsSettingsSection.tsx+++ b/dashboard/src/pages/settings/DefaultsSettingsSection.tsx@@ -142,12 +142,10 @@ export function DefaultsSettingsSection({</SettingRow><SettingRowlabel="Tab lifecycle"- description="Auto-close idle tabs after a /text, /snapshot, or /action response. The timer resets on each subsequent request and is cancelled by /navigate."+ description="Optionally auto-close idle tabs after a /text, /snapshot, or /action response. The timer resets on each subsequent request and is cancelled by /navigate."><Select- value={- backendConfig.instanceDefaults.tabPolicy?.lifecycle ?? "close_idle"- }+ value={backendConfig.instanceDefaults.tabPolicy?.lifecycle ?? "keep"}onChange={(e) =>updateBackendSection("instanceDefaults", {tabPolicy: {@@ -180,8 +178,8 @@ export function DefaultsSettingsSection({})}disabled={- (backendConfig.instanceDefaults.tabPolicy?.lifecycle ??- "close_idle") !== "close_idle"+ (backendConfig.instanceDefaults.tabPolicy?.lifecycle ?? "keep") !==+ "close_idle"}className={fieldClass}/>diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.tsindex cf2c26c0..a6edd12e 100644--- a/dashboard/src/types/index.ts+++ b/dashboard/src/types/index.ts@@ -250,7 +250,7 @@ export const defaultBackendConfig: BackendConfig = {stealthLevel: "light",tabEvictionPolicy: "close_lru",tabPolicy: {- lifecycle: "close_idle",+ lifecycle: "keep",closeDelaySec: 300,restore: false,},diff --git a/docs/commands.md b/docs/commands.mdindex d3c32f3d..dbe54fee 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -17,10 +17,8 @@ pinchtab completion <shell> # Generate shell completions## Navigation-`pinchtab nav <url>` uses `/navigate`. When you do not pass `--tab`, PinchTab opens a new tab and navigates it.-```bash-pinchtab nav <url> # Open a new tab and navigate it+pinchtab nav <url> # Navigate current tab, or create one if neededpinchtab nav <url> --tab <id> # Reuse a specific tabpinchtab nav <url> --new-tab # Explicitly force a new tabpinchtab nav <url> --block-images # Block images for this navigation@@ -32,19 +30,14 @@ pinchtab forward # Go forward in the active tabpinchtab reload # Reload the active tab```-Use `--tab <id>` when you intend to replace an existing tab's URL. Unscoped reads and actions use the current tracked tab, but unscoped `nav` intentionally opens a new tab to avoid replacing active work by accident.--Hidden aliases: `goto`, `navigate`, `open`-## Tabs-The `tab` command only lists, focuses, creates, and closes tabs. It does not proxy the rest of the browser command set.+The `tab` command only lists, focuses, and closes tabs. It does not proxy the rest of the browser command set.```bashpinchtab tab # List tabspinchtab tab <id> # Focus a tab by ID or 1-based index-pinchtab tab new # Open a blank tab-pinchtab tab new <url> # Open a tab and navigate it+pinchtab nav <url> --new-tab # Open a new tab and navigate itpinchtab tab close <id> # Close a tab```@@ -116,7 +109,7 @@ pinchtab drag e5 400,320## Page Analysis```bash-pinchtab snap # Accessibility snapshot+pinchtab snap [selector] # Accessibility snapshot, optionally scopedpinchtab snap -i -c # Interactive + compactpinchtab snap -d # Diff from previous snapshotpinchtab snap --selector <css> # Scope snapshotdiff --git a/docs/core-concepts.md b/docs/core-concepts.mdindex 3e3c3322..d5197c59 100644--- a/docs/core-concepts.md+++ b/docs/core-concepts.md@@ -190,12 +190,11 @@ curl -X POST http://localhost:9867/close \-d "{\"tabId\":\"$TAB\"}"```-By default, tabs also use the `close_idle` lifecycle policy: after an authorized-`/text`, `/snapshot`, or `/action` request finishes, the tab is auto-closed-after 300 seconds unless it is touched again first. Set-`instanceDefaults.tabPolicy.lifecycle` to `keep` to disable lifecycle-auto-close, or change `instanceDefaults.tabPolicy.closeDelaySec` to adjust the-delay.+By default, tabs use the `keep` lifecycle policy and are not auto-closed after+reads or actions. Set `instanceDefaults.tabPolicy.lifecycle` to `close_idle` to+auto-close a tab after an authorized `/text`, `/snapshot`, or `/action` request+finishes. `instanceDefaults.tabPolicy.closeDelaySec` adjusts the idle delay+when `close_idle` is enabled.### Are tabs persistent?diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex f88eb8ac..a16a238b 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -49,6 +49,12 @@ pinchtab find "login button"pinchtab network --limit 20```+`pinchtab nav <url>` auto-starts the local PinchTab server when it is not already running. To navigate and snapshot in one command after install, run:++```bash+pinchtab nav https://pinchtab.com --snap+```+Global flags such as `--server` and `--agent-id` apply to direct command mode. `--agent-id` is recorded in activity logs and dashboard agent views so multiple CLI-driven agents are distinguishable.## Agent Attribution@@ -126,7 +132,7 @@ Common commands:| --- | --- || `pinchtab nav <url>` | Open a new tab and navigate it || `pinchtab nav <url> --snap` | Navigate and output an interactive compact snapshot |-| `pinchtab snap` | Accessibility snapshot |+| `pinchtab snap [selector]` | Accessibility snapshot for the current tab, optionally scoped || `pinchtab frame [target\|main]` | Show or set selector frame scope || `pinchtab click <selector>` | Click an element || `pinchtab mouse move <x> <y>` | Move the pointer to coordinates |@@ -187,7 +193,6 @@ curl -X POST http://localhost:9867/tabs/<tabId>/resume \```bashpinchtab tabpinchtab tab <id>-pinchtab tab new [url]pinchtab tab close <id>pinchtab tab handoff <id>pinchtab tab handoff-status <id>diff --git a/docs/reference/config.md b/docs/reference/config.mdindex 4be1f488..7515d1fd 100644--- a/docs/reference/config.md+++ b/docs/reference/config.md@@ -39,6 +39,22 @@ pinchtab config init`config init` respects `PINCHTAB_CONFIG`. If that environment variable is set, the file is created there.+Generated config files include a versioned `$schema` URL for IDE completion and validation.++### `pinchtab config schema`++Prints the versioned JSON Schema URL for this PinchTab build.++```bash+pinchtab config schema+```++Print the bundled schema JSON:++```bash+pinchtab config schema --print+```+### `pinchtab config show`Shows the effective runtime configuration.@@ -144,6 +160,7 @@ Current nested file-config shape:```json{+ "$schema": "https://raw.githubusercontent.com/pinchtab/pinchtab/v0.8.0/schema/config.json","configVersion": "0.8.0","server": {"port": "9867",@@ -176,7 +193,7 @@ Current nested file-config shape:"stealthLevel": "light","tabEvictionPolicy": "close_lru","tabPolicy": {- "lifecycle": "close_idle",+ "lifecycle": "keep","closeDelaySec": 300,"restore": false},@@ -354,7 +371,7 @@ You can change or clear that default with `browser.extensionPaths`."instanceDefaults": {"tabPolicy": {"eviction": "close_lru",- "lifecycle": "close_idle",+ "lifecycle": "keep","closeDelaySec": 300,"restore": false}@@ -363,8 +380,8 @@ You can change or clear that default with `browser.extensionPaths`.```- `eviction` controls what happens when `maxTabs` is reached: `close_lru`, `close_oldest`, or `reject`.-- `lifecycle` controls idle lifecycle behavior: `close_idle` auto-closes a tab after it handles an authorized `/text`, `/snapshot`, or `/action` request; `keep` disables lifecycle auto-close.-- `closeDelaySec` is the idle delay for `close_idle`. The default is `300` seconds.+- `lifecycle` controls idle lifecycle behavior: `keep` disables lifecycle auto-close and is the default; `close_idle` auto-closes a tab after it handles an authorized `/text`, `/snapshot`, or `/action` request.+- `closeDelaySec` is the idle delay for `close_idle`. The default is `300` seconds when auto-close is enabled.- `restore` controls whether session tabs are restored on startup. The default is `false`.`instanceDefaults.tabEvictionPolicy` is still accepted for compatibility. New configs should use `instanceDefaults.tabPolicy.eviction`.diff --git a/docs/reference/navigate.md b/docs/reference/navigate.mdindex 465edadd..413e2793 100644--- a/docs/reference/navigate.md+++ b/docs/reference/navigate.md@@ -1,6 +1,6 @@# Navigate-Open a new tab and navigate it to a URL, or reuse a tab when a tab ID is provided.+Navigate the current tracked tab to a URL, or create a tab when no current tab is available.```bashcurl -X POST http://localhost:9867/navigate \@@ -14,6 +14,9 @@ pinchtab nav https://pinchtab.com## CLI Flags+`pinchtab nav <url>` auto-starts the local server when it is not already running.+Hidden aliases: `goto`, `navigate`, `open`.+| Flag | Description ||------|-------------|| `--tab` | Reuse existing tab |@@ -28,10 +31,11 @@ pinchtab nav https://pinchtab.com## Examples```bash-pinchtab nav https://example.com # Navigate, print tab ID+pinchtab nav https://example.com # Navigate current tab, or create onepinchtab nav https://example.com --snap # Navigate and snapshotTAB=$(pinchtab nav https://example.com) # Capture tab ID for reusepinchtab nav https://other.com --tab "$TAB" # Reuse tab+pinchtab nav https://example.com --new-tab # Force another tabpinchtab nav https://example.com --block-images # Skip images```@@ -50,12 +54,13 @@ pinchtab nav https://example.com --block-images # Skip images## Behavior-- Top-level `POST /navigate` and `pinchtab nav <url>` open a new tab when no `tabId` or `--tab` is provided.+- Top-level `POST /navigate` opens a new tab when no `tabId` is provided.+- `pinchtab nav <url>` uses the current tracked tab when one is available; otherwise it opens a new tab.- `POST /tabs/{id}/navigate`, `POST /navigate` with `tabId`, and `pinchtab nav <url> --tab <id>` reuse the specified tab and make it the current tab for later unscoped operations.- `--new-tab` and `newTab:true` force a new tab even if another tab is current.- Commands that operate without `--tab` use the current tracked tab. Focusing or using a tab updates that current-tab pointer; if the pointer is stale, PinchTab falls back to the most recently used tracked tab.-Rationale: unscoped navigation should not accidentally replace the user or agent's active work surface. Reuse is explicit through `--tab`/`tabId`, while later unscoped read/action commands still have predictable current-tab behavior.+Rationale: the CLI keeps one obvious work surface by default. Use `--new-tab` when you intentionally want another tab, or `--tab`/`tabId` when you need a specific tab.## Related Pagesdiff --git a/docs/reference/tabs.md b/docs/reference/tabs.mdindex a22747dc..07842bd4 100644--- a/docs/reference/tabs.md+++ b/docs/reference/tabs.md@@ -101,22 +101,21 @@ curl http://localhost:9867/instances/tabsUse `GET /instances/tabs` when you need the orchestrator-wide view.-## Focus, Create, And Close From The CLI+## Focus And Close From The CLI```bashpinchtab tab # list tabspinchtab tab 2 # focus tab by 1-based indexpinchtab tab 8f9c7d4e1234... # focus tab by tab ID-pinchtab tab new # open blank tab-pinchtab tab new https://pinchtab.com # open and navigate+pinchtab nav https://pinchtab.com --new-tab # open a new tab and navigate itpinchtab tab close 8f9c7d4e1234... # close tab```Numeric arguments are resolved as 1-based indices against `GET /tabs`. Non-numeric arguments are treated as tab IDs.-Focusing, creating, navigating, or otherwise accessing a tracked tab marks it as the current tab. Unscoped commands use that current tab; if the recorded current tab has gone stale, PinchTab falls back to the most recently used tracked tab.+Focusing, navigating, or otherwise accessing a tracked tab marks it as the current tab. Unscoped commands use that current tab; if the recorded current tab has gone stale, PinchTab falls back to the most recently used tracked tab.-Top-level navigation is intentionally different from unscoped reads/actions: `pinchtab nav <url>` opens a new tab unless you pass `--tab <id>`. This keeps new navigations from replacing an existing work surface by accident.+Top-level navigation uses the current tab when one is available. Use `pinchtab nav <url> --new-tab` when you explicitly want another tab.## Operate On An Existing Tabdiff --git a/internal/cli/actions/actions_navigate.go b/internal/cli/actions/actions_navigate.goindex 2726e6e3..5b14278d 100644--- a/internal/cli/actions/actions_navigate.go+++ b/internal/cli/actions/actions_navigate.go@@ -102,6 +102,32 @@ func Reload(client *http.Client, base, token string, cmd *cobra.Command) {}func Navigate(client *http.Client, base, token string, url string, cmd *cobra.Command) string {+ path, body := buildNavigateRequest(client, base, token, url, cmd)++ // JSON output mode+ jsonOutput, _ := cmd.Flags().GetBool("json")+ if jsonOutput {+ result := apiclient.DoPost(client, base, token, path, body)+ apiclient.SuggestNextAction("navigate", result)+ return tabIDFromNavigateResult(result)+ }++ resultTabID := postNavigateQuiet(client, base, token, path, body)+ if resultTabID != "" {+ fmt.Println(resultTabID)+ }++ // If --snap or --snap-diff flag is set, fetch and output snapshot+ snap, _ := cmd.Flags().GetBool("snap")+ snapDiff, _ := cmd.Flags().GetBool("snap-diff")+ if snap || snapDiff {+ fetchAndPrintSnapshot(client, base, token, resultTabID, snapDiff)+ }++ return resultTabID+}++func buildNavigateRequest(client *http.Client, base, token, url string, cmd *cobra.Command) (string, map[string]any) {body := map[string]any{"url": url}newTab, _ := cmd.Flags().GetBool("new-tab")if newTab {@@ -115,33 +141,25 @@ func Navigate(client *http.Client, base, token string, url string, cmd *cobra.Co}tabID, _ := cmd.Flags().GetString("tab")path := "/navigate"- // Don't use tab-specific path when creating a new tab- if tabID != "" && !newTab {+ explicitTab := cmd.Flags().Changed("tab")+ // Don't use tab-specific path when creating a new tab. If the tab came from+ // the saved current-tab state file and no longer exists, treat it as no+ // current tab and let /navigate create one.+ if tabID != "" && !newTab && (explicitTab || tabExists(client, base, token, tabID)) {path = "/tabs/" + tabID + "/navigate"}- // JSON output mode- jsonOutput, _ := cmd.Flags().GetBool("json")- if jsonOutput {- result := apiclient.DoPost(client, base, token, path, body)- apiclient.SuggestNextAction("navigate", result)- return ""- }+ return path, body+}- // Terse mode: emit only the tabId (default, or when --print-tab-id / pipe)+func postNavigateQuiet(client *http.Client, base, token, path string, body map[string]any) string {result := apiclient.DoPostQuiet(client, base, token, path, body)- resultTabID := ""- if tid, ok := result["tabId"].(string); ok && tid != "" {- resultTabID = tid- fmt.Println(tid)- }+ return tabIDFromNavigateResult(result)+}- // If --snap or --snap-diff flag is set, fetch and output snapshot- snap, _ := cmd.Flags().GetBool("snap")- snapDiff, _ := cmd.Flags().GetBool("snap-diff")- if snap || snapDiff {- fetchAndPrintSnapshot(client, base, token, resultTabID, snapDiff)+func tabIDFromNavigateResult(result map[string]any) string {+ if tid, ok := result["tabId"].(string); ok && tid != "" {+ return tid}-- return resultTabID+ return ""}diff --git a/internal/cli/actions/actions_navigate_test.go b/internal/cli/actions/actions_navigate_test.goindex 939d7307..270ed4b7 100644--- a/internal/cli/actions/actions_navigate_test.go+++ b/internal/cli/actions/actions_navigate_test.go@@ -38,6 +38,54 @@ func TestNavigate(t *testing.T) {}}+func TestNavigateReusesImplicitTabWhenItExists(t *testing.T) {+ m := newMockServer()+ m.response = `{"tabs":[{"id":"ABC123"}],"tabId":"ABC123","status":"ok"}`+ defer m.close()+ client := m.server.Client()++ cmd := newNavigateCmd()+ cmd.Flags().Lookup("tab").DefValue = "ABC123"+ _ = cmd.Flags().Set("tab", "ABC123")+ cmd.Flags().Lookup("tab").Changed = false++ Navigate(client, m.base(), "", "https://pinchtab.com", cmd)++ if len(m.requests) != 2 {+ t.Fatalf("requests = %d, want 2", len(m.requests))+ }+ if m.requests[0].Path != "/tabs" {+ t.Fatalf("first request path = %q, want /tabs", m.requests[0].Path)+ }+ if m.requests[1].Path != "/tabs/ABC123/navigate" {+ t.Fatalf("navigate path = %q, want /tabs/ABC123/navigate", m.requests[1].Path)+ }+}++func TestNavigateFallsBackToNewTabForStaleImplicitTab(t *testing.T) {+ m := newMockServer()+ m.response = `{"tabs":[],"tabId":"NEW123","status":"ok"}`+ defer m.close()+ client := m.server.Client()++ cmd := newNavigateCmd()+ cmd.Flags().Lookup("tab").DefValue = "STALE123"+ _ = cmd.Flags().Set("tab", "STALE123")+ cmd.Flags().Lookup("tab").Changed = false++ Navigate(client, m.base(), "", "https://pinchtab.com", cmd)++ if len(m.requests) != 2 {+ t.Fatalf("requests = %d, want 2", len(m.requests))+ }+ if m.requests[0].Path != "/tabs" {+ t.Fatalf("first request path = %q, want /tabs", m.requests[0].Path)+ }+ if m.requests[1].Path != "/navigate" {+ t.Fatalf("navigate path = %q, want /navigate", m.requests[1].Path)+ }+}+func TestNavigateWithAllFlags(t *testing.T) {m := newMockServer()defer m.close()diff --git a/internal/cli/actions/actions_system.go b/internal/cli/actions/actions_system.goindex 405a773e..dbe81813 100644--- a/internal/cli/actions/actions_system.go+++ b/internal/cli/actions/actions_system.go@@ -145,12 +145,6 @@ func getInstances(client *http.Client, base, token string) []map[string]any {return instances}-// launchInstance launches a managed instance for the requested profile.-func launchInstance(client *http.Client, base, token string, profile string) {- body := map[string]any{"profileId": profile}- apiclient.DoPost(client, base, token, "/instances/start", body)-}-func decodeInstancesResponse(body []byte) ([]map[string]any, error) {var instances []map[string]anyif err := json.Unmarshal(body, &instances); err == nil {diff --git a/internal/cli/actions/actions_tab_lookup.go b/internal/cli/actions/actions_tab_lookup.gonew file mode 100644index 00000000..47861d9a--- /dev/null+++ b/internal/cli/actions/actions_tab_lookup.go@@ -0,0 +1,77 @@+package actions++import (+ "encoding/json"+ "fmt"+ "net/http"+ "strconv"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+)++func tabExists(client *http.Client, base, token, tabID string) bool {+ if tabID == "" {+ return false+ }+ tabIDs, err := listTabIDs(client, base, token)+ if err != nil {+ return false+ }+ for _, id := range tabIDs {+ if id == tabID {+ return true+ }+ }+ return false+}++func resolveTabReference(client *http.Client, base, token, ref string) (string, error) {+ index, err := strconv.Atoi(ref)+ if err != nil {+ return ref, nil+ }+ if index < 1 {+ return "", fmt.Errorf("tab index %d out of range", index)+ }++ tabIDs, err := listTabIDs(client, base, token)+ if err != nil {+ return "", err+ }+ if index > len(tabIDs) {+ return "", fmt.Errorf("tab index %d out of range (1-%d)", index, len(tabIDs))+ }+ return tabIDs[index-1], nil+}++func listTabIDs(client *http.Client, base, token string) ([]string, error) {+ body := apiclient.DoGetRaw(client, base, token, "/tabs", nil)+ var resp struct {+ Tabs []struct {+ ID string `json:"id"`+ } `json:"tabs"`+ }+ if err := json.Unmarshal(body, &resp); err == nil && resp.Tabs != nil {+ ids := make([]string, 0, len(resp.Tabs))+ for _, tab := range resp.Tabs {+ if tab.ID != "" {+ ids = append(ids, tab.ID)+ }+ }+ return ids, nil+ }++ var tabs []struct {+ ID string `json:"id"`+ }+ if err := json.Unmarshal(body, &tabs); err != nil {+ return nil, err+ }+ ids := make([]string, 0, len(tabs))+ for _, tab := range tabs {+ if tab.ID != "" {+ ids = append(ids, tab.ID)+ }+ }+ return ids, nil+}diff --git a/internal/cli/actions/actions_tabs.go b/internal/cli/actions/actions_tabs.goindex 7a4f65c1..077779a2 100644--- a/internal/cli/actions/actions_tabs.go+++ b/internal/cli/actions/actions_tabs.go@@ -4,7 +4,6 @@ import ("encoding/json""fmt""net/http"- "os""github.com/pinchtab/pinchtab/internal/cli""github.com/pinchtab/pinchtab/internal/cli/apiclient"@@ -40,30 +39,6 @@ func TabList(client *http.Client, base, token string, cmd *cobra.Command) {}}-// TabNew opens a new tab (exported for cobra subcommand).-func TabNew(client *http.Client, base, token string, body map[string]any, cmd *cobra.Command) {- // Check if any instances are running- instances := getInstances(client, base, token)- if len(instances) == 0 {- fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.WarningStyle, "No instances running, launching default..."))- launchInstance(client, base, token, "default")- fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.SuccessStyle, "Instance launched"))- }-- jsonOutput, _ := cmd.Flags().GetBool("json")- if jsonOutput {- apiclient.DoPost(client, base, token, "/tab", body)- return- }-- result := apiclient.DoPostQuiet(client, base, token, "/tab", body)- if tabID, ok := result["tabId"].(string); ok {- output.Value(tabID)- } else {- output.Success()- }-}-// TabClose closes a tab by ID.func TabClose(client *http.Client, base, token string, tabID string, cmd *cobra.Command) {jsonOutput, _ := cmd.Flags().GetBool("json")@@ -78,21 +53,34 @@ func TabClose(client *http.Client, base, token string, tabID string, cmd *cobra.// TabFocus switches to a tab by ID, making it the active tab// for subsequent commands.-func TabFocus(client *http.Client, base, token string, tabID string, cmd *cobra.Command) {+func TabFocus(client *http.Client, base, token string, tabID string, cmd *cobra.Command) string {+ resolvedTabID, err := resolveTabReference(client, base, token, tabID)+ if err != nil {+ cli.Fatal("%v", err)+ }+jsonOutput, _ := cmd.Flags().GetBool("json")if jsonOutput {- apiclient.DoPost(client, base, token, "/tab", map[string]any{+ result := apiclient.DoPost(client, base, token, "/tab", map[string]any{"action": "focus",- "tabId": tabID,+ "tabId": resolvedTabID,})- return+ if tid, ok := result["tabId"].(string); ok && tid != "" {+ return tid+ }+ return resolvedTabID}- apiclient.DoPostQuiet(client, base, token, "/tab", map[string]any{+ result := apiclient.DoPostQuiet(client, base, token, "/tab", map[string]any{"action": "focus",- "tabId": tabID,+ "tabId": resolvedTabID,})- output.Value(tabID)+ if tid, ok := result["tabId"].(string); ok && tid != "" {+ output.Value(tid)+ return tid+ }+ output.Value(resolvedTabID)+ return resolvedTabID}// TabHandoff pauses automation on a tab for manual operator intervention.diff --git a/internal/cli/actions/actions_tabs_test.go b/internal/cli/actions/actions_tabs_test.goindex f916f460..c80c1d90 100644--- a/internal/cli/actions/actions_tabs_test.go+++ b/internal/cli/actions/actions_tabs_test.go@@ -27,3 +27,51 @@ func TestTabCloseUsesCloseEndpoint(t *testing.T) {t.Fatalf("close endpoint body should not include legacy action field, got %s", m.lastBody)}}++func TestTabFocusUsesResolvedTabID(t *testing.T) {+ m := newMockServer()+ m.response = `{"focused":true,"tabId":"tab_123"}`+ defer m.close()++ cmd := &cobra.Command{}+ cmd.Flags().Bool("json", false, "")++ got := TabFocus(http.DefaultClient, m.base(), "", "tab_123", cmd)++ if got != "tab_123" {+ t.Fatalf("focused tab = %q, want tab_123", got)+ }+ if m.lastPath != "/tab" {+ t.Fatalf("expected /tab, got %s", m.lastPath)+ }+ if !strings.Contains(m.lastBody, `"tabId":"tab_123"`) {+ t.Fatalf("expected tabId in body, got %s", m.lastBody)+ }+}++func TestTabFocusResolvesOneBasedIndex(t *testing.T) {+ m := newMockServer()+ m.response = `{"tabs":[{"id":"tab_1"},{"id":"tab_2"}]}`+ defer m.close()++ cmd := &cobra.Command{}+ cmd.Flags().Bool("json", false, "")++ got := TabFocus(http.DefaultClient, m.base(), "", "2", cmd)++ if got != "tab_2" {+ t.Fatalf("focused tab = %q, want tab_2", got)+ }+ if len(m.requests) != 2 {+ t.Fatalf("requests = %d, want 2", len(m.requests))+ }+ if m.requests[0].Path != "/tabs" {+ t.Fatalf("first request path = %q, want /tabs", m.requests[0].Path)+ }+ if m.requests[1].Path != "/tab" {+ t.Fatalf("second request path = %q, want /tab", m.requests[1].Path)+ }+ if !strings.Contains(m.requests[1].Body, `"tabId":"tab_2"`) {+ t.Fatalf("expected resolved tabId in body, got %s", m.requests[1].Body)+ }+}diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex 5351726d..f2a74e06 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -7,6 +7,9 @@ import (// CurrentConfigVersion is bumped when config schema changes require migration or wizard re-run.const CurrentConfigVersion = "0.8.0"+// ConfigSchemaURL is the immutable JSON Schema URL for the current config line.+const ConfigSchemaURL = "https://raw.githubusercontent.com/pinchtab/pinchtab/v" + CurrentConfigVersion + "/schema/config.json"+// DefaultFileConfig returns a FileConfig with sensible defaults (nested format).func DefaultFileConfig() FileConfig {start := 9868@@ -57,6 +60,7 @@ func DefaultFileConfig() FileConfig {autoSolverRetryMaxDelayMs := 10000autoSolverLLMFallback := falsereturn FileConfig{+ Schema: ConfigSchemaURL,ConfigVersion: CurrentConfigVersion,Server: ServerConfig{Port: defaultPort,diff --git a/internal/config/config_file_json.go b/internal/config/config_file_json.goindex a2642e94..ee7f4d24 100644--- a/internal/config/config_file_json.go+++ b/internal/config/config_file_json.go@@ -1,6 +1,7 @@package configtype fileConfigJSON struct {+ Schema string `json:"$schema,omitempty"`ConfigVersion string `json:"configVersion,omitempty"`Server serverConfigJSON `json:"server"`Browser browserConfigJSON `json:"browser"`diff --git a/internal/config/config_file_marshal.go b/internal/config/config_file_marshal.goindex db626512..f13382d2 100644--- a/internal/config/config_file_marshal.go+++ b/internal/config/config_file_marshal.go@@ -32,7 +32,7 @@ func tabPolicyDefaultsFromRuntime(cfg *RuntimeConfig) *TabPolicyDefaults {return nil}hasLifecycle := cfg.TabLifecyclePolicy != "" &&- (cfg.TabLifecyclePolicy != "close_idle" || cfg.TabCloseDelay != 5*time.Minute)+ (cfg.TabLifecyclePolicy != "keep" || cfg.TabCloseDelay != 5*time.Minute)hasRestore := cfg.TabRestoreif !hasLifecycle && !hasRestore {return nil@@ -40,7 +40,7 @@ func tabPolicyDefaultsFromRuntime(cfg *RuntimeConfig) *TabPolicyDefaults {out := &TabPolicyDefaults{}if hasLifecycle {out.Lifecycle = cfg.TabLifecyclePolicy- if cfg.TabLifecyclePolicy == "close_idle" && cfg.TabCloseDelay > 0 {+ if cfg.TabLifecyclePolicy == "close_idle" && cfg.TabCloseDelay > 0 && cfg.TabCloseDelay != 5*time.Minute {sec := int(cfg.TabCloseDelay / time.Second)out.CloseDelaySec = &sec}@@ -54,6 +54,7 @@ func tabPolicyDefaultsFromRuntime(cfg *RuntimeConfig) *TabPolicyDefaults {func (fc FileConfig) MarshalJSON() ([]byte, error) {return json.Marshal(fileConfigJSON{+ Schema: fc.Schema,ConfigVersion: fc.ConfigVersion,Server: serverConfigJSON{Port: fc.Server.Port,@@ -304,6 +305,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {}fc := FileConfig{+ Schema: ConfigSchemaURL,Server: ServerConfig{Port: cfg.Port,Bind: cfg.Bind,diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.goindex 6dc8dec4..fbe067f6 100644--- a/internal/config/config_file_test.go+++ b/internal/config/config_file_test.go@@ -2,12 +2,16 @@ package configimport ("encoding/json"+ "strings""testing""time")func TestDefaultFileConfig(t *testing.T) {fc := DefaultFileConfig()+ if fc.Schema != ConfigSchemaURL {+ t.Errorf("DefaultFileConfig.Schema = %q, want %q", fc.Schema, ConfigSchemaURL)+ }if fc.Server.Port != "9867" {t.Errorf("DefaultFileConfig.Server.Port = %v, want 9867", fc.Server.Port)}@@ -219,18 +223,18 @@ func TestConvertLegacyConfig(t *testing.T) {func TestTabPolicyDefaultsFromRuntime(t *testing.T) {if got := tabPolicyDefaultsFromRuntime(&RuntimeConfig{- TabLifecyclePolicy: "close_idle",+ TabLifecyclePolicy: "keep",TabCloseDelay: 5 * time.Minute,}); got != nil {- t.Fatalf("default close_idle/5m policy should not be emitted; got %#v", got)+ t.Fatalf("default keep policy should not be emitted; got %#v", got)}got := tabPolicyDefaultsFromRuntime(&RuntimeConfig{- TabLifecyclePolicy: "keep",+ TabLifecyclePolicy: "close_idle",TabCloseDelay: 5 * time.Minute,})- if got == nil || got.Lifecycle != "keep" || got.CloseDelaySec != nil {- t.Fatalf("keep policy = %#v, want lifecycle=keep without delay", got)+ if got == nil || got.Lifecycle != "close_idle" || got.CloseDelaySec != nil {+ t.Fatalf("close_idle implicit-delay policy = %#v, want lifecycle=close_idle without delay", got)}got = tabPolicyDefaultsFromRuntime(&RuntimeConfig{@@ -256,6 +260,12 @@ func TestDefaultFileConfigJSON(t *testing.T) {t.Fatalf("failed to unmarshal DefaultFileConfig output: %v", err)}+ if !strings.HasPrefix(string(data), "{\n \"$schema\": ") {+ t.Fatalf("DefaultFileConfig JSON should start with $schema, got:\n%s", data)+ }+ if parsed.Schema != ConfigSchemaURL {+ t.Errorf("round-trip Schema = %q, want %q", parsed.Schema, ConfigSchemaURL)+ }if parsed.Server.Port != "9867" {t.Errorf("round-trip Server.Port = %v, want 9867", parsed.Server.Port)}diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 6cd85e81..d6f21caa 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -60,7 +60,7 @@ func Load() *RuntimeConfig {Humanize: false,StealthLevel: "light",TabEvictionPolicy: "close_lru",- TabLifecyclePolicy: "close_idle",+ TabLifecyclePolicy: "keep",TabCloseDelay: 5 * time.Minute,TabRestore: false,diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.goindex 83ebc410..ad065392 100644--- a/internal/config/config_load_test.go+++ b/internal/config/config_load_test.go@@ -788,8 +788,8 @@ func TestLoadConfig_TabLifecycleDefaults(t *testing.T) {defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()cfg := Load()- if cfg.TabLifecyclePolicy != "close_idle" {- t.Errorf("default TabLifecyclePolicy = %q, want close_idle", cfg.TabLifecyclePolicy)+ if cfg.TabLifecyclePolicy != "keep" {+ t.Errorf("default TabLifecyclePolicy = %q, want keep", cfg.TabLifecyclePolicy)}if cfg.TabCloseDelay != 5*time.Minute {t.Errorf("default TabCloseDelay = %v, want 5m", cfg.TabCloseDelay)@@ -832,9 +832,9 @@ func TestLoadConfig_LegacyTabEvictionPolicyStillHonored(t *testing.T) {if cfg.TabEvictionPolicy != "close_oldest" {t.Errorf("legacy tabEvictionPolicy not honored; got %q", cfg.TabEvictionPolicy)}- // Lifecycle defaults preserved (default is close_idle).- if cfg.TabLifecyclePolicy != "close_idle" {- t.Errorf("legacy-only config should leave lifecycle at default close_idle; got %q", cfg.TabLifecyclePolicy)+ // Lifecycle defaults preserved (default is keep).+ if cfg.TabLifecyclePolicy != "keep" {+ t.Errorf("legacy-only config should leave lifecycle at default keep; got %q", cfg.TabLifecyclePolicy)}}diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex 5d8a6921..164b0e0b 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -63,8 +63,8 @@ type RuntimeConfig struct {Humanize bool // when true, mouse moves and clicks use a humanized bezier path with per-step jitter and pre-press delays; default false (raw, fast input)StealthLevel stringTabEvictionPolicy string // "close_lru" (default), "reject", "close_oldest" — fires on MaxTabs pressure- TabLifecyclePolicy string // "close_idle" (default), "keep" — fires on idle after read/action- TabCloseDelay time.Duration // applies when TabLifecyclePolicy == "close_idle" (default 5m)+ TabLifecyclePolicy string // "keep" (default), "close_idle" — fires on idle after read/action+ TabCloseDelay time.Duration // applies when TabLifecyclePolicy == "close_idle" (default 5m when enabled)TabRestore bool // restore previously open tabs from sessions.json on startup (default false)// Timeout settings@@ -227,6 +227,7 @@ type ActivityEventsConfig struct {// FileConfig is the persistent configuration written to disk.type FileConfig struct {+ Schema string `json:"$schema,omitempty"`ConfigVersion string `json:"configVersion,omitempty"`Server ServerConfig `json:"server,omitempty"`Browser BrowserConfig `json:"browser,omitempty"`@@ -304,7 +305,7 @@ type InstanceDefaultsConfig struct {type TabPolicyDefaults struct {Eviction string `json:"eviction,omitempty"` // "close_lru" | "reject" | "close_oldest"Lifecycle string `json:"lifecycle,omitempty"` // "keep" | "close_idle"- CloseDelaySec *int `json:"closeDelaySec,omitempty"` // applies to close_idle; default 300+ CloseDelaySec *int `json:"closeDelaySec,omitempty"` // applies to close_idle; default 300 when enabledRestore *bool `json:"restore,omitempty"` // restore tabs from sessions.json on startup; default false}diff --git a/internal/config/workflow/mutate_test.go b/internal/config/workflow/mutate_test.gonew file mode 100644index 00000000..8a49f5b8--- /dev/null+++ b/internal/config/workflow/mutate_test.go@@ -0,0 +1,31 @@+package workflow++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func TestInitDefaultConfigIncludesSchema(t *testing.T) {+ configPath := filepath.Join(t.TempDir(), "pinchtab", "config.json")++ if err := InitDefaultConfig(configPath); err != nil {+ t.Fatalf("InitDefaultConfig() error = %v", err)+ }++ data, err := os.ReadFile(configPath)+ if err != nil {+ t.Fatalf("ReadFile() error = %v", err)+ }++ var raw map[string]any+ if err := json.Unmarshal(data, &raw); err != nil {+ t.Fatalf("config JSON is invalid: %v", err)+ }+ if raw["$schema"] != config.ConfigSchemaURL {+ t.Fatalf("$schema = %q, want %q", raw["$schema"], config.ConfigSchemaURL)+ }+}diff --git a/schema/config.json b/schema/config.jsonnew file mode 100644index 00000000..a31b4876--- /dev/null+++ b/schema/config.json@@ -0,0 +1,895 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "https://raw.githubusercontent.com/pinchtab/pinchtab/v0.8.0/schema/config.json",+ "title": "PinchTab configuration",+ "description": "Configuration file for PinchTab. The CLI's Go validation remains authoritative for cross-field checks.",+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "$schema": {+ "type": "string",+ "format": "uri",+ "default": "https://raw.githubusercontent.com/pinchtab/pinchtab/v0.8.0/schema/config.json",+ "description": "JSON Schema URL for IDE validation."+ },+ "configVersion": {+ "type": "string",+ "default": "0.8.0",+ "description": "PinchTab config compatibility version."+ },+ "server": {+ "$ref": "#/definitions/server"+ },+ "browser": {+ "$ref": "#/definitions/browser"+ },+ "instanceDefaults": {+ "$ref": "#/definitions/instanceDefaults"+ },+ "security": {+ "$ref": "#/definitions/security"+ },+ "profiles": {+ "$ref": "#/definitions/profiles"+ },+ "multiInstance": {+ "$ref": "#/definitions/multiInstance"+ },+ "timeouts": {+ "$ref": "#/definitions/timeouts"+ },+ "scheduler": {+ "$ref": "#/definitions/scheduler"+ },+ "observability": {+ "$ref": "#/definitions/observability"+ },+ "sessions": {+ "$ref": "#/definitions/sessions"+ },+ "autoSolver": {+ "$ref": "#/definitions/autoSolver"+ }+ },+ "definitions": {+ "nullableBoolean": {+ "type": [+ "boolean",+ "null"+ ]+ },+ "nullableInteger": {+ "type": [+ "integer",+ "null"+ ]+ },+ "nullableString": {+ "type": [+ "string",+ "null"+ ]+ },+ "stringArray": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "default": []+ },+ "domainPattern": {+ "type": "string",+ "pattern": "^(?!file://)(?!.*\\s).+$",+ "description": "Hostname or domain pattern. Values must not be empty, contain whitespace, or start with file://."+ },+ "domainPatternArray": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/domainPattern"+ },+ "default": []+ },+ "cidrOrIPArray": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1,+ "description": "IP address or CIDR block."+ },+ "default": []+ },+ "portString": {+ "type": "string",+ "pattern": "^(?:[1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"+ },+ "nullablePort": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": 1,+ "maximum": 65535+ },+ {+ "type": "null"+ }+ ]+ },+ "positiveNullableInteger": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": 1+ },+ {+ "type": "null"+ }+ ]+ },+ "nonNegativeNullableInteger": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": 0+ },+ {+ "type": "null"+ }+ ]+ },+ "server": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "port": {+ "$ref": "#/definitions/portString",+ "default": "9867"+ },+ "bind": {+ "type": "string",+ "default": "127.0.0.1"+ },+ "token": {+ "type": "string",+ "description": "API token. Keep this value secret."+ },+ "stateDir": {+ "type": "string"+ },+ "engine": {+ "type": "string",+ "enum": [+ "",+ "chrome",+ "lite",+ "auto"+ ],+ "default": "chrome"+ },+ "networkBufferSize": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": 1,+ "maximum": 10000+ },+ {+ "type": "null"+ }+ ]+ },+ "trustProxyHeaders": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "cookieSecure": {+ "$ref": "#/definitions/nullableBoolean"+ }+ }+ },+ "browser": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "version": {+ "type": "string",+ "default": "144.0.7559.133"+ },+ "binary": {+ "type": "string"+ },+ "remoteDebuggingPort": {+ "$ref": "#/definitions/nullablePort"+ },+ "extraFlags": {+ "type": "string"+ },+ "extensionPaths": {+ "$ref": "#/definitions/stringArray"+ }+ }+ },+ "instanceDefaults": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "mode": {+ "type": "string",+ "enum": [+ "",+ "headless",+ "headed"+ ],+ "default": "headless"+ },+ "noRestore": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "timezone": {+ "type": "string"+ },+ "blockImages": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "blockMedia": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "blockAds": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "maxTabs": {+ "$ref": "#/definitions/positiveNullableInteger",+ "default": 20+ },+ "maxParallelTabs": {+ "$ref": "#/definitions/nonNegativeNullableInteger",+ "default": 0+ },+ "userAgent": {+ "type": "string"+ },+ "noAnimations": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "humanize": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "stealthLevel": {+ "type": "string",+ "enum": [+ "",+ "light",+ "medium",+ "full"+ ],+ "default": "light"+ },+ "tabEvictionPolicy": {+ "type": "string",+ "enum": [+ "",+ "reject",+ "close_oldest",+ "close_lru"+ ],+ "default": "close_lru",+ "description": "Deprecated. Prefer instanceDefaults.tabPolicy.eviction."+ },+ "tabPolicy": {+ "anyOf": [+ {+ "$ref": "#/definitions/tabPolicy"+ },+ {+ "type": "null"+ }+ ]+ },+ "dialogAutoAccept": {+ "$ref": "#/definitions/nullableBoolean"+ }+ }+ },+ "tabPolicy": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "eviction": {+ "type": "string",+ "enum": [+ "",+ "reject",+ "close_oldest",+ "close_lru"+ ]+ },+ "lifecycle": {+ "type": "string",+ "enum": [+ "",+ "keep",+ "close_idle"+ ]+ },+ "closeDelaySec": {+ "$ref": "#/definitions/nonNegativeNullableInteger"+ },+ "restore": {+ "$ref": "#/definitions/nullableBoolean"+ }+ }+ },+ "profiles": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "baseDir": {+ "type": "string"+ },+ "defaultProfile": {+ "type": "string",+ "default": "default"+ }+ }+ },+ "security": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "allowEvaluate": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "allowMacro": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "allowScreencast": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "allowDownload": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "allowedDomains": {+ "$ref": "#/definitions/domainPatternArray"+ },+ "downloadAllowedDomains": {+ "$ref": "#/definitions/domainPatternArray"+ },+ "downloadMaxBytes": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": 1,+ "maximum": 104857600+ },+ {+ "type": "null"+ }+ ],+ "default": 20971520+ },+ "allowUpload": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "allowClipboard": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "allowStateExport": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "stateEncryptionKey": {+ "$ref": "#/definitions/nullableString"+ },+ "enableActionGuards": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "uploadMaxRequestBytes": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": 1,+ "maximum": 104857600+ },+ {+ "type": "null"+ }+ ],+ "default": 10485760+ },+ "uploadMaxFiles": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": 1,+ "maximum": 32+ },+ {+ "type": "null"+ }+ ],+ "default": 8+ },+ "uploadMaxFileBytes": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": 1,+ "maximum": 26214400+ },+ {+ "type": "null"+ }+ ],+ "default": 5242880+ },+ "uploadMaxTotalBytes": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": 1,+ "maximum": 104857600+ },+ {+ "type": "null"+ }+ ],+ "default": 10485760+ },+ "maxRedirects": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": -1+ },+ {+ "type": "null"+ }+ ],+ "default": -1+ },+ "trustedProxyCIDRs": {+ "$ref": "#/definitions/cidrOrIPArray"+ },+ "trustedResolveCIDRs": {+ "$ref": "#/definitions/cidrOrIPArray"+ },+ "attach": {+ "$ref": "#/definitions/attach"+ },+ "idpi": {+ "$ref": "#/definitions/idpi"+ }+ }+ },+ "attach": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "enabled": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "allowHosts": {+ "$ref": "#/definitions/stringArray"+ },+ "allowSchemes": {+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "ws",+ "wss",+ "http",+ "https"+ ]+ },+ "default": [+ "ws",+ "wss"+ ]+ }+ }+ },+ "idpi": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "enabled": {+ "type": "boolean",+ "default": true+ },+ "strictMode": {+ "type": "boolean",+ "default": true+ },+ "scanContent": {+ "type": "boolean",+ "default": true+ },+ "wrapContent": {+ "type": "boolean",+ "default": true+ },+ "customPatterns": {+ "$ref": "#/definitions/stringArray"+ },+ "scanTimeoutSec": {+ "type": "integer",+ "minimum": 0,+ "default": 5+ },+ "shieldThreshold": {+ "type": "integer",+ "minimum": 0,+ "maximum": 100,+ "default": 0+ }+ }+ },+ "multiInstance": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "strategy": {+ "type": "string",+ "enum": [+ "",+ "simple",+ "explicit",+ "simple-autorestart",+ "always-on",+ "no-instance"+ ],+ "default": "always-on"+ },+ "allocationPolicy": {+ "type": "string",+ "enum": [+ "",+ "fcfs",+ "round_robin",+ "random"+ ],+ "default": "fcfs"+ },+ "instancePortStart": {+ "$ref": "#/definitions/nullablePort",+ "default": 9868+ },+ "instancePortEnd": {+ "$ref": "#/definitions/nullablePort",+ "default": 9968+ },+ "restart": {+ "$ref": "#/definitions/restart"+ }+ }+ },+ "restart": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "maxRestarts": {+ "anyOf": [+ {+ "type": "integer",+ "minimum": -1+ },+ {+ "type": "null"+ }+ ],+ "default": 20+ },+ "initBackoffSec": {+ "$ref": "#/definitions/positiveNullableInteger",+ "default": 2+ },+ "maxBackoffSec": {+ "$ref": "#/definitions/positiveNullableInteger",+ "default": 60+ },+ "stableAfterSec": {+ "$ref": "#/definitions/positiveNullableInteger",+ "default": 300+ }+ }+ },+ "timeouts": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "actionSec": {+ "type": "integer",+ "minimum": 0,+ "default": 30+ },+ "navigateSec": {+ "type": "integer",+ "minimum": 0,+ "default": 60+ },+ "shutdownSec": {+ "type": "integer",+ "minimum": 0,+ "default": 10+ },+ "waitNavMs": {+ "type": "integer",+ "minimum": 0,+ "default": 1000+ }+ }+ },+ "scheduler": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "enabled": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "strategy": {+ "type": "string"+ },+ "maxQueueSize": {+ "$ref": "#/definitions/nonNegativeNullableInteger"+ },+ "maxPerAgent": {+ "$ref": "#/definitions/nonNegativeNullableInteger"+ },+ "maxInflight": {+ "$ref": "#/definitions/nonNegativeNullableInteger"+ },+ "maxPerAgentInflight": {+ "$ref": "#/definitions/nonNegativeNullableInteger"+ },+ "resultTTLSec": {+ "$ref": "#/definitions/nonNegativeNullableInteger"+ },+ "workerCount": {+ "$ref": "#/definitions/nonNegativeNullableInteger"+ }+ }+ },+ "observability": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "activity": {+ "$ref": "#/definitions/activity"+ }+ }+ },+ "activity": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "enabled": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "sessionIdleSec": {+ "$ref": "#/definitions/nonNegativeNullableInteger",+ "default": 1800+ },+ "retentionDays": {+ "$ref": "#/definitions/positiveNullableInteger",+ "default": 30+ },+ "stateDir": {+ "type": "string"+ },+ "events": {+ "$ref": "#/definitions/activityEvents"+ }+ }+ },+ "activityEvents": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "dashboard": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "server": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "bridge": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "orchestrator": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "scheduler": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "mcp": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "other": {+ "$ref": "#/definitions/nullableBoolean"+ }+ }+ },+ "sessions": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "dashboard": {+ "$ref": "#/definitions/dashboardSession"+ },+ "agent": {+ "$ref": "#/definitions/agentSession"+ }+ }+ },+ "dashboardSession": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "persist": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "idleTimeoutSec": {+ "$ref": "#/definitions/positiveNullableInteger",+ "default": 604800+ },+ "maxLifetimeSec": {+ "$ref": "#/definitions/positiveNullableInteger",+ "default": 604800+ },+ "elevationWindowSec": {+ "$ref": "#/definitions/positiveNullableInteger",+ "default": 900+ },+ "persistElevationAcrossRestart": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "requireElevation": {+ "$ref": "#/definitions/nullableBoolean"+ }+ }+ },+ "agentSession": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "enabled": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "mode": {+ "type": "string"+ },+ "idleTimeoutSec": {+ "$ref": "#/definitions/positiveNullableInteger"+ },+ "maxLifetimeSec": {+ "$ref": "#/definitions/positiveNullableInteger"+ }+ }+ },+ "autoSolver": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "enabled": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "autoTrigger": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "triggerOnNavigate": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "triggerOnAction": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "maxAttempts": {+ "$ref": "#/definitions/positiveNullableInteger",+ "default": 8+ },+ "solverTimeoutSec": {+ "$ref": "#/definitions/positiveNullableInteger",+ "default": 30+ },+ "retryBaseDelayMs": {+ "$ref": "#/definitions/nonNegativeNullableInteger",+ "default": 500+ },+ "retryMaxDelayMs": {+ "$ref": "#/definitions/nonNegativeNullableInteger",+ "default": 10000+ },+ "solvers": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1+ },+ "default": [+ "cloudflare",+ "semantic",+ "capsolver",+ "twocaptcha"+ ]+ },+ "llmProvider": {+ "type": "string"+ },+ "llmFallback": {+ "$ref": "#/definitions/nullableBoolean"+ },+ "external": {+ "$ref": "#/definitions/autoSolverExternal"+ },+ "credentials": {+ "$ref": "#/definitions/autoSolverCredentials"+ }+ }+ },+ "autoSolverExternal": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "capsolverKey": {+ "type": "string"+ },+ "twoCaptchaKey": {+ "type": "string"+ }+ }+ },+ "autoSolverCredentials": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "login": {+ "$ref": "#/definitions/autoSolverLogin"+ },+ "signup": {+ "$ref": "#/definitions/autoSolverSignup"+ },+ "form": {+ "$ref": "#/definitions/autoSolverForm"+ }+ }+ },+ "autoSolverLogin": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "user": {+ "type": "string"+ },+ "password": {+ "type": "string"+ }+ }+ },+ "autoSolverSignup": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "name": {+ "type": "string"+ },+ "email": {+ "type": "string"+ },+ "password": {+ "type": "string"+ }+ }+ },+ "autoSolverForm": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "field1": {+ "type": "string"+ },+ "field2": {+ "type": "string"+ },+ "email": {+ "type": "string"+ }+ }+ }+ }+}diff --git a/schema/schema.go b/schema/schema.gonew file mode 100644index 00000000..cb5c39ae--- /dev/null+++ b/schema/schema.go@@ -0,0 +1,8 @@+package schema++import _ "embed"++// ConfigJSON is the PinchTab config JSON Schema bundled with this build.+//+//go:embed config.json+var ConfigJSON []bytediff --git a/schema/schema_test.go b/schema/schema_test.gonew file mode 100644index 00000000..6c8894ce--- /dev/null+++ b/schema/schema_test.go@@ -0,0 +1,34 @@+package schema++import (+ "encoding/json"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func TestConfigSchemaMetadata(t *testing.T) {+ var raw map[string]any+ if err := json.Unmarshal(ConfigJSON, &raw); err != nil {+ t.Fatalf("ConfigJSON is not valid JSON: %v", err)+ }++ if raw["$schema"] != "http://json-schema.org/draft-07/schema#" {+ t.Fatalf("schema dialect = %q, want draft-07", raw["$schema"])+ }+ if raw["$id"] != config.ConfigSchemaURL {+ t.Fatalf("schema $id = %q, want %q", raw["$id"], config.ConfigSchemaURL)+ }++ properties, ok := raw["properties"].(map[string]any)+ if !ok {+ t.Fatal("schema properties missing or malformed")+ }+ schemaProp, ok := properties["$schema"].(map[string]any)+ if !ok {+ t.Fatal("schema does not describe config $schema property")+ }+ if schemaProp["default"] != config.ConfigSchemaURL {+ t.Fatalf("config $schema default = %q, want %q", schemaProp["default"], config.ConfigSchemaURL)+ }+}diff --git a/skills/pinchtab/SKILL.md b/skills/pinchtab/SKILL.mdindex 642d5f05..808f7bb0 100644--- a/skills/pinchtab/SKILL.md+++ b/skills/pinchtab/SKILL.md@@ -27,8 +27,8 @@ CLI-first browser skill. Use `pinchtab` commands.## Core Workflow-1. Ensure the right server/profile/instance is active.-2. Navigate: `pinchtab nav <url> --snap` — returns tab ID + interactive snapshot in one call.+1. Ensure the right profile/instance is selected when needed.+2. Navigate: `pinchtab nav <url> --snap` — auto-starts the local server if needed, then returns tab ID + interactive snapshot in one call.3. Interact: `pinchtab click <ref> --snap-diff` — returns OK + only changed elements (most token-efficient).4. For read-only observation: `pinchtab text` when you won't act on refs.@@ -46,10 +46,11 @@ e12:textbox val="updated" [~]Fallback observation (when `--snap` wasn't used):- `pinchtab snap` — interactive elements + headings in compact format (default).+- `pinchtab snap [selector]` — scope the current-tab snapshot to one element.- `pinchtab snap --full` — all nodes as JSON (for debugging).- `pinchtab text` — content only (use when snap is missing prose you need).-Rules: never act on stale refs; screenshots only for visual/debug; choose the instance/profile up front for parallel or multi-site work.+Rules: only `nav <url>` auto-starts the local server; `snap`, `text`, `html`, `find`, and action commands operate on an already-running server/current tab. Never act on stale refs; screenshots only for visual/debug; choose the instance/profile up front for parallel or multi-site work.## Selectors@@ -88,20 +89,21 @@ pinchtab --server http://localhost:9868 snap -i -c # target a specific instance### Navigation and tabs```bash-pinchtab nav <url> # flags: --snap, --new-tab, --tab <id>, --block-images, --block-ads, --print-tab-id+pinchtab nav <url> # auto-starts local server; flags: --snap, --new-tab, --tab <id>, --block-images, --block-ads, --print-tab-idpinchtab back | forward | reload # all support --snap, --snap-diff, --textpinchtab tab # list tabspinchtab tab <tab-id> # focus tab-pinchtab tab new <url> | tab close <tab-id>+pinchtab nav <url> --new-tab # force another tab+pinchtab tab close <tab-id>pinchtab instance navigate <instance-id> <url>```-Tab state is automatic: `nav` persists the tab ID to a state file, and subsequent commands read it. No need for `export PINCHTAB_TAB=...` boilerplate. Just run `pinchtab nav URL` then `pinchtab snap -i -c` — the tab is remembered. For explicit control: `--tab <id>` flag or `PINCHTAB_TAB` env var override the state file.+Tab state is automatic: `nav` persists the tab ID to a state file, and subsequent commands read it. Just run `pinchtab nav URL` then `pinchtab snap -i -c` — the tab is remembered. For explicit control, use `--tab <id>`.### Observation```bash-pinchtab snap # default: compact + interactive; flags: --full (JSON), -d (diff), --selector <css>, --max-tokens <n>+pinchtab snap [selector] # default: compact + interactive; flags: --full (JSON), -d (diff), --selector <css>, --max-tokens <n>pinchtab text # Readability-filtered page textpinchtab text --full # raw document.body.innerText (alias: --raw)pinchtab text <selector> # ref / -s CSS / xpath:... — text from one elementdiff --git a/skills/pinchtab/references/agent-optimization.md b/skills/pinchtab/references/agent-optimization.mdindex 429f80e3..9c6fdce1 100644--- a/skills/pinchtab/references/agent-optimization.md+++ b/skills/pinchtab/references/agent-optimization.md@@ -14,7 +14,7 @@ Need to check page state?├─ Need to find interactive elements? → snap -i -c (cheapest)├─ Need to read text/data only? → pinchtab text (no tree overhead)├─ Need to find a specific element? → pinchtab find "<text>"-├─ Need full page structure? → snap -c (compact tree)+├─ Need full page structure? → snap --full├─ Need to debug visually? → screenshot (use sparingly, large output)└─ Need to run a JS check? → eval (precise, zero visual overhead)```@@ -23,11 +23,9 @@ Need to check page state?1. `eval` — single value, no DOM traversal output2. `find` — targeted element list only3. `text` — readable text only-4. `snap -i -c` — interactive elements, compact format-5. `snap -c` — full tree, compact-6. `snap -i` — interactive elements, verbose-7. `snap` — full tree, verbose-8. `screenshot` — image payload, highest token cost+4. `snap` / `snap -i -c` — interactive elements, compact format+5. `snap --full` — full JSON tree+6. `screenshot` — image payload, highest token cost**Rule of thumb:** Reach for `snap -i -c` as your default snapshot. Only escalate to `screenshot` when visual layout matters (CAPTCHA, canvas, complex CSS).@@ -65,27 +63,15 @@ e12:textbox val="updated" [~] # changed----## Lite Engine+## Faster Page Loads-Start PinchTab with `--engine lite` for minimal rendering overhead.+Use `--block-images` on navigation for read-heavy tasks where images are not needed.```bash-pinchtab start --engine lite+pinchtab nav <url> --block-images --snap```-**Lite engine capabilities:**-- Faster page loads (no CSS animations, reduced JS execution)-- Lower memory footprint — useful for multi-tab fleet workflows-- Accessibility tree (`snap`) works fully-- `text`, `find`, `eval` all work as normal--**Lite engine limitations:**-- `screenshot` output may not reflect full visual styling-- Pages that depend on CSS transitions for state changes may behave differently-- Some canvas/WebGL content will not render-- Not suitable for visual regression testing--**Best for:** Form automation, data extraction, API-heavy SPAs, scraping workflows where visual fidelity is not required.+**Best for:** Form automation, data extraction, API-heavy SPAs, and scraping workflows where image content is not required.---@@ -109,7 +95,7 @@ pinchtab find "target text" # avoids eval entirely**Recovery:**1. `pinchtab screenshot` — confirm login page is showing2. Re-authenticate: `pinchtab nav <login-url>`, then fill credentials-3. If using a profile: `pinchtab profile use <name>` may restore the session+3. If using a profile, start or target that profile explicitly: `pinchtab instance start --profile <name>`---@@ -119,7 +105,7 @@ pinchtab find "target text" # avoids eval entirely**Recovery:**```bashpinchtab health # confirm down-pinchtab start # restart+pinchtab server # restart in the foreground, or use `pinchtab nav <url>` to auto-start for a new navigationpinchtab health # confirm up before continuing```@@ -152,7 +138,7 @@ pinchtab snap -i -c # fresh snapshot → new refs-H 'Content-Type: application/json' -d '{"maxAttempts": 3}'```2. If solve returns `solved: false`, try with more attempts or check `challengeType`-3. Slow down: add `pinchtab wait --ms 1500` between interactions+3. Slow down: add `pinchtab wait 1500` between interactions4. Switch to a profile with existing session cookies (CF cookies persist)5. If unsupported CAPTCHA (not Cloudflare): report to user for manual intervention6. Check `GET /solvers` to see which solver types are available@@ -164,13 +150,9 @@ pinchtab snap -i -c # fresh snapshot → new refs**Cause:** Page load exceeded default timeout (usually 30s).**Recovery:**-```bash-pinchtab nav <url> --timeout 90 # extend timeout-```-If the page consistently times out, consider `--block-images` to speed up load:```bash-pinchtab nav <url> --block-images --timeout 60+pinchtab nav <url> --block-images --snap```---@@ -184,4 +166,4 @@ pinchtab nav <url> --block-images --timeout 60- **Scope snapshots.** Use `snap -s <selector>` to target a specific section of the page when you know where the element is.- **Prefer `fill` over `type` for framework forms.** Saves retries caused by React/Vue not detecting raw keystroke events.- **Check health before long workflows.** Run `pinchtab health` at the start of a multi-step task to fail fast if the server is down.-- **Export network traces after sessions.** `pinchtab network-export -o session.har` captures every request. For live capture: `pinchtab network-export --stream -o live.har`.+- **Inspect network activity when needed.** `pinchtab network --limit 20` lists recent requests; use `pinchtab network <requestId> --body` for details.diff --git a/skills/pinchtab/references/api.md b/skills/pinchtab/references/api.mdindex 70daa56b..0e8e5247 100644--- a/skills/pinchtab/references/api.md+++ b/skills/pinchtab/references/api.md@@ -319,7 +319,7 @@ Set `awaitPromise: true` when the expression returns a promise and you want the## Tab management```bash-# CLI: pinchtab tabs / pinchtab tabs new <url> / pinchtab tabs close <id>+# CLI: pinchtab tabs / pinchtab nav <url> --new-tab / pinchtab tabs close <id># List tabscurl /tabsdiff --git a/skills/pinchtab/references/commands.md b/skills/pinchtab/references/commands.mdindex 4d9b5510..8753e9c0 100644--- a/skills/pinchtab/references/commands.md+++ b/skills/pinchtab/references/commands.md@@ -1,4 +1,4 @@-# CLI Commands Reference — Pinchtab 0.8.x+# CLI Commands Reference — PinchTab> **Quick tip:** Use `pinchtab help` or `pinchtab <command> --help` for full flag lists.@@ -25,10 +25,18 @@ pinchtab server -e ./ext # load browser extension> **Note:** Use `--headed` only when you need visual feedback (debugging, watching automation). Headless mode is more resource-efficient.-### `pinchtab stop`-Stop the running server.+### `pinchtab daemon`+Manage the user-level background service.-### `pinchtab status` / `pinchtab health`+```bash+pinchtab daemon+pinchtab daemon install+pinchtab daemon start+pinchtab daemon stop+pinchtab daemon restart+```++### `pinchtab health`Check if the server is running and healthy.---@@ -36,37 +44,35 @@ Check if the server is running and healthy.## Browser Commands### `pinchtab nav <url>`-Navigate the current tab to a URL.+Open a new tab and navigate to a URL by default. This is the browser command that auto-starts the local server when it is not already running.```bashpinchtab nav https://pinchtab.compinchtab nav https://pinchtab.com --new-tabpinchtab nav https://pinchtab.com --snappinchtab nav https://pinchtab.com --block-images-pinchtab nav https://pinchtab.com --timeout 60+pinchtab nav https://pinchtab.com --tab <tabId>```| Flag | Description ||------|-------------|-| `--new-tab` | Open in a new tab instead of current |+| `--new-tab` | Explicitly force a new tab |+| `--tab <id>` | Reuse a specific tab || `--snap` | Navigate and print an interactive compact snapshot || `--block-images` | Block image loading (faster, fewer tokens) |-| `--timeout <s>` | Navigation timeout in seconds |-| `--profile <name>` | Target a named profile |--> ⚠️ **Quirk:** Use `--profile`, not `--profileId`. The long-form flag is required.+| `--block-ads` | Block ads for this navigation |+| `--print-tab-id` | Print only the tab ID |### `pinchtab tab` (not `tabs`)Manage browser tabs.```bash-pinchtab tab list # List all open tabs-pinchtab tab close # Close current tab+pinchtab tab # List all open tabs+pinchtab tab <tabId> # Focus a tab by ID or 1-based index+pinchtab nav <url> --new-tab # Open a new tab and navigate itpinchtab tab close <tabId> # Close specific tab```-> ⚠️ **Quirk:** The command is `tab` (singular), not `tabs`.----## Interaction Commands@@ -150,12 +156,11 @@ pinchtab select e8 "value" --snap-diff # select + return only changed elementGet the accessibility tree of the current page. **Primary tool for understanding page state.**```bash-pinchtab snap # full tree-pinchtab snap -i # interactive elements only (smaller)-pinchtab snap -c # compact format (fewer tokens)-pinchtab snap -i -c # both: cheapest snapshot+pinchtab snap # compact interactive snapshot (default)+pinchtab snap "#main" # scoped positional selector+pinchtab snap -s main # scoped with --selector+pinchtab snap --full # full JSON treepinchtab snap -d # diff: only changes since last snap (prefer --snap-diff on actions)-pinchtab snap -s main # scoped to CSS selectorpinchtab snap --max-tokens 2000 # token budget cap```@@ -177,6 +182,7 @@ Extract readable text from the page.```bashpinchtab textpinchtab text --raw # no formatting cleanup+pinchtab text "#main" # text from one element```### `pinchtab find <query>`@@ -197,31 +203,26 @@ pinchtab eval "document.querySelectorAll('a').length"> Requires `security.allowEvaluate: true` in config. Returns 403 by default.-### `pinchtab network-export`-Export captured network data in standard formats.+### `pinchtab network`+Inspect captured network requests for the current tab.```bash-pinchtab network-export # HAR 1.2 to exports/-pinchtab network-export -o session.har # HAR to specific file-pinchtab network-export --format ndjson -o s.ndjson # NDJSON (one JSON per line)-pinchtab network-export --body # Include response bodies-pinchtab network-export --stream -o live.har # Live capture while browsing+pinchtab network+pinchtab network --limit 20+pinchtab network --filter api+pinchtab network <requestId> --body```-Formats: `har` (Chrome DevTools compatible), `ndjson` (streamable). Sensitive headers redacted by default.----## Fleet / Multi-Profile Commands-### `pinchtab profile list`-List all available profiles.--### `pinchtab profile use <name>`-Switch the active profile.+### `pinchtab profiles`+List available profiles.```bash-pinchtab profile use work+pinchtab profiles+pinchtab instance start --profile work```### `pinchtab instances`@@ -235,5 +236,3 @@ List running PinchTab instances across profiles.|-------|-------|------|| `pinchtab ss` | `pinchtab screenshot` | No `ss` alias || `pinchtab snapshot` | `pinchtab snap` | Use short form |-| `--profileId` | `--profile` | Long-form flag name |-| `pinchtab tabs` | `pinchtab tab` | Singular subcommand |diff --git a/skills/pinchtab/references/env.md b/skills/pinchtab/references/env.mdindex cb3bc7ed..2ad77565 100644--- a/skills/pinchtab/references/env.md+++ b/skills/pinchtab/references/env.md@@ -10,7 +10,6 @@ For agent workflows, most runtime behavior should be configured through `config.|---|---|---|| `PINCHTAB_TOKEN` | Authenticate CLI or MCP requests to a protected server | Sent as `Authorization: Bearer ...` || `PINCHTAB_CONFIG` | Override the config file path | Prefer this over ad hoc env overrides when automating |-| `PINCHTAB_TAB` | Default tab ID for tab-scoped commands (`snap`, `eval`, `click`, `fill`, `drag`, etc.) | Used when `--tab` isn't passed explicitly. Lets agents `export PINCHTAB_TAB=$(pinchtab nav URL)` once and drop `--tab "$TAB"` from every subsequent command. |## Targeting remote servers@@ -34,16 +33,9 @@ For most agent tasks, the only variable you need is:PINCHTAB_TOKEN=...```-For multi-step flows on a specific tab, also set `PINCHTAB_TAB` once after-navigating so you don't have to thread `--tab` through every command:--```bash-export PINCHTAB_TOKEN=...-export PINCHTAB_TAB=$(pinchtab nav http://example.com) # pipe → tabId only-pinchtab snap -i -c # auto-targets $PINCHTAB_TAB-pinchtab eval --await-promise "window.fetchPayload()"-pinchtab click "#submit"-```+For multi-step flows on the same tab, run `pinchtab nav URL` once and then use+unscoped commands. PinchTab remembers the current tab in its state file. Use+`--tab <id>` only when you need to target a specific tab explicitly.Or use agent sessions for per-agent identity and revocability:diff --git a/skills/pinchtab/references/mcp.md b/skills/pinchtab/references/mcp.mdindex 5f64f258..7200a363 100644--- a/skills/pinchtab/references/mcp.md+++ b/skills/pinchtab/references/mcp.md@@ -35,7 +35,7 @@ For Claude Desktop (`~/Library/Application Support/Claude/claude_desktop_config.}```-PinchTab must be running (`pinchtab start`) before the MCP server can proxy requests. The MCP server communicates with the PinchTab HTTP API at `localhost:9867` by default.+`pinchtab mcp` auto-starts the local PinchTab server if needed, then proxies requests to the HTTP API at `localhost:9867` by default.> [!CAUTION]> Widening MCP browsing beyond local or explicitly trusted domains is a security-reducing choice. If IDPI allowlists or strict protections are relaxed, `pinchtab_snapshot` and `pinchtab_get_text` may surface hostile instructions from untrusted pages.@@ -131,11 +131,11 @@ The MCP surface is intentionally scoped to browser automation. The following are| Capability | Status | Alternative ||------------|--------|-------------|-| Create/edit/delete profiles | ❌ Not available | Use `pinchtab profile` CLI or HTTP API |-| Configure the scheduler | ❌ Not available | Use `pinchtab schedule` CLI |+| Create/edit/delete profiles | ❌ Not available | Use `pinchtab profiles`, `pinchtab instance start --profile <name>`, or the HTTP API |+| Configure the scheduler | ❌ Not available | Use the HTTP API/configuration surface || Solve challenges (Cloudflare, etc.) | ❌ Not available | Use `POST /solve` HTTP API || Modify stealth / fingerprint settings | ❌ Not available | Edit config file directly |-| Start or stop the PinchTab server | ❌ Not available | Use `pinchtab start` / `pinchtab stop` CLI |+| Start or stop the PinchTab server | ❌ Not available | Use `pinchtab server` or `pinchtab daemon` CLI || Manage fleet instances | ❌ Not available | Use `pinchtab instances` CLI || Read/write PinchTab config | ❌ Not available | Edit `~/.pinchtab/config.json` directly |@@ -166,7 +166,7 @@ MCP tools surface errors as tool errors (not protocol-level errors). Common case| Error | Cause | Fix ||-------|-------|-----|-| Connection refused | PinchTab not running | `pinchtab start` |+| Connection refused | PinchTab not running | Run `pinchtab mcp` locally, or start with `pinchtab server` / `pinchtab daemon start` || `ref not found` | Stale element ref | Re-run `pinchtab_snapshot` || `evaluate not allowed` (403) | `security.allowEvaluate` is false | Enable in config or use `find`/`snap` instead || `invalid URL` | Missing `http://` or `https://` | Include full scheme in URL |diff --git a/tests/e2e/scenarios/api/tabs-autoclose-smoke.sh b/tests/e2e/scenarios/api/tabs-autoclose-smoke.shindex 2dbbb7f5..71be9318 100755--- a/tests/e2e/scenarios/api/tabs-autoclose-smoke.sh+++ b/tests/e2e/scenarios/api/tabs-autoclose-smoke.sh@@ -2,8 +2,8 @@# tabs-autoclose-smoke.sh — verifies the auto-close-after-use lifecycle policy.## Requires the server to be started with tests/e2e/config/pinchtab-autoclose.json-# (lifecycle=close_idle, closeDelaySec=1). The default e2e config uses the-# production 5-minute auto-close delay, which is too slow for these assertions.+# (lifecycle=close_idle, closeDelaySec=1). The default e2e config keeps tabs+# open, so this scenario uses an explicit auto-close server.## Behaviour under test:# 1. /text on a tab arms an auto-close timer; the tab disappears after the delay.diff --git a/tests/e2e/scenarios/cli/stealth-basic.sh b/tests/e2e/scenarios/cli/stealth-basic.shindex 4d605da3..e89749a3 100644--- a/tests/e2e/scenarios/cli/stealth-basic.sh+++ b/tests/e2e/scenarios/cli/stealth-basic.sh@@ -60,10 +60,10 @@ assert_output_contains "true" "user agent version remains coherent"end_test# ─────────────────────────────────────────────────────────────────────────────-start_test "stealth-cli: created tab keeps stealth capability contract"+start_test "stealth-cli: new navigation keeps stealth capability contract"-pt_ok tab new --json-assert_output_json "tab new returns JSON"+pt_ok nav "${FIXTURES_URL}/bot-detect.html" --new-tab --json+assert_output_json "nav --new-tab returns JSON"TAB_ID=$(echo "$PT_OUT" | jq -r '.tabId // empty')if [ -n "$TAB_ID" ]; thendiff --git a/tests/e2e/scenarios/cli/system-basic.sh b/tests/e2e/scenarios/cli/system-basic.shindex b54ceb03..21cb702f 100644--- a/tests/e2e/scenarios/cli/system-basic.sh+++ b/tests/e2e/scenarios/cli/system-basic.sh@@ -95,6 +95,23 @@ assert_output_contains "$EXPECTED_PATH" "path matches expected"config_cleanupend_test+start_test "config schema prints bundled schema"++pt_ok config schema+SCHEMA_URL=$(echo "$PT_OUT" | tr -d '[:space:]')+if [[ "$SCHEMA_URL" =~ ^https://raw\.githubusercontent\.com/pinchtab/pinchtab/v[0-9]+\.[0-9]+\.[0-9]+/schema/config\.json$ ]]; then+ pass_assert "prints versioned GitHub schema URL"+else+ fail_assert "prints versioned GitHub schema URL (got $SCHEMA_URL)"+fi++pt_ok config schema --print+assert_output_json "schema output is valid JSON"+assert_json_field '."$id"' "$SCHEMA_URL" 'schema $id matches URL'+assert_json_field '."$schema"' "http://json-schema.org/draft-07/schema#" 'schema $schema is draft-07'++end_test+start_test "config set updates a value"config_setupdiff --git a/tests/e2e/scenarios/cli/tabs-basic.sh b/tests/e2e/scenarios/cli/tabs-basic.shindex 23eab39d..5053a681 100644--- a/tests/e2e/scenarios/cli/tabs-basic.sh+++ b/tests/e2e/scenarios/cli/tabs-basic.sh@@ -29,20 +29,80 @@ assert_output_not_contains "$TAB_ID" "tab was closed"end_test# ─────────────────────────────────────────────────────────────────-start_test "pinchtab tab new <url>"+start_test "pinchtab nav --new-tab <url>"-pt_ok tab new "${FIXTURES_URL}/buttons.html" --json+pt_ok nav "${FIXTURES_URL}/index.html" --new-tab+BASE_TAB_ID=$(echo "$PT_OUT" | tr -d '[:space:]')++pt_ok nav "${FIXTURES_URL}/buttons.html" --new-tab --jsonassert_output_jsonassert_output_contains "tabId" "returns new tab ID"-NEW_TAB_ID=$(echo "$PT_OUT" | jq -r '.tabId')+if [ "$NEW_TAB_ID" != "$BASE_TAB_ID" ]; then+ echo -e " ${GREEN}✓${NC} --new-tab returned a different tab"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} --new-tab reused ${BASE_TAB_ID}"+ ((ASSERTIONS_FAILED++)) || true+fi+pt_ok tabassert_output_contains "$NEW_TAB_ID" "new tab appears in list"if [ -n "$NEW_TAB_ID" ] && [ "$NEW_TAB_ID" != "null" ]; thenpt tabs close "$NEW_TAB_ID" > /dev/null 2>&1 || truefi+if [ -n "$BASE_TAB_ID" ] && [ "$BASE_TAB_ID" != "null" ]; then+ pt tabs close "$BASE_TAB_ID" > /dev/null 2>&1 || true+fi++end_test++# ─────────────────────────────────────────────────────────────────+start_test "pinchtab nav reuses current tracked tab"++pt_ok nav "${FIXTURES_URL}/index.html" --new-tab+TRACKED_TAB_ID=$(echo "$PT_OUT" | tr -d '[:space:]')++pt_ok nav "${FIXTURES_URL}/form.html"+REUSED_TAB_ID=$(echo "$PT_OUT" | tr -d '[:space:]')++if [ "$REUSED_TAB_ID" = "$TRACKED_TAB_ID" ]; then+ echo -e " ${GREEN}✓${NC} plain nav reused current tab"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} expected $TRACKED_TAB_ID, got $REUSED_TAB_ID"+ ((ASSERTIONS_FAILED++)) || true+fi++pt_ok url --tab "$TRACKED_TAB_ID"+assert_output_contains "form.html" "tracked tab navigated to second URL"++pt tabs close "$TRACKED_TAB_ID" > /dev/null 2>&1 || true++end_test++# ─────────────────────────────────────────────────────────────────+start_test "pinchtab nav creates after current tab closes"++pt_ok nav "${FIXTURES_URL}/index.html" --new-tab+CLOSED_TAB_ID=$(echo "$PT_OUT" | tr -d '[:space:]')++pt_ok tab close "$CLOSED_TAB_ID"++pt_ok nav "${FIXTURES_URL}/form.html"+NEW_AFTER_CLOSE_ID=$(echo "$PT_OUT" | tr -d '[:space:]')++if [ "$NEW_AFTER_CLOSE_ID" != "$CLOSED_TAB_ID" ]; then+ echo -e " ${GREEN}✓${NC} nav created a fresh tab after close"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} nav reused closed tab ${CLOSED_TAB_ID}"+ ((ASSERTIONS_FAILED++)) || true+fi++pt tabs close "$NEW_AFTER_CLOSE_ID" > /dev/null 2>&1 || trueend_test@@ -58,23 +118,34 @@ end_test# ─────────────────────────────────────────────────────────────────start_test "pinchtab tab <id> (focus by tab ID)"-pt nav "${FIXTURES_URL}/index.html"--# Tab list now outputs terse format: [*]<id>\t<url>\t<title>-pt tab --json-assert_output_json "tab list is valid JSON"-TAB_ID=$(echo "$PT_OUT" | jq -r '.tabs[0].id // empty')--if [ -n "$TAB_ID" ] && [ "$TAB_ID" != "null" ]; then- echo -e " ${BLUE}→ focusing on tab ID: ${TAB_ID:0:12}...${NC}"- pt_ok tab "$TAB_ID"- # Output is now the tab ID- assert_output_contains "$TAB_ID" "output contains focused tab ID"+pt_ok nav "${FIXTURES_URL}/index.html" --new-tab+FOCUS_TAB_ID=$(echo "$PT_OUT" | tr -d '[:space:]')++pt_ok nav "${FIXTURES_URL}/buttons.html" --new-tab+OTHER_TAB_ID=$(echo "$PT_OUT" | tr -d '[:space:]')++if [ -n "$FOCUS_TAB_ID" ] && [ "$FOCUS_TAB_ID" != "null" ]; then+ echo -e " ${BLUE}→ focusing on tab ID: ${FOCUS_TAB_ID:0:12}...${NC}"+ pt_ok tab "$FOCUS_TAB_ID"+ assert_output_contains "$FOCUS_TAB_ID" "output contains focused tab ID"++ pt_ok nav "${FIXTURES_URL}/form.html"+ REUSED_FOCUS_ID=$(echo "$PT_OUT" | tr -d '[:space:]')+ if [ "$REUSED_FOCUS_ID" = "$FOCUS_TAB_ID" ]; then+ echo -e " ${GREEN}✓${NC} nav reused focused tab"+ ((ASSERTIONS_PASSED++)) || true+ else+ echo -e " ${RED}✗${NC} expected focused tab $FOCUS_TAB_ID, got $REUSED_FOCUS_ID"+ ((ASSERTIONS_FAILED++)) || true+ fielseecho -e " ${YELLOW}⚠${NC} could not extract tab ID, skipping"((ASSERTIONS_PASSED++)) || truefi+pt tabs close "$FOCUS_TAB_ID" > /dev/null 2>&1 || true+pt tabs close "$OTHER_TAB_ID" > /dev/null 2>&1 || true+end_test# ─────────────────────────────────────────────────────────────────diff --git a/tests/e2e/scenarios/cli/tabs-extended.sh b/tests/e2e/scenarios/cli/tabs-extended.shindex c053ca61..d0287f02 100644--- a/tests/e2e/scenarios/cli/tabs-extended.sh+++ b/tests/e2e/scenarios/cli/tabs-extended.sh@@ -67,9 +67,9 @@ assert_output_contains "tabs" "response contains tabs field"end_test# ─────────────────────────────────────────────────────────────────-start_test "pinchtab tab new + close roundtrip"+start_test "pinchtab nav --new-tab + close roundtrip"-pt_ok nav "${FIXTURES_URL}/index.html"+pt_ok nav "${FIXTURES_URL}/index.html" --new-tabTAB_ID=$(echo "$PT_OUT" | tr -d '[:space:]')pt_ok tab close "$TAB_ID"diff --git a/tests/e2e/scenarios/plugin/plugin-basic.sh b/tests/e2e/scenarios/plugin/plugin-basic.shindex 8167b044..f9f1e483 100644--- a/tests/e2e/scenarios/plugin/plugin-basic.sh+++ b/tests/e2e/scenarios/plugin/plugin-basic.sh@@ -125,7 +125,7 @@ assert_json_length_gte "$RESULT" '.' 1 "has at least one tab"end_test# ─────────────────────────────────────────────────────────────────-start_test "plugin: tab new"+start_test "plugin: /tab action=new"pt_post /tab -d '{"action":"new"}'assert_ok "new tab"diff --git a/tests/optimization/optimization-loop.md b/tests/optimization/optimization-loop.mdindex 94a069c0..ddd0efd9 100644--- a/tests/optimization/optimization-loop.md+++ b/tests/optimization/optimization-loop.md@@ -105,7 +105,7 @@ Typical examples:- when to use `text` vs `snap -i -c`- when to re-snapshot- how to handle navigation `409`-- how to reuse `PINCHTAB_TAB`+- how to rely on the current-tab state file or use `--tab <id>`### Make a benchmark/task change when:diff --git a/tests/tools/scripts/pt b/tests/tools/scripts/ptindex d7792f6c..67fddd0b 100755--- a/tests/tools/scripts/pt+++ b/tests/tools/scripts/pt@@ -10,7 +10,7 @@## The only abstraction this script provides is the Docker exec boundary:# - container selection via $PINCHTAB_CONTAINER-# - auth + endpoint + tab + session env forwarded into the container+# - auth + endpoint + session env forwarded into the container# - stdin forwarding so pipes, heredocs, and process substitution work# (needed for e.g. uploads, piped eval expressions)#@@ -19,7 +19,6 @@# PINCHTAB_SERVER Pinchtab server URL (default: http://localhost:9867)# PINCHTAB_TOKEN Bearer token (default: benchmark-token;# set to "" for no auth header)-# PINCHTAB_TAB Tab ID to target (default: active tab)# PINCHTAB_SESSION Agent session token (default: unset)## Usage examples:@@ -29,12 +28,6 @@# ./scripts/pt --tab "$TAB" click e5# ./scripts/pt eval 'document.title'#-# NOTE on shell-isolated callers (e.g. agent Bash tool calls where each-# invocation is a fresh shell): `export PINCHTAB_TAB=$(./scripts/pt nav URL-# --print-tab-id)` will NOT carry into the next call. Use `--tab "$TAB_ID"`-# explicitly on every call that must pin to a specific tab, or rely on the-# active-tab default for single-tab workflows.-set -euo pipefailSCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"@@ -72,11 +65,6 @@ args=(docker exec-e "PINCHTAB_SERVER=${PINCHTAB_SERVER}")-# Forward optional env vars only when set, so an empty value in the host doesn't-# clobber a default inside the container.-if [[ -n "${PINCHTAB_TAB:-}" ]]; then- args+=(-e "PINCHTAB_TAB=${PINCHTAB_TAB}")-fiif [[ -n "${PINCHTAB_SESSION:-}" ]]; thenargs+=(-e "PINCHTAB_SESSION=${PINCHTAB_SESSION}")fi