High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(api): POST /tabs/{id}/close returns 404 for a missing tab and 409 for the last-tab precondition, not 500 (PIN-408)
Luigi Agostibc263ae9c2fd
diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.goindex 9d0da3ed..e6d12653 100644--- a/internal/bridge/tab_manager.go+++ b/internal/bridge/tab_manager.go@@ -306,6 +306,12 @@ func (tm *TabManager) createTab(url, browserContextID string) (string, context.Creturn tabID, ctx, cancel, nil}+// ErrCannotCloseLastTab is the last-tab precondition: at least one tab must+// remain or Chrome exits and takes the server down. It is a client precondition,+// not a server fault, so handlers classify it as a 4xx via errors.Is rather than+// matching the message text.+var ErrCannotCloseLastTab = errors.New("cannot close the last tab — at least one tab must remain")+func (tm *TabManager) CloseTab(tabID string) error {if tm == nil {return fmt.Errorf("tab manager not initialized")@@ -316,7 +322,7 @@ func (tm *TabManager) CloseTab(tabID string) error {return fmt.Errorf("list targets: %w", err)}if len(targets) <= 1 {- return fmt.Errorf("cannot close the last tab — at least one tab must remain")+ return ErrCannotCloseLastTab}tm.mu.Lock()diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.goindex 4836c1f9..54561005 100644--- a/internal/handlers/handlers_test.go+++ b/internal/handlers/handlers_test.go@@ -31,6 +31,7 @@ type mockBridge struct {ensureBrowserCfg *config.RuntimeConfigdialogManager *bridge.DialogManagerexecuteActionErr error+ closeTabErr erroractionResult map[string]anyautoCloseArmed []stringautoCloseCanceled []string@@ -105,6 +106,9 @@ func (m *mockBridge) CreateTabInBrowserContext(url, browserContextID string) (st}func (m *mockBridge) CloseTab(tabID string) error {+ if m.closeTabErr != nil {+ return m.closeTabErr+ }if tabID == "fail" {return fmt.Errorf("close failed")}diff --git a/internal/handlers/tab_lifecycle.go b/internal/handlers/tab_lifecycle.goindex 794dcb88..6b459f42 100644--- a/internal/handlers/tab_lifecycle.go+++ b/internal/handlers/tab_lifecycle.go@@ -3,11 +3,13 @@ package handlersimport ("context""encoding/json"+ "errors""fmt""net/http""strings""github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/httpx")@@ -167,7 +169,18 @@ func (h *Handlers) closeTab(w http.ResponseWriter, r *http.Request, tabID string}if err := h.Bridge.CloseTab(tabID); err != nil {- httpx.Error(w, 500, err)+ var notFound *bridge.TabNotFoundError+ switch {+ case errors.As(err, ¬Found):+ // Match every other tab-scoped op: a missing tab is a 404 client error,+ // not a server fault. WriteTabContextError also carries the crash+ // annotation when the tab died with the browser.+ WriteTabContextError(w, err, 404)+ case errors.Is(err, bridge.ErrCannotCloseLastTab):+ httpx.ErrorCode(w, http.StatusConflict, "cannot_close_last_tab", err.Error(), false, nil)+ default:+ httpx.Error(w, 500, err)+ }return}diff --git a/internal/handlers/tab_lifecycle_test.go b/internal/handlers/tab_lifecycle_test.gonew file mode 100644index 00000000..ebc7e642--- /dev/null+++ b/internal/handlers/tab_lifecycle_test.go@@ -0,0 +1,67 @@+package handlers++import (+ "bytes"+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+)++// Closing a tab classifies the failure the way every other tab-scoped op does: a+// missing tab is a 404 client error, the last-tab precondition a 409, and only a+// genuine internal failure a 500. Before this fix the explicit-tabID path mapped+// every CloseTab error to 500, so a missing tab tripped integrator alerting.+func TestCloseTabClassifiesBridgeErrors(t *testing.T) {+ for _, tc := range []struct {+ name string+ err error+ want int+ }{+ {name: "missing tab is 404", err: &bridge.TabNotFoundError{TabID: "DEADBEEF00000000"}, want: http.StatusNotFound},+ {name: "last tab precondition is 409", err: bridge.ErrCannotCloseLastTab, want: http.StatusConflict},+ {name: "internal failure stays 500", err: fmt.Errorf("tab manager not initialized"), want: http.StatusInternalServerError},+ } {+ t.Run(tc.name, func(t *testing.T) {+ h := New(&mockBridge{closeTabErr: tc.err}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ req := httptest.NewRequest(http.MethodPost, "/tabs/DEADBEEF00000000/close", nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != tc.want {+ t.Fatalf("status = %d, want %d: %s", w.Code, tc.want, w.Body.String())+ }+ })+ }+}++// The success path is unchanged: a real close still returns 200.+func TestCloseTabSucceeds(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ req := httptest.NewRequest(http.MethodPost, "/close", bytes.NewReader([]byte(`{"tabId":"tab1"}`)))+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())+ }+}++// The last-tab guard returns a sentinel handlers can classify with errors.Is,+// not a message they must string-match — so rewording it cannot silently send+// the precondition back to 500.+func TestErrCannotCloseLastTabIsMatchable(t *testing.T) {+ if !errors.Is(fmt.Errorf("wrap: %w", bridge.ErrCannotCloseLastTab), bridge.ErrCannotCloseLastTab) {+ t.Fatal("ErrCannotCloseLastTab is not matchable through errors.Is")+ }+}