High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
chore: add config schema publishing support and other improvements
Luigi Agosti8456b4062aaf
diff --git a/cmd/pinchtab/cmd_cli_autostart_test.go b/cmd/pinchtab/cmd_cli_autostart_test.goindex 0b4e6b23..0dc645a7 100644--- a/cmd/pinchtab/cmd_cli_autostart_test.go+++ b/cmd/pinchtab/cmd_cli_autostart_test.go@@ -87,6 +87,9 @@ func TestSnapDoesNotAutoStartAndTreatsArgAsSelector(t *testing.T) {if selector != "#main" {t.Fatalf("snapshot selector = %q, want #main", selector)}+ if got, _ := flags.GetString("selector"); got != "" {+ t.Fatalf("snap selector flag = %q, want unchanged empty flag", got)+ }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 5f2dd65a..729c71dd 100644--- a/cmd/pinchtab/cmd_cli_browser_inspect.go+++ b/cmd/pinchtab/cmd_cli_browser_inspect.go@@ -11,13 +11,12 @@ var snapCmd = &cobra.Command{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])- }+ selector := ""+ if len(args) > 0 && stringFlag(cmd, "selector") == "" {+ selector = args[0]}runCLI(func(rt cliRuntime) {- browseractions.Snapshot(rt.client, rt.base, rt.token, cmd)+ browseractions.Snapshot(rt.client, rt.base, rt.token, cmd, selector)})},}diff --git a/cmd/pinchtab/cmd_cli_browser_nav.go b/cmd/pinchtab/cmd_cli_browser_nav.goindex e4be5fc8..71c3f6a4 100644--- a/cmd/pinchtab/cmd_cli_browser_nav.go+++ b/cmd/pinchtab/cmd_cli_browser_nav.go@@ -80,56 +80,73 @@ var tabsCmd = &cobra.Command{},}-var tabCloseCmd = &cobra.Command{- Use: "close <id>",- Short: "Close a tab by ID",- Args: cobra.ExactArgs(1),- 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])- })- },+var closeCmd = newTabCloseCmd()+var tabCloseCmd = newTabCloseCmd()+var handoffCmd = newTabHandoffCmd()+var tabHandoffCmd = newTabHandoffCmd()+var resumeCmd = newTabResumeCmd()+var tabResumeCmd = newTabResumeCmd()+var handoffStatusCmd = newTabHandoffStatusCmd()+var tabHandoffStatusCmd = newTabHandoffStatusCmd()++func newTabCloseCmd() *cobra.Command {+ return &cobra.Command{+ Use: "close <id>",+ Short: "Close a tab by ID",+ Args: cobra.ExactArgs(1),+ 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])+ })+ },+ }}-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 from the state file.",- Args: cobra.MaximumNArgs(1),- Run: func(cmd *cobra.Command, args []string) {- reason, _ := cmd.Flags().GetString("reason")- timeoutMS, _ := cmd.Flags().GetInt("timeout-ms")- tabID := resolveTabArg(args)- runCLI(func(rt cliRuntime) {- browseractions.TabHandoff(rt.client, rt.base, rt.token, tabID, reason, timeoutMS, cmd)- })- },+func newTabHandoffCmd() *cobra.Command {+ return &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 from the state file.",+ Args: cobra.MaximumNArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ reason, _ := cmd.Flags().GetString("reason")+ timeoutMS, _ := cmd.Flags().GetInt("timeout-ms")+ tabID := resolveTabArg(args)+ runCLI(func(rt cliRuntime) {+ browseractions.TabHandoff(rt.client, rt.base, rt.token, tabID, reason, timeoutMS, cmd)+ })+ },+ }}-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 from the state file.",- Args: cobra.MaximumNArgs(1),- Run: func(cmd *cobra.Command, args []string) {- status, _ := cmd.Flags().GetString("status")- tabID := resolveTabArg(args)- runCLI(func(rt cliRuntime) {- browseractions.TabResume(rt.client, rt.base, rt.token, tabID, status, cmd)- })- },+func newTabResumeCmd() *cobra.Command {+ return &cobra.Command{+ Use: "resume [id]",+ Short: "Resume a paused_handoff tab",+ 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")+ tabID := resolveTabArg(args)+ runCLI(func(rt cliRuntime) {+ browseractions.TabResume(rt.client, rt.base, rt.token, tabID, status, cmd)+ })+ },+ }}-var tabHandoffStatusCmd = &cobra.Command{- Use: "handoff-status [id]",- Short: "Show handoff status for a tab",- 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)- runCLI(func(rt cliRuntime) {- browseractions.TabHandoffStatus(rt.client, rt.base, rt.token, tabID, cmd)- })- },+func newTabHandoffStatusCmd() *cobra.Command {+ return &cobra.Command{+ Use: "handoff-status [id]",+ Short: "Show handoff status for a tab",+ 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)+ runCLI(func(rt cliRuntime) {+ browseractions.TabHandoffStatus(rt.client, rt.base, rt.token, tabID, cmd)+ })+ },+ }}diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.goindex 4dd98375..99650466 100644--- a/cmd/pinchtab/cmd_cli_register.go+++ b/cmd/pinchtab/cmd_cli_register.go@@ -61,17 +61,18 @@ func registerBrowserCommands() {cacheCmd,storageCmd,stateCmd,+ closeCmd,tabCloseCmd,+ handoffCmd,tabHandoffCmd,+ resumeCmd,tabResumeCmd,+ handoffStatusCmd,tabHandoffStatusCmd,)- // 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.+ // These commands carry GroupID="browser" (set by setCommandGroup above).+ // Add the same group to tabsCmd so cobra accepts grouped tab subcommands.tabsCmd.AddGroup(&cobra.Group{ID: "browser", Title: "Browser"})tabsCmd.AddCommand(tabCloseCmd, tabHandoffCmd, tabResumeCmd, tabHandoffStatusCmd)clipboardCmd.AddCommand(clipboardReadCmd, clipboardWriteCmd, clipboardCopyCmd, clipboardPasteCmd)@@ -127,9 +128,10 @@ func registerBrowserCommands() {cacheCmd,storageCmd,stateCmd,- tabHandoffCmd,- tabResumeCmd,- tabHandoffStatusCmd,+ closeCmd,+ handoffCmd,+ resumeCmd,+ handoffStatusCmd,)}@@ -318,9 +320,13 @@ func configureBrowserFlags() {evalCmd.Flags().Bool("await-promise", false, "Resolve a returned Promise before responding")navCmd.Flags().Bool("print-tab-id", false, "Print only the tab ID on stdout (also triggered automatically when stdout is a pipe)")- tabHandoffCmd.Flags().String("reason", "", "Reason for human handoff (default: manual_handoff)")- tabHandoffCmd.Flags().Int("timeout-ms", 0, "Optional auto-resume timeout in milliseconds")- tabResumeCmd.Flags().String("status", "", "Optional resume status note (e.g. completed, failed)")+ for _, cmd := range []*cobra.Command{handoffCmd, tabHandoffCmd} {+ cmd.Flags().String("reason", "", "Reason for human handoff (default: manual_handoff)")+ cmd.Flags().Int("timeout-ms", 0, "Optional auto-resume timeout in milliseconds")+ }+ for _, cmd := range []*cobra.Command{resumeCmd, tabResumeCmd} {+ cmd.Flags().String("status", "", "Optional resume status note (e.g. completed, failed)")+ }// Add --json flag to action commands (default is terse output)addJSONFlag(@@ -351,9 +357,13 @@ func configureBrowserFlags() {findCmd,evalCmd,tabsCmd,+ closeCmd,tabCloseCmd,+ handoffCmd,tabHandoffCmd,+ resumeCmd,tabResumeCmd,+ handoffStatusCmd,tabHandoffStatusCmd,healthCmd,cacheClearCmd,diff --git a/cmd/pinchtab/cmd_cli_runtime.go b/cmd/pinchtab/cmd_cli_runtime.goindex 19f25e51..9b52482c 100644--- a/cmd/pinchtab/cmd_cli_runtime.go+++ b/cmd/pinchtab/cmd_cli_runtime.go@@ -23,12 +23,7 @@ func runCLI(fn func(cliRuntime)) {}func runCLIWith(cfg *config.RuntimeConfig, fn func(cliRuntime)) {- rt := cliRuntime{- client: newCLIHTTPClient(resolveCLIAgentID()),- base: resolveCLIBase(cfg),- token: resolveCLIToken(cfg),- }- fn(rt)+ fn(newCLIRuntime(cfg))}func runCLIEnsuringServer(command string, fn func(cliRuntime)) {@@ -36,18 +31,22 @@ func runCLIEnsuringServer(command string, fn func(cliRuntime)) {}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 {+ rt := newCLIRuntime(cfg)+ if err := ensureServerForCLI(cfg, rt.base, rt.token, command); err != nil {fmt.Fprintf(os.Stderr, "pinchtab: %v\n", err)os.Exit(1)}fn(rt)}+func newCLIRuntime(cfg *config.RuntimeConfig) cliRuntime {+ return cliRuntime{+ client: newCLIHTTPClient(resolveCLIAgentID()),+ base: resolveCLIBase(cfg),+ token: resolveCLIToken(cfg),+ }+}+func newCLIHTTPClient(agentID string) *http.Client {baseTransport := http.DefaultTransportreturn &http.Client{@@ -69,9 +68,20 @@ func resolveCLIBase(cfg *config.RuntimeConfig) string {// Default to the main server port so requests go through the// orchestrator. This ensures activity is recorded in the shared// store and visible in the dashboard.+ return resolveDefaultCLIBase(cfg)+}++func resolveDefaultCLIBase(cfg *config.RuntimeConfig) string {return fmt.Sprintf("http://127.0.0.1:%s", cfg.Port)}+func canAutoStartServerForCLI(cfg *config.RuntimeConfig, baseURL string) bool {+ if serverURL != "" || os.Getenv("PINCHTAB_SERVER") != "" {+ return false+ }+ return strings.TrimRight(baseURL, "/") == resolveDefaultCLIBase(cfg)+}+func resolveCLIToken(cfg *config.RuntimeConfig) string {if sessionToken := os.Getenv("PINCHTAB_SESSION"); sessionToken != "" {return sessionTokendiff --git a/cmd/pinchtab/cmd_cli_runtime_test.go b/cmd/pinchtab/cmd_cli_runtime_test.goindex f6a0221c..93ad0dbc 100644--- a/cmd/pinchtab/cmd_cli_runtime_test.go+++ b/cmd/pinchtab/cmd_cli_runtime_test.go@@ -65,6 +65,33 @@ func TestResolveCLIBase(t *testing.T) {}}+func TestCanAutoStartServerForCLIOnlyAllowsDefaultLocalBase(t *testing.T) {+ oldServerURL := serverURL+ defer func() { serverURL = oldServerURL }()++ cfg := &config.RuntimeConfig{Port: "9867"}+ serverURL = ""+ t.Setenv("PINCHTAB_SERVER", "")++ if !canAutoStartServerForCLI(cfg, "http://127.0.0.1:9867") {+ t.Fatal("expected default local base to allow auto-start")+ }+ if canAutoStartServerForCLI(cfg, "http://127.0.0.1:9999") {+ t.Fatal("expected mismatched base to disable auto-start")+ }++ serverURL = "http://127.0.0.1:9999"+ if canAutoStartServerForCLI(cfg, "http://127.0.0.1:9999") {+ t.Fatal("expected explicit --server target to disable auto-start")+ }++ serverURL = ""+ t.Setenv("PINCHTAB_SERVER", "http://127.0.0.1:9999")+ if canAutoStartServerForCLI(cfg, "http://127.0.0.1:9999") {+ t.Fatal("expected PINCHTAB_SERVER target to disable auto-start")+ }+}+func TestResolveCLIAgentID(t *testing.T) {tests := []struct {name stringdiff --git a/cmd/pinchtab/cmd_cli_test.go b/cmd/pinchtab/cmd_cli_test.goindex c28e7872..b98e3ee6 100644--- a/cmd/pinchtab/cmd_cli_test.go+++ b/cmd/pinchtab/cmd_cli_test.go@@ -21,6 +21,18 @@ func findCommand(cmd *cobra.Command, use string) *cobra.Command {return nil}+func findDirectCommand(cmd *cobra.Command, use string) *cobra.Command {+ if cmd == nil {+ return nil+ }+ for _, child := range cmd.Commands() {+ if child.Name() == use || child.Use == use {+ return child+ }+ }+ return nil+}+func TestNormalizeRequiredURL(t *testing.T) {t.Run("normalizes bare hostname", func(t *testing.T) {got := normalizeRequiredURL("pinchtab.com")@@ -67,21 +79,33 @@ func TestDragCommandRegistered(t *testing.T) {}}-func TestTabHandoffCommandsRegistered(t *testing.T) {- for _, name := range []string{"handoff [id]", "resume [id]", "handoff-status [id]"} {- if findCommand(rootCmd, name) == nil {+func TestTabManagementCommandsRegistered(t *testing.T) {+ for _, name := range []string{"close <id>", "handoff [id]", "resume [id]", "handoff-status [id]"} {+ if findDirectCommand(rootCmd, name) == nil {t.Fatalf("expected top-level command %q to be registered", name)}}- tabCmd := findCommand(rootCmd, "tab [id]")+ tabCmd := findDirectCommand(rootCmd, "tab [id]")if tabCmd == nil {t.Fatal("expected tab command to be registered")return}- for _, name := range []string{"handoff [id]", "resume [id]", "handoff-status [id]"} {- if findCommand(tabCmd, name) == nil {+ for _, name := range []string{"close <id>", "handoff [id]", "resume [id]", "handoff-status [id]"} {+ if findDirectCommand(tabCmd, name) == nil {t.Fatalf("expected tab subcommand %q to be registered", name)}}++ rootClose := findDirectCommand(rootCmd, "close <id>")+ tabClose := findDirectCommand(tabCmd, "close <id>")+ if rootClose == tabClose {+ t.Fatal("top-level close and tab close should be separate cobra commands")+ }+ if got := rootClose.CommandPath(); got != "pinchtab close" {+ t.Fatalf("root close path = %q, want pinchtab close", got)+ }+ if got := tabClose.CommandPath(); got != "pinchtab tab close" {+ t.Fatalf("tab close path = %q, want pinchtab tab close", got)+ }}diff --git a/cmd/pinchtab/cmd_config.go b/cmd/pinchtab/cmd_config.goindex c43c8b13..c066bb28 100644--- a/cmd/pinchtab/cmd_config.go+++ b/cmd/pinchtab/cmd_config.go@@ -435,16 +435,19 @@ func handleConfigValidate() {}func handleConfigSchema(printSchema bool) {+ schemaURL := config.CurrentConfigSchemaURL()if printSchema {- if _, err := os.Stdout.Write(configschema.ConfigJSON); err != nil {- fmt.Printf("Error writing schema: %v\n", err)+ schemaJSON, err := configschema.ConfigJSONForURL(schemaURL)+ if err != nil {+ fmt.Printf("Error rendering schema: %v\n", err)os.Exit(1)}- if len(configschema.ConfigJSON) == 0 || configschema.ConfigJSON[len(configschema.ConfigJSON)-1] != '\n' {- fmt.Println()+ if _, err := os.Stdout.Write(schemaJSON); err != nil {+ fmt.Printf("Error writing schema: %v\n", err)+ os.Exit(1)}return}- fmt.Println(config.ConfigSchemaURL)+ fmt.Println(schemaURL)}diff --git a/cmd/pinchtab/cmd_config_test.go b/cmd/pinchtab/cmd_config_test.goindex 3aa057b0..115b5b3d 100644--- a/cmd/pinchtab/cmd_config_test.go+++ b/cmd/pinchtab/cmd_config_test.go@@ -238,8 +238,8 @@ func TestConfigSchemaSubcommandPrintsURL(t *testing.T) {}})- if got := strings.TrimSpace(output); got != config.ConfigSchemaURL {- t.Fatalf("config schema output = %q, want %q", got, config.ConfigSchemaURL)+ if got := strings.TrimSpace(output); got != config.CurrentConfigSchemaURL() {+ t.Fatalf("config schema output = %q, want %q", got, config.CurrentConfigSchemaURL())}}@@ -261,8 +261,8 @@ func TestConfigSchemaSubcommandPrintsBundledSchema(t *testing.T) {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)+ if raw["$id"] != config.CurrentConfigSchemaURL() {+ t.Fatalf("schema $id = %q, want %q", raw["$id"], config.CurrentConfigSchemaURL())}}diff --git a/cmd/pinchtab/cmd_mcp.go b/cmd/pinchtab/cmd_mcp.goindex bad8bf87..fed5e3c4 100644--- a/cmd/pinchtab/cmd_mcp.go+++ b/cmd/pinchtab/cmd_mcp.go@@ -28,7 +28,7 @@ func runMCP(cfg *config.RuntimeConfig) {baseURL := resolveCLIBase(cfg)token := resolveCLIToken(cfg)- if err := ensureServer(baseURL, token, "mcp"); err != nil {+ if err := ensureServerForCLI(cfg, baseURL, token, "mcp"); err != nil {fmt.Fprintf(os.Stderr, "mcp: %v\n", err)os.Exit(1)}diff --git a/cmd/pinchtab/cmd_mcp_test.go b/cmd/pinchtab/cmd_mcp_test.goindex 12d66ebf..c8b55ccf 100644--- a/cmd/pinchtab/cmd_mcp_test.go+++ b/cmd/pinchtab/cmd_mcp_test.go@@ -4,6 +4,7 @@ import ("errors""net/http""net/http/httptest"+ "strings""testing""time")@@ -122,6 +123,43 @@ func TestEnsureServerStartsAndWaits(t *testing.T) {}}+func TestEnsureServerDoesNotStartWhenAutoStartDisabled(t *testing.T) {+ started := false++ err := ensureServerWithAutoStart(+ "http://127.0.0.1:9999",+ "",+ "test",+ false,+ func() error {+ started = true+ return nil+ },+ func(baseURL, token string) bool {+ return false+ },+ time.Second,+ )++ if err == nil || !strings.Contains(err.Error(), "auto-start is only supported") {+ t.Fatalf("ensureServerWithAutoStart() error = %v, want auto-start disabled error", err)+ }+ if started {+ t.Fatal("expected auto-start function not to run")+ }+}++func TestAutoStartServerArgsIgnoreClientServerURL(t *testing.T) {+ oldServerURL := serverURL+ serverURL = "http://127.0.0.1:9999"+ defer func() { serverURL = oldServerURL }()++ args := autoStartServerArgs()+ if len(args) != 1 || args[0] != "server" {+ t.Fatalf("autoStartServerArgs() = %v, want [server]", args)+ }+}+func TestEnsureServerReturnsStartError(t *testing.T) {wantErr := errors.New("boom")diff --git a/cmd/pinchtab/cmd_server_ensure.go b/cmd/pinchtab/cmd_server_ensure.goindex fbc4033e..b94f998b 100644--- a/cmd/pinchtab/cmd_server_ensure.go+++ b/cmd/pinchtab/cmd_server_ensure.go@@ -7,6 +7,8 @@ import ("os""os/exec""time"++ "github.com/pinchtab/pinchtab/internal/config")const ensureServerTimeout = 30 * time.Second@@ -14,15 +16,23 @@ const ensureServerTimeout = 30 * time.Secondtype serverStartFunc func() errortype serverHealthFunc func(baseURL, token string) bool-func ensureServer(baseURL, token, command string) error {- return ensureServerWith(baseURL, token, command, autoStartServer, isServerHealthy, ensureServerTimeout)+func ensureServerForCLI(cfg *config.RuntimeConfig, baseURL, token, command string) error {+ return ensureServerWithAutoStart(baseURL, token, command, canAutoStartServerForCLI(cfg, baseURL), autoStartServer, isServerHealthy, ensureServerTimeout)}func ensureServerWith(baseURL, token, command string, start serverStartFunc, healthy serverHealthFunc, timeout time.Duration) error {+ return ensureServerWithAutoStart(baseURL, token, command, true, start, healthy, timeout)+}++func ensureServerWithAutoStart(baseURL, token, command string, allowAutoStart bool, start serverStartFunc, healthy serverHealthFunc, timeout time.Duration) error {if healthy(baseURL, token) {return nil}+ if !allowAutoStart {+ return fmt.Errorf("server at %s is not running; auto-start is only supported for the default local server", baseURL)+ }+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)@@ -60,12 +70,7 @@ func autoStartServer() error {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 := exec.Command(binary, autoStartServerArgs()...) // #nosec G204 -- binary is our own executable from os.Executable(), args are hardcoded subcommandscmd.Stdin = nilcmd.Stdout = nilcmd.Stderr = nil@@ -82,6 +87,10 @@ func autoStartServer() error {return nil}+func autoStartServerArgs() []string {+ return []string{"server"}+}+func waitForServer(baseURL, token string, timeout time.Duration) bool {return waitForServerWith(baseURL, token, timeout, isServerHealthy)}diff --git a/cmd/pinchtab/root.go b/cmd/pinchtab/root.goindex 427d31e3..8acb2000 100644--- a/cmd/pinchtab/root.go+++ b/cmd/pinchtab/root.go@@ -105,6 +105,8 @@ var serverURL stringvar cliAgentID stringfunc init() {+ config.SetConfigSchemaVersion(version)+rootCmd.Version = versionrootCmd.SetVersionTemplate("pinchtab {{.Version}}\n")diff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex a16a238b..a126d4cf 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -49,7 +49,7 @@ 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:+`pinchtab nav <url>` auto-starts the local PinchTab server when it is not already running. Explicit `--server` and `PINCHTAB_SERVER` targets are used as-is and are not auto-started. To navigate and snapshot in one command after install, run:```bashpinchtab nav https://pinchtab.com --snap@@ -124,13 +124,13 @@ pinchtab server -e ./my-extension # load extension## Browser Commands-The browser control surface is top-level. `tab` is only for list/focus/new/close.+The browser control surface is top-level. `tab` is only for list/focus/close.Common commands:| Command | Purpose || --- | --- |-| `pinchtab nav <url>` | Open a new tab and navigate it |+| `pinchtab nav <url>` | Navigate current tracked tab, or create one if needed || `pinchtab nav <url> --snap` | Navigate and output an interactive compact snapshot || `pinchtab snap [selector]` | Accessibility snapshot for the current tab, optionally scoped || `pinchtab frame [target\|main]` | Show or set selector frame scope |diff --git a/docs/reference/config.md b/docs/reference/config.mdindex 7515d1fd..08cd660a 100644--- a/docs/reference/config.md+++ b/docs/reference/config.md@@ -39,11 +39,14 @@ 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.+Generated config files include a `$schema` URL for IDE completion and validation.### `pinchtab config schema`-Prints the versioned JSON Schema URL for this PinchTab build.+Prints the JSON Schema URL for this PinchTab build. Source builds, development+builds, and versions without a published schema use the `main` schema URL.+When a matching release schema is known, PinchTab uses that release tag; when a+newer matching schema is known, PinchTab uses the closest newer tag.```bashpinchtab config schema@@ -160,7 +163,7 @@ Current nested file-config shape:```json{- "$schema": "https://raw.githubusercontent.com/pinchtab/pinchtab/v0.8.0/schema/config.json",+ "$schema": "https://raw.githubusercontent.com/pinchtab/pinchtab/main/schema/config.json","configVersion": "0.8.0","server": {"port": "9867",diff --git a/docs/reference/navigate.md b/docs/reference/navigate.mdindex 413e2793..93147ec3 100644--- a/docs/reference/navigate.md+++ b/docs/reference/navigate.md@@ -14,7 +14,7 @@ pinchtab nav https://pinchtab.com## CLI Flags-`pinchtab nav <url>` auto-starts the local server when it is not already running.+`pinchtab nav <url>` auto-starts the default local server when it is not already running. When `--server` or `PINCHTAB_SERVER` targets another server, PinchTab connects to that server without auto-starting a new process.Hidden aliases: `goto`, `navigate`, `open`.| Flag | Description |diff --git a/internal/cli/actions/actions_navigate.go b/internal/cli/actions/actions_navigate.goindex 5b14278d..cbadd48b 100644--- a/internal/cli/actions/actions_navigate.go+++ b/internal/cli/actions/actions_navigate.go@@ -102,17 +102,18 @@ 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)+ req := buildNavigateRequest(url, cmd)// JSON output modejsonOutput, _ := cmd.Flags().GetBool("json")if jsonOutput {- result := apiclient.DoPost(client, base, token, path, body)+ result := postNavigate(client, base, token, req, true)apiclient.SuggestNextAction("navigate", result)return tabIDFromNavigateResult(result)}- resultTabID := postNavigateQuiet(client, base, token, path, body)+ result := postNavigate(client, base, token, req, false)+ resultTabID := tabIDFromNavigateResult(result)if resultTabID != "" {fmt.Println(resultTabID)}@@ -127,7 +128,13 @@ func Navigate(client *http.Client, base, token string, url string, cmd *cobra.Coreturn resultTabID}-func buildNavigateRequest(client *http.Client, base, token, url string, cmd *cobra.Command) (string, map[string]any) {+type navigateRequest struct {+ path string+ body map[string]any+ fallbackOnNotFound bool+}++func buildNavigateRequest(url string, cmd *cobra.Command) navigateRequest {body := map[string]any{"url": url}newTab, _ := cmd.Flags().GetBool("new-tab")if newTab {@@ -142,19 +149,35 @@ func buildNavigateRequest(client *http.Client, base, token, url string, cmd *cobtabID, _ := cmd.Flags().GetString("tab")path := "/navigate"explicitTab := cmd.Flags().Changed("tab")+ fallbackOnNotFound := false// 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)) {+ // the saved current-tab state file and no longer exists, retry through+ // /navigate so the server can create/select a current tab. Explicit --tab+ // remains strict and surfaces the 404.+ if tabID != "" && !newTab {path = "/tabs/" + tabID + "/navigate"+ fallbackOnNotFound = !explicitTab}- return path, body+ return navigateRequest{+ path: path,+ body: body,+ fallbackOnNotFound: fallbackOnNotFound,+ }}-func postNavigateQuiet(client *http.Client, base, token, path string, body map[string]any) string {- result := apiclient.DoPostQuiet(client, base, token, path, body)- return tabIDFromNavigateResult(result)+func postNavigate(client *http.Client, base, token string, req navigateRequest, printResponse bool) map[string]any {+ statusCode, respBody, result := apiclient.DoPostQuietWithStatus(client, base, token, req.path, req.body)+ if statusCode == http.StatusNotFound && req.fallbackOnNotFound {+ statusCode, respBody, result = apiclient.DoPostQuietWithStatus(client, base, token, "/navigate", req.body)+ }+ if statusCode >= 400 {+ apiclient.ExitWithAPIError(statusCode, respBody)+ }+ if printResponse {+ return apiclient.PrintAndDecode(respBody)+ }+ return result}func tabIDFromNavigateResult(result map[string]any) string {diff --git a/internal/cli/actions/actions_navigate_test.go b/internal/cli/actions/actions_navigate_test.goindex 270ed4b7..dff011ba 100644--- a/internal/cli/actions/actions_navigate_test.go+++ b/internal/cli/actions/actions_navigate_test.go@@ -2,6 +2,7 @@ package actionsimport ("encoding/json"+ "net/http""strings""testing"@@ -40,7 +41,7 @@ func TestNavigate(t *testing.T) {func TestNavigateReusesImplicitTabWhenItExists(t *testing.T) {m := newMockServer()- m.response = `{"tabs":[{"id":"ABC123"}],"tabId":"ABC123","status":"ok"}`+ m.response = `{"tabId":"ABC123","status":"ok"}`defer m.close()client := m.server.Client()@@ -51,20 +52,18 @@ func TestNavigateReusesImplicitTabWhenItExists(t *testing.T) {Navigate(client, m.base(), "", "https://pinchtab.com", cmd)- if len(m.requests) != 2 {- t.Fatalf("requests = %d, want 2", len(m.requests))+ if len(m.requests) != 1 {+ t.Fatalf("requests = %d, want 1", 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)+ if m.requests[0].Path != "/tabs/ABC123/navigate" {+ t.Fatalf("navigate path = %q, want /tabs/ABC123/navigate", m.requests[0].Path)}}func TestNavigateFallsBackToNewTabForStaleImplicitTab(t *testing.T) {m := newMockServer()- m.response = `{"tabs":[],"tabId":"NEW123","status":"ok"}`+ m.setResponse(http.MethodPost, "/tabs/STALE123/navigate", http.StatusNotFound, `{"error":"tab not found"}`)+ m.setResponse(http.MethodPost, "/navigate", http.StatusOK, `{"tabId":"NEW123","status":"ok"}`)defer m.close()client := m.server.Client()@@ -78,14 +77,28 @@ func TestNavigateFallsBackToNewTabForStaleImplicitTab(t *testing.T) {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[0].Path != "/tabs/STALE123/navigate" {+ t.Fatalf("first request path = %q, want /tabs/STALE123/navigate", m.requests[0].Path)}if m.requests[1].Path != "/navigate" {t.Fatalf("navigate path = %q, want /navigate", m.requests[1].Path)}}+func TestBuildNavigateRequestDoesNotFallbackForExplicitTab(t *testing.T) {+ cmd := newNavigateCmd()+ _ = cmd.Flags().Set("tab", "EXPLICIT123")++ req := buildNavigateRequest("https://pinchtab.com", cmd)++ if req.path != "/tabs/EXPLICIT123/navigate" {+ t.Fatalf("path = %q, want /tabs/EXPLICIT123/navigate", req.path)+ }+ if req.fallbackOnNotFound {+ t.Fatal("explicit --tab should not fallback on 404")+ }+}+func TestNavigateWithAllFlags(t *testing.T) {m := newMockServer()defer m.close()diff --git a/internal/cli/actions/actions_snapshot.go b/internal/cli/actions/actions_snapshot.goindex 20c5a67d..52aacc92 100644--- a/internal/cli/actions/actions_snapshot.go+++ b/internal/cli/actions/actions_snapshot.go@@ -1,13 +1,14 @@package actionsimport (- "github.com/pinchtab/pinchtab/internal/cli/apiclient"- "github.com/spf13/cobra""net/http""net/url"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/spf13/cobra")-func Snapshot(client *http.Client, base, token string, cmd *cobra.Command) {+func Snapshot(client *http.Client, base, token string, cmd *cobra.Command, selectorOverride string) {params := url.Values{}full, _ := cmd.Flags().GetBool("full")if !full {@@ -26,6 +27,8 @@ func Snapshot(client *http.Client, base, token string, cmd *cobra.Command) {}if v, _ := cmd.Flags().GetString("selector"); v != "" {params.Set("selector", v)+ } else if selectorOverride != "" {+ params.Set("selector", selectorOverride)}if v, _ := cmd.Flags().GetString("max-tokens"); v != "" {params.Set("maxTokens", v)diff --git a/internal/cli/actions/actions_snapshot_test.go b/internal/cli/actions/actions_snapshot_test.goindex adbca717..45b83d1b 100644--- a/internal/cli/actions/actions_snapshot_test.go+++ b/internal/cli/actions/actions_snapshot_test.go@@ -29,7 +29,7 @@ func TestSnapshot(t *testing.T) {cmd := newSnapshotCmd()_ = cmd.Flags().Set("interactive", "true")_ = cmd.Flags().Set("compact", "true")- Snapshot(client, m.base(), "", cmd)+ Snapshot(client, m.base(), "", cmd, "")if m.lastMethod != "GET" {t.Errorf("expected GET, got %s", m.lastMethod)}@@ -54,7 +54,7 @@ func TestSnapshotDiff(t *testing.T) {_ = cmd.Flags().Set("selector", "main")_ = cmd.Flags().Set("max-tokens", "2000")_ = cmd.Flags().Set("depth", "5")- Snapshot(client, m.base(), "", cmd)+ Snapshot(client, m.base(), "", cmd, "")if !strings.Contains(m.lastQuery, "diff=true") {t.Errorf("expected diff=true, got %s", m.lastQuery)}@@ -76,8 +76,20 @@ func TestSnapshotTabId(t *testing.T) {cmd := newSnapshotCmd()_ = cmd.Flags().Set("tab", "ABC123")- Snapshot(client, m.base(), "", cmd)+ Snapshot(client, m.base(), "", cmd, "")if !strings.Contains(m.lastQuery, "tabId=ABC123") {t.Errorf("expected tabId=ABC123, got %s", m.lastQuery)}}++func TestSnapshotSelectorOverride(t *testing.T) {+ m := newMockServer()+ defer m.close()+ client := m.server.Client()++ cmd := newSnapshotCmd()+ Snapshot(client, m.base(), "", cmd, "#main")+ if !strings.Contains(m.lastQuery, "selector=%23main") {+ t.Errorf("expected selector override, got %s", m.lastQuery)+ }+}diff --git a/internal/cli/actions/actions_tab_lookup.go b/internal/cli/actions/actions_tab_lookup.goindex 47861d9a..01ea021a 100644--- a/internal/cli/actions/actions_tab_lookup.go+++ b/internal/cli/actions/actions_tab_lookup.go@@ -9,22 +9,6 @@ import ("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 {diff --git a/internal/cli/actions/mock_server_test.go b/internal/cli/actions/mock_server_test.goindex 8d152b68..ff392e1d 100644--- a/internal/cli/actions/mock_server_test.go+++ b/internal/cli/actions/mock_server_test.go@@ -25,10 +25,16 @@ type mockServer struct {requests []capturedRequestresponse stringstatusCode int+ responses map[string]mockResponse+}++type mockResponse struct {+ statusCode int+ body string}func newMockServer() *mockServer {- m := &mockServer{statusCode: 200, response: `{"status":"ok"}`}+ m := &mockServer{statusCode: 200, response: `{"status":"ok"}`, responses: map[string]mockResponse{}}handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {m.lastMethod = r.Methodm.lastPath = r.URL.Path@@ -45,8 +51,9 @@ func newMockServer() *mockServer {Body: m.lastBody,Headers: m.lastHeaders.Clone(),})- w.WriteHeader(m.statusCode)- _, _ = w.Write([]byte(m.response))+ resp := m.responseFor(r.Method, r.URL.Path)+ w.WriteHeader(resp.statusCode)+ _, _ = w.Write([]byte(resp.body))})listener, err := net.Listen("tcp4", "127.0.0.1:0")if err != nil {@@ -63,3 +70,14 @@ func newMockServer() *mockServer {func (m *mockServer) close() { m.server.Close() }func (m *mockServer) base() string { return m.server.URL }++func (m *mockServer) setResponse(method, path string, statusCode int, body string) {+ m.responses[method+" "+path] = mockResponse{statusCode: statusCode, body: body}+}++func (m *mockServer) responseFor(method, path string) mockResponse {+ if resp, ok := m.responses[method+" "+path]; ok {+ return resp+ }+ return mockResponse{statusCode: m.statusCode, body: m.response}+}diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.goindex 69584e44..547fcc34 100644--- a/internal/cli/apiclient/client.go+++ b/internal/cli/apiclient/client.go@@ -85,8 +85,21 @@ func DoPostQuiet(client *http.Client, base, token, path string, body map[string]return DoPostQuietWithHeaders(client, base, token, path, body, nil)}+func DoPostQuietWithStatus(client *http.Client, base, token, path string, body map[string]any) (int, []byte, map[string]any) {+ return doPostQuietWithStatus(client, base, token, path, body, nil)+}+// DoPostQuietWithHeaders is like DoPostQuiet but allows custom headers.func DoPostQuietWithHeaders(client *http.Client, base, token, path string, body map[string]any, headers map[string]string) map[string]any {+ statusCode, respBody, result := doPostQuietWithStatus(client, base, token, path, body, headers)+ if statusCode >= 400 {+ handleAPIError(statusCode, respBody)+ os.Exit(1)+ }+ return result+}++func doPostQuietWithStatus(client *http.Client, base, token, path string, body map[string]any, headers map[string]string) (int, []byte, map[string]any) {data, _ := json.Marshal(body)req, _ := http.NewRequest("POST", base+path, bytes.NewReader(data))req.Header.Set("Content-Type", "application/json")@@ -101,16 +114,22 @@ func DoPostQuietWithHeaders(client *http.Client, base, token, path string, bodydefer func() { _ = resp.Body.Close() }()respBody, _ := io.ReadAll(resp.Body)- if resp.StatusCode >= 400 {- handleAPIError(resp.StatusCode, respBody)- os.Exit(1)- }-var result map[string]any- if err := json.Unmarshal(respBody, &result); err != nil {- log.Printf("warning: error unmarshaling response: %v", err)+ if resp.StatusCode < 400 {+ if err := json.Unmarshal(respBody, &result); err != nil {+ log.Printf("warning: error unmarshaling response: %v", err)+ }}- return result+ return resp.StatusCode, respBody, result+}++func PrintAndDecode(body []byte) map[string]any {+ return printAndDecode(body)+}++func ExitWithAPIError(statusCode int, body []byte) {+ handleAPIError(statusCode, body)+ os.Exit(1)}func DoPostWithHeaders(client *http.Client, base, token, path string, body map[string]any, headers map[string]string) map[string]any {diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex f2a74e06..d89381c6 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -2,13 +2,111 @@ package configimport ("path/filepath"+ "strconv"+ "strings")// 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"+const configSchemaRawBaseURL = "https://raw.githubusercontent.com/pinchtab/pinchtab"++// ConfigSchemaURL is the source-checkout/default JSON Schema URL. Released+// binaries replace this with their own release tag at command startup.+const ConfigSchemaURL = configSchemaRawBaseURL + "/main/schema/config.json"++var currentConfigSchemaURL = ConfigSchemaURL++// publishedConfigSchemaVersions lists release tags known to contain+// schema/config.json. Keep this empty until the first schema-bearing release is+// published; unknown versions fall back to main rather than broken old tags.+var publishedConfigSchemaVersions []string++// SetConfigSchemaVersion switches generated configs to the schema hosted on+// the release tag for a concrete release build. Non-release builds keep main,+// which avoids pointing at old config-version tags that predate the schema.+func SetConfigSchemaVersion(version string) {+ currentConfigSchemaURL = schemaURLForVersion(version)+}++// CurrentConfigSchemaURL returns the schema URL generated by this process.+func CurrentConfigSchemaURL() string {+ return currentConfigSchemaURL+}++func schemaURLForVersion(version string) string {+ version = strings.TrimPrefix(strings.TrimSpace(version), "v")+ if !isReleaseVersion(version) {+ return ConfigSchemaURL+ }+ schemaVersion, ok := closestPublishedConfigSchemaVersion(version)+ if !ok {+ return ConfigSchemaURL+ }+ return configSchemaRawBaseURL + "/v" + schemaVersion + "/schema/config.json"+}++func isReleaseVersion(version string) bool {+ _, ok := parseSemver(version)+ return ok+}++func closestPublishedConfigSchemaVersion(version string) (string, bool) {+ target, ok := parseSemver(version)+ if !ok {+ return "", false+ }++ // Use an older-or-equal schema so generated configs never point at rules+ // from a future PinchTab release.+ closest := ""+ for _, candidate := range publishedConfigSchemaVersions {+ parsed, ok := parseSemver(candidate)+ if !ok || compareSemver(parsed, target) > 0 {+ continue+ }+ if closest == "" {+ closest = candidate+ continue+ }+ closestParsed, _ := parseSemver(closest)+ if compareSemver(parsed, closestParsed) > 0 {+ closest = candidate+ }+ }+ return closest, closest != ""+}++func parseSemver(version string) ([3]int, bool) {+ var out [3]int+ parts := strings.Split(strings.TrimPrefix(strings.TrimSpace(version), "v"), ".")+ if len(parts) != 3 {+ return out, false+ }+ for i, part := range parts {+ if part == "" {+ return out, false+ }+ n, err := strconv.Atoi(part)+ if err != nil {+ return out, false+ }+ out[i] = n+ }+ return out, true+}++func compareSemver(a, b [3]int) int {+ for i := range a {+ if a[i] < b[i] {+ return -1+ }+ if a[i] > b[i] {+ return 1+ }+ }+ return 0+}// DefaultFileConfig returns a FileConfig with sensible defaults (nested format).func DefaultFileConfig() FileConfig {@@ -60,7 +158,7 @@ func DefaultFileConfig() FileConfig {autoSolverRetryMaxDelayMs := 10000autoSolverLLMFallback := falsereturn FileConfig{- Schema: ConfigSchemaURL,+ Schema: CurrentConfigSchemaURL(),ConfigVersion: CurrentConfigVersion,Server: ServerConfig{Port: defaultPort,diff --git a/internal/config/config_file_marshal.go b/internal/config/config_file_marshal.goindex f13382d2..e3542c34 100644--- a/internal/config/config_file_marshal.go+++ b/internal/config/config_file_marshal.go@@ -305,7 +305,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {}fc := FileConfig{- Schema: ConfigSchemaURL,+ Schema: CurrentConfigSchemaURL(),Server: ServerConfig{Port: cfg.Port,Bind: cfg.Bind,diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.goindex fbe067f6..f1a1f6ed 100644--- a/internal/config/config_file_test.go+++ b/internal/config/config_file_test.go@@ -9,8 +9,8 @@ import (func TestDefaultFileConfig(t *testing.T) {fc := DefaultFileConfig()- if fc.Schema != ConfigSchemaURL {- t.Errorf("DefaultFileConfig.Schema = %q, want %q", fc.Schema, ConfigSchemaURL)+ if fc.Schema != CurrentConfigSchemaURL() {+ t.Errorf("DefaultFileConfig.Schema = %q, want %q", fc.Schema, CurrentConfigSchemaURL())}if fc.Server.Port != "9867" {t.Errorf("DefaultFileConfig.Server.Port = %v, want 9867", fc.Server.Port)@@ -132,6 +132,65 @@ func TestDefaultFileConfig(t *testing.T) {}}+func TestConfigSchemaURLFallsBackToLatestWhenNoPublishedSchemaMatches(t *testing.T) {+ originalPublished := publishedConfigSchemaVersions+ t.Cleanup(func() {+ publishedConfigSchemaVersions = originalPublished+ SetConfigSchemaVersion("dev")+ })++ publishedConfigSchemaVersions = nil++ SetConfigSchemaVersion("1.2.3")+ if got := CurrentConfigSchemaURL(); got != ConfigSchemaURL {+ t.Fatalf("unpublished CurrentConfigSchemaURL() = %q, want latest %q", got, ConfigSchemaURL)+ }+ if fc := DefaultFileConfig(); fc.Schema != ConfigSchemaURL {+ t.Fatalf("DefaultFileConfig().Schema = %q, want latest %q", fc.Schema, ConfigSchemaURL)+ }++ SetConfigSchemaVersion("dev")+ if got := CurrentConfigSchemaURL(); got != ConfigSchemaURL {+ t.Fatalf("dev CurrentConfigSchemaURL() = %q, want %q", got, ConfigSchemaURL)+ }+}++func TestConfigSchemaURLUsesClosestOlderOrEqualPublishedSchema(t *testing.T) {+ originalPublished := publishedConfigSchemaVersions+ t.Cleanup(func() {+ publishedConfigSchemaVersions = originalPublished+ SetConfigSchemaVersion("dev")+ })++ publishedConfigSchemaVersions = []string{"1.2.3", "1.4.0", "2.0.0"}++ SetConfigSchemaVersion("1.2.3")+ wantReleaseURL := "https://raw.githubusercontent.com/pinchtab/pinchtab/v1.2.3/schema/config.json"+ if got := CurrentConfigSchemaURL(); got != wantReleaseURL {+ t.Fatalf("CurrentConfigSchemaURL() = %q, want %q", got, wantReleaseURL)+ }+ if fc := DefaultFileConfig(); fc.Schema != wantReleaseURL {+ t.Fatalf("DefaultFileConfig().Schema = %q, want %q", fc.Schema, wantReleaseURL)+ }++ SetConfigSchemaVersion("1.3.0")+ wantClosestOlderURL := "https://raw.githubusercontent.com/pinchtab/pinchtab/v1.2.3/schema/config.json"+ if got := CurrentConfigSchemaURL(); got != wantClosestOlderURL {+ t.Fatalf("closest older CurrentConfigSchemaURL() = %q, want %q", got, wantClosestOlderURL)+ }++ SetConfigSchemaVersion("1.1.0")+ if got := CurrentConfigSchemaURL(); got != ConfigSchemaURL {+ t.Fatalf("older than first published CurrentConfigSchemaURL() = %q, want latest %q", got, ConfigSchemaURL)+ }++ SetConfigSchemaVersion("2.1.0")+ wantLatestPublishedURL := "https://raw.githubusercontent.com/pinchtab/pinchtab/v2.0.0/schema/config.json"+ if got := CurrentConfigSchemaURL(); got != wantLatestPublishedURL {+ t.Fatalf("newer than published CurrentConfigSchemaURL() = %q, want %q", got, wantLatestPublishedURL)+ }+}+// TestIsLegacyConfig tests the format detection logic.func TestIsLegacyConfig(t *testing.T) {tests := []struct {@@ -263,8 +322,8 @@ func TestDefaultFileConfigJSON(t *testing.T) {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.Schema != CurrentConfigSchemaURL() {+ t.Errorf("round-trip Schema = %q, want %q", parsed.Schema, CurrentConfigSchemaURL())}if parsed.Server.Port != "9867" {t.Errorf("round-trip Server.Port = %v, want 9867", parsed.Server.Port)diff --git a/internal/config/workflow/mutate_test.go b/internal/config/workflow/mutate_test.goindex 8a49f5b8..0d856ad7 100644--- a/internal/config/workflow/mutate_test.go+++ b/internal/config/workflow/mutate_test.go@@ -25,7 +25,7 @@ func TestInitDefaultConfigIncludesSchema(t *testing.T) {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)+ if raw["$schema"] != config.CurrentConfigSchemaURL() {+ t.Fatalf("$schema = %q, want %q", raw["$schema"], config.CurrentConfigSchemaURL())}}diff --git a/schema/config.json b/schema/config.jsonindex a31b4876..f206a158 100644--- a/schema/config.json+++ b/schema/config.json@@ -1,6 +1,6 @@{"$schema": "http://json-schema.org/draft-07/schema#",- "$id": "https://raw.githubusercontent.com/pinchtab/pinchtab/v0.8.0/schema/config.json",+ "$id": "https://raw.githubusercontent.com/pinchtab/pinchtab/main/schema/config.json","title": "PinchTab configuration","description": "Configuration file for PinchTab. The CLI's Go validation remains authoritative for cross-field checks.","type": "object",@@ -9,7 +9,7 @@"$schema": {"type": "string","format": "uri",- "default": "https://raw.githubusercontent.com/pinchtab/pinchtab/v0.8.0/schema/config.json",+ "default": "https://raw.githubusercontent.com/pinchtab/pinchtab/main/schema/config.json","description": "JSON Schema URL for IDE validation."},"configVersion": {diff --git a/schema/schema.go b/schema/schema.goindex cb5c39ae..028909fc 100644--- a/schema/schema.go+++ b/schema/schema.go@@ -1,8 +1,34 @@package schema-import _ "embed"+import (+ _ "embed"+ "encoding/json"+ "fmt"+)// ConfigJSON is the PinchTab config JSON Schema bundled with this build.////go:embed config.jsonvar ConfigJSON []byte++// ConfigJSONForURL returns ConfigJSON with its public identifier rewritten to+// the URL generated by this build.+func ConfigJSONForURL(schemaURL string) ([]byte, error) {+ var raw map[string]any+ if err := json.Unmarshal(ConfigJSON, &raw); err != nil {+ return nil, fmt.Errorf("parse embedded schema: %w", err)+ }++ raw["$id"] = schemaURL+ properties, _ := raw["properties"].(map[string]any)+ schemaProperty, _ := properties["$schema"].(map[string]any)+ if schemaProperty != nil {+ schemaProperty["default"] = schemaURL+ }++ data, err := json.MarshalIndent(raw, "", " ")+ if err != nil {+ return nil, fmt.Errorf("render schema: %w", err)+ }+ return append(data, '\n'), nil+}diff --git a/schema/schema_test.go b/schema/schema_test.goindex 6c8894ce..d98f262a 100644--- a/schema/schema_test.go+++ b/schema/schema_test.go@@ -32,3 +32,26 @@ func TestConfigSchemaMetadata(t *testing.T) {t.Fatalf("config $schema default = %q, want %q", schemaProp["default"], config.ConfigSchemaURL)}}++func TestConfigJSONForURL(t *testing.T) {+ const schemaURL = "https://raw.githubusercontent.com/pinchtab/pinchtab/v1.2.3/schema/config.json"++ data, err := ConfigJSONForURL(schemaURL)+ if err != nil {+ t.Fatalf("ConfigJSONForURL() error = %v", err)+ }++ var raw map[string]any+ if err := json.Unmarshal(data, &raw); err != nil {+ t.Fatalf("rendered schema is not valid JSON: %v", err)+ }+ if raw["$id"] != schemaURL {+ t.Fatalf("schema $id = %q, want %q", raw["$id"], schemaURL)+ }++ properties := raw["properties"].(map[string]any)+ schemaProp := properties["$schema"].(map[string]any)+ if schemaProp["default"] != schemaURL {+ t.Fatalf("config $schema default = %q, want %q", schemaProp["default"], schemaURL)+ }+}diff --git a/skills/pinchtab/SKILL.md b/skills/pinchtab/SKILL.mdindex 808f7bb0..764cec83 100644--- a/skills/pinchtab/SKILL.md+++ b/skills/pinchtab/SKILL.md@@ -50,7 +50,7 @@ Fallback observation (when `--snap` wasn't used):- `pinchtab snap --full` — all nodes as JSON (for debugging).- `pinchtab text` — content only (use when snap is missing prose you need).-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.+Rules: only `nav <url>` auto-starts the default local server; `snap`, `text`, `html`, `find`, and action commands operate on an already-running server/current tab. Explicit `--server` targets are never auto-started. Never act on stale refs; screenshots only for visual/debug; choose the instance/profile up front for parallel or multi-site work.## Selectors@@ -89,7 +89,7 @@ pinchtab --server http://localhost:9868 snap -i -c # target a specific instance### Navigation and tabs```bash-pinchtab nav <url> # auto-starts local server; flags: --snap, --new-tab, --tab <id>, --block-images, --block-ads, --print-tab-id+pinchtab nav <url> # auto-starts default 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 tabdiff --git a/skills/pinchtab/references/commands.md b/skills/pinchtab/references/commands.mdindex 8753e9c0..72227744 100644--- a/skills/pinchtab/references/commands.md+++ b/skills/pinchtab/references/commands.md@@ -44,7 +44,7 @@ Check if the server is running and healthy.## Browser Commands### `pinchtab nav <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.+Navigate the current tracked tab to a URL, or create one when no current tab is available. This is the browser command that auto-starts the default local server when it is not already running.```bashpinchtab nav https://pinchtab.comdiff --git a/skills/pinchtab/references/mcp.md b/skills/pinchtab/references/mcp.mdindex 7200a363..2589890b 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 mcp` auto-starts the local PinchTab server if needed, then proxies requests to the 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. Explicit `--server` targets are used as-is and are not auto-started.> [!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.diff --git a/tests/e2e/scenarios/cli/system-basic.sh b/tests/e2e/scenarios/cli/system-basic.shindex 21cb702f..292d1eca 100644--- a/tests/e2e/scenarios/cli/system-basic.sh+++ b/tests/e2e/scenarios/cli/system-basic.sh@@ -99,10 +99,10 @@ start_test "config schema prints bundled schema"pt_ok config schemaSCHEMA_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"+if [[ "$SCHEMA_URL" =~ ^https://raw\.githubusercontent\.com/pinchtab/pinchtab/(main|v[0-9]+\.[0-9]+\.[0-9]+)/schema/config\.json$ ]]; then+ pass_assert "prints GitHub schema URL"else- fail_assert "prints versioned GitHub schema URL (got $SCHEMA_URL)"+ fail_assert "prints GitHub schema URL (got $SCHEMA_URL)"fipt_ok config schema --print