High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: tab focus command and index-based tab resolution
Bosch15cb975e7461
diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.goindex ae90fe01..d52ac62e 100644--- a/cmd/pinchtab/cmd_cli.go+++ b/cmd/pinchtab/cmd_cli.go@@ -88,13 +88,18 @@ var screenshotCmd = &cobra.Command{}var tabsCmd = &cobra.Command{- Use: "tab",+ Use: "tab [n|id]",Aliases: []string{"tabs"},- Short: "List or manage tabs",+ Short: "List tabs, or focus a tab by index or ID",+ Args: cobra.MaximumNArgs(1),Run: func(cmd *cobra.Command, args []string) {cfg := config.Load()runCLIWith(cfg, func(client *http.Client, base, token string) {- browseractions.TabList(client, base, token)+ if len(args) == 0 {+ browseractions.TabList(client, base, token)+ } else {+ browseractions.TabFocus(client, base, token, args[0])+ }})},}@@ -312,8 +317,8 @@ func init() {},})tabsCmd.AddCommand(&cobra.Command{- Use: "close <tabId>",- Short: "Close a tab",+ Use: "close <n|id>",+ Short: "Close a tab by index or ID",Args: cobra.ExactArgs(1),Run: func(cmd *cobra.Command, args []string) {cfg := config.Load()diff --git a/internal/bridge/api.go b/internal/bridge/api.goindex f56ad64e..fa701bd4 100644--- a/internal/bridge/api.go+++ b/internal/bridge/api.go@@ -18,6 +18,7 @@ type BridgeAPI interface {// The raw CDP target ID is stored internally and used for CDP operations.CreateTab(url string) (hashTabID string, ctx context.Context, cancel context.CancelFunc, err error)CloseTab(tabID string) error+ FocusTab(tabID string) errorGetRefCache(tabID string) *RefCacheSetRefCache(tabID string, cache *RefCache)diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.goindex 814e6158..754af0f2 100644--- a/internal/bridge/tab_manager.go+++ b/internal/bridge/tab_manager.go@@ -8,6 +8,7 @@ import ("time"cdp "github.com/chromedp/cdproto/cdp"+ "github.com/chromedp/cdproto/page""github.com/chromedp/cdproto/target""github.com/chromedp/chromedp""github.com/pinchtab/pinchtab/internal/config"@@ -342,6 +343,46 @@ func (tm *TabManager) CloseTab(tabID string) error {return nil}+// FocusTab activates a tab by ID, bringing it to the foreground and setting it+// as the current tab for subsequent operations.+func (tm *TabManager) FocusTab(tabID string) error {+ ctx, resolvedID, err := tm.TabContext(tabID)+ if err != nil {+ return err+ }++ // Bring the tab to front via CDP+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ return page.BringToFront().Do(ctx)+ })); err != nil {+ return fmt.Errorf("bring to front: %w", err)+ }++ tm.mu.Lock()+ tm.currentTab = resolvedID+ if entry, ok := tm.tabs[resolvedID]; ok {+ entry.LastUsed = time.Now()+ }+ tm.mu.Unlock()++ return nil+}++// ResolveTabByIndex resolves a 1-based tab index to a tab ID.+// Returns the tab ID and its URL/title for display.+func (tm *TabManager) ResolveTabByIndex(index int) (string, string, string, error) {+ targets, err := tm.ListTargets()+ if err != nil {+ return "", "", "", err+ }+ if index < 1 || index > len(targets) {+ return "", "", "", fmt.Errorf("tab index %d out of range (1-%d)", index, len(targets))+ }+ t := targets[index-1]+ tabID := tm.idMgr.TabIDFromCDPTarget(string(t.TargetID))+ return tabID, t.URL, t.Title, nil+}+func (tm *TabManager) ListTargets() ([]*target.Info, error) {if tm == nil {return nil, fmt.Errorf("tab manager not initialized")diff --git a/internal/cli/actions/actions_tabs.go b/internal/cli/actions/actions_tabs.goindex d5693b27..c571ce02 100644--- a/internal/cli/actions/actions_tabs.go+++ b/internal/cli/actions/actions_tabs.go@@ -1,11 +1,14 @@package actionsimport (+ "encoding/json""fmt"- "github.com/pinchtab/pinchtab/internal/cli"- "github.com/pinchtab/pinchtab/internal/cli/apiclient""net/http""os"+ "strconv"++ "github.com/pinchtab/pinchtab/internal/cli"+ "github.com/pinchtab/pinchtab/internal/cli/apiclient")// TabList lists all open tabs.@@ -25,10 +28,55 @@ func TabNew(client *http.Client, base, token string, body map[string]any) {apiclient.DoPost(client, base, token, "/tab", body)}-// TabClose closes a tab by ID (exported for cobra subcommand).-func TabClose(client *http.Client, base, token string, tabID string) {+// TabClose closes a tab by index or ID.+func TabClose(client *http.Client, base, token string, ref string) {+ tabID := resolveTabRef(client, base, token, ref)+ if tabID == "" {+ return+ }apiclient.DoPost(client, base, token, "/tab", map[string]any{"action": "close","tabId": tabID,})}++// TabFocus switches to a tab by index or ID, making it the active tab+// for subsequent commands.+func TabFocus(client *http.Client, base, token string, ref string) {+ tabID := resolveTabRef(client, base, token, ref)+ if tabID == "" {+ return+ }+ apiclient.DoPost(client, base, token, "/tab", map[string]any{+ "action": "focus",+ "tabId": tabID,+ })+}++// resolveTabRef resolves a tab reference that can be either a 1-based index+// (e.g., "1", "2") or a tab ID (e.g., "A1B2C3D4...").+// Returns the resolved tab ID, or empty string on error (already printed).+func resolveTabRef(client *http.Client, base, token string, ref string) string {+ n, err := strconv.Atoi(ref)+ if err != nil {+ // Not a number — treat as tab ID directly+ return ref+ }++ // Numeric — resolve index to tab ID via /tabs+ 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 {+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("Failed to parse tabs: %v", err)))+ return ""+ }+ if n < 1 || n > len(resp.Tabs) {+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("Tab index %d out of range (1-%d)", n, len(resp.Tabs))))+ return ""+ }+ return resp.Tabs[n-1].ID+}diff --git a/internal/cli/actions/actions_tabs_test.go b/internal/cli/actions/actions_tabs_test.goindex 2ca8ec2c..c701202d 100644--- a/internal/cli/actions/actions_tabs_test.go+++ b/internal/cli/actions/actions_tabs_test.go@@ -1,17 +1,77 @@package actionsimport (+ "encoding/json"+ "net/http"+ "net/http/httptest""testing")-func TestTabList(t *testing.T) {- m := newMockServer()- m.response = `[{"id":"TAB1","url":"https://pinchtab.com"}]`- defer m.close()- client := m.server.Client()-- TabList(client, m.base(), "")- if m.lastPath != "/tabs" {- t.Errorf("expected /tabs, got %s", m.lastPath)+func TestResolveTabRef(t *testing.T) {+ tabs := []struct {+ ID string `json:"id"`+ }{+ {ID: "AAAA1111"},+ {ID: "BBBB2222"},+ {ID: "CCCC3333"},}+ resp, _ := json.Marshal(map[string]any{"tabs": tabs})++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write(resp)+ }))+ defer srv.Close()++ client := srv.Client()++ t.Run("numeric index 1", func(t *testing.T) {+ id := resolveTabRef(client, srv.URL, "", "1")+ if id != "AAAA1111" {+ t.Errorf("expected AAAA1111, got %s", id)+ }+ })++ t.Run("numeric index 3", func(t *testing.T) {+ id := resolveTabRef(client, srv.URL, "", "3")+ if id != "CCCC3333" {+ t.Errorf("expected CCCC3333, got %s", id)+ }+ })++ t.Run("index out of range", func(t *testing.T) {+ id := resolveTabRef(client, srv.URL, "", "5")+ if id != "" {+ t.Errorf("expected empty, got %s", id)+ }+ })++ t.Run("index zero", func(t *testing.T) {+ id := resolveTabRef(client, srv.URL, "", "0")+ if id != "" {+ t.Errorf("expected empty, got %s", id)+ }+ })++ t.Run("negative index", func(t *testing.T) {+ // Negative numbers are valid ints but out of range+ id := resolveTabRef(client, srv.URL, "", "-1")+ if id != "" {+ t.Errorf("expected empty, got %s", id)+ }+ })++ t.Run("non-numeric passed through as ID", func(t *testing.T) {+ id := resolveTabRef(client, srv.URL, "", "AAAA1111")+ if id != "AAAA1111" {+ t.Errorf("expected AAAA1111, got %s", id)+ }+ })++ t.Run("hex-like ID passed through", func(t *testing.T) {+ id := resolveTabRef(client, srv.URL, "", "A1B2C3D4E5F6")+ if id != "A1B2C3D4E5F6" {+ t.Errorf("expected A1B2C3D4E5F6, got %s", id)+ }+ })}diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.goindex 574a3a22..3c672603 100644--- a/internal/handlers/handlers_test.go+++ b/internal/handlers/handlers_test.go@@ -55,6 +55,13 @@ func (m *mockBridge) CloseTab(tabID string) error {return nil}+func (m *mockBridge) FocusTab(tabID string) error {+ if tabID == "fail" {+ return fmt.Errorf("tab not found")+ }+ return nil+}+func (m *mockBridge) EnsureChrome(cfg *config.RuntimeConfig) error {// Mock implementation - just return nilreturn nil@@ -211,6 +218,60 @@ func TestHandleTab(t *testing.T) {}}+func TestHandleTabFocus(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ t.Run("focus success", func(t *testing.T) {+ body := `{"action": "focus", "tabId": "tab1"}`+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleTab(w, req)+ if w.Code != 200 {+ t.Errorf("expected 200, got %d", w.Code)+ }+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["focused"] != true {+ t.Error("expected focused=true")+ }+ if resp["tabId"] != "tab1" {+ t.Errorf("expected tabId=tab1, got %v", resp["tabId"])+ }+ })++ t.Run("focus missing tabId", func(t *testing.T) {+ body := `{"action": "focus"}`+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleTab(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+ })++ t.Run("focus not found", func(t *testing.T) {+ body := `{"action": "focus", "tabId": "fail"}`+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleTab(w, req)+ if w.Code != 404 {+ t.Errorf("expected 404, got %d", w.Code)+ }+ })++ t.Run("invalid action", func(t *testing.T) {+ body := `{"action": "invalid"}`+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleTab(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+ })+}+func searchString(s, substr string) bool {for i := 0; i <= len(s)-len(substr); i++ {if s[i:i+len(substr)] == substr {diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.goindex 574c26d6..7b15e80f 100644--- a/internal/handlers/health_tabs_test.go+++ b/internal/handlers/health_tabs_test.go@@ -296,6 +296,10 @@ func (m *MockBridge) CloseTab(tabID string) error {return nil}+func (m *MockBridge) FocusTab(tabID string) error {+ return nil+}+func (m *MockBridge) GetRefCache(tabID string) *bridge.RefCache {return nil}diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.goindex 5732b4f9..36cf6431 100644--- a/internal/handlers/navigation.go+++ b/internal/handlers/navigation.go@@ -411,7 +411,18 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {}web.JSON(w, 200, map[string]any{"closed": true})+ case "focus":+ if req.TabID == "" {+ web.Error(w, 400, fmt.Errorf("tabId required"))+ return+ }+ if err := h.Bridge.FocusTab(req.TabID); err != nil {+ web.Error(w, 404, err)+ return+ }+ web.JSON(w, 200, map[string]any{"focused": true, "tabId": req.TabID})+default:- web.Error(w, 400, fmt.Errorf("action must be 'new' or 'close'"))+ web.Error(w, 400, fmt.Errorf("action must be 'new', 'close', or 'focus'"))}}