High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: the CLI error remedy hook mutates state from inside the API error formatter (PIN-135)
Luigi Agostia84d94f4cb87
diff --git a/cmd/pinchtab/tab_state.go b/cmd/pinchtab/tab_state.goindex c2d3a689..554fd9d3 100644--- a/cmd/pinchtab/tab_state.go+++ b/cmd/pinchtab/tab_state.go@@ -1,8 +1,6 @@package mainimport (- "bytes"- "fmt""io""net/http""os"@@ -108,7 +106,9 @@ func (s tabStateStore) resolveArg(args []string) string {if !s.useLocal() {return ""}- return s.read()+ cached := s.read()+ s.announceCachedTab(cached)+ return cached}// applyDefaultFlag fills an unset --tab from the cached current tab, probing the@@ -136,6 +136,7 @@ func (s tabStateStore) applyDefaultFlag(cmd *cobra.Command) {_ = os.Remove(s.path())return}+ s.announceCachedTab(tabID)_ = cmd.Flags().Set("tab", tabID)flag.Changed = false}@@ -194,23 +195,18 @@ func (tabStateStore) probe(tabID string) tabProbeResult {}}-// A tab-not-found 404 that names an ID the user never typed is unactionable on its-// own — the ID came from this cache, so this is the only layer that can say so.-// Clearing it here is the remedy rather than instructions to delete a file: the-// retry the message asks for is what makes it true.-func init() { apiclient.ErrorRemedy = defaultTabState.staleTabRemedy }--func (s tabStateStore) staleTabRemedy(statusCode int, body []byte) string {- if statusCode != http.StatusNotFound || !s.useLocal() {- return ""- }- cached := s.read()- if cached == "" || !bytes.Contains(body, []byte(cached)) {- return ""+// announceCachedTab hands the error renderer the two facts only this layer knows —+// that the id came from this cache, and where that cache lives — as data, at the+// moment the substitution happens. A tab-not-found 404 naming an id the user never+// typed is unactionable without them, and resolving them here keeps the config read+// and the state-file deletion out of the render path: the renderer formats, the+// terminal path in apiclient clears.+func (s tabStateStore) announceCachedTab(tabID string) {+ if tabID == "" {+ return}- _ = os.Remove(s.path())base, _ := resolveTabStateEndpoint()- return fmt.Sprintf("that tab id is this CLI's cached current tab for %s, not something you asked for; the cache is now cleared, so retry the command (or run `pinchtab nav <url>` to open a fresh tab)", base)+ apiclient.UseCachedTab(apiclient.CachedTab{TabID: tabID, Base: base, StateFile: s.path()})}// The package-level helpers below preserve the existing CLI/test API bydiff --git a/cmd/pinchtab/tab_state_test.go b/cmd/pinchtab/tab_state_test.goindex 70d8219a..6d4a745a 100644--- a/cmd/pinchtab/tab_state_test.go+++ b/cmd/pinchtab/tab_state_test.go@@ -50,6 +50,12 @@ func newTabStateHarness(t *testing.T) *tabStateHarness {t.Setenv("PINCHTAB_AGENT_ID", "")t.Setenv("PINCHTAB_SERVER", "")t.Setenv("PINCHTAB_TOKEN", "")+ // The cached-tab announcement is process-global data in apiclient, so each+ // harness starts from nothing rather than from whatever a previous test left.+ previousAnnounced := apiclient.AnnouncedCachedTab()+ apiclient.UseCachedTab(apiclient.CachedTab{})+ t.Cleanup(func() { apiclient.UseCachedTab(previousAnnounced) })+oldAgent := cliAgentIDcliAgentID = ""oldResolve := resolveTabStateEndpoint@@ -188,32 +194,68 @@ func TestInconclusiveProbeDoesNotProtectAStaleEntry(t *testing.T) {}// A 404 naming an id the user never typed is unactionable without saying where the-// id came from. The remedy also clears the cache, so the retry it asks for works.-func TestStaleTabErrorCarriesTheCachedTabRemedy(t *testing.T) {- newTabStateHarness(t)+// id came from, and only this layer knows. It hands the renderer that fact as data+// at the moment it substitutes the cached id — so the remedy needs no callback+// installed into apiclient, and no config read or file deletion while an error is+// being formatted.+func TestSubstitutingTheCachedTabAnnouncesItToTheErrorRenderer(t *testing.T) {+ h := newTabStateHarness(t)WriteTabStateFile("CACHED-TAB")- body := []byte(`{"code":"tab_not_found","error":"tab CACHED-TAB not found"}`)- remedy := apiclient.ErrorRemedy(http.StatusNotFound, body)+ cmd := tabFlagCommand()+ defaultTabFlagFromState(cmd)+ if got, _ := cmd.Flags().GetString("tab"); got != "CACHED-TAB" {+ t.Fatalf("--tab = %q, want the cached tab so the announcement has something to describe", got)+ }- if remedy == "" {- t.Fatal("no remedy for a 404 naming the cached tab")+ announced := apiclient.AnnouncedCachedTab()+ if announced.TabID != "CACHED-TAB" {+ t.Errorf("announced tab id = %q, want CACHED-TAB; without it the renderer cannot tell a cached id from one the user typed", announced.TabID)}- for _, want := range []string{"cached current tab", "retry", "pinchtab nav"} {- if !strings.Contains(remedy, want) {- t.Errorf("remedy %q does not mention %q", remedy, want)- }+ if announced.Base != h.base {+ t.Errorf("announced base = %q, want the server this cache belongs to (%q)", announced.Base, h.base)}- if _, err := os.Stat(tabStateFile()); !os.IsNotExist(err) {- t.Error("the remedy claims the cache is cleared but the file survived")+ if announced.StateFile != tabStateFile() {+ t.Errorf("announced state file = %q, want %q — the terminal path removes this file", announced.StateFile, tabStateFile())+ }+ if _, err := os.Stat(tabStateFile()); err != nil {+ t.Errorf("announcing the cached tab must not touch it: %v", err)+ }+}++// A positional tab argument resolves from the same cache, so it needs the same+// announcement — the commands taking `pinchtab <cmd> [tab]` reach the identical 404.+func TestResolvingAPositionalTabFromTheCacheAnnouncesIt(t *testing.T) {+ newTabStateHarness(t)+ WriteTabStateFile("CACHED-TAB")++ if got := resolveTabArg(nil); got != "CACHED-TAB" {+ t.Fatalf("resolveTabArg = %q, want the cached tab", got)+ }+ if got := apiclient.AnnouncedCachedTab().TabID; got != "CACHED-TAB" {+ t.Errorf("announced tab id = %q after a positional resolve, want CACHED-TAB", got)}+}- // A 404 about someone else's tab is not this cache's business.+// An id the user typed is not this cache's business: the remedy says "not something+// you asked for", so announcing an explicit id would make the message a lie.+func TestAnExplicitTabIsNotAnnouncedAsCached(t *testing.T) {+ newTabStateHarness(t)WriteTabStateFile("CACHED-TAB")- if got := apiclient.ErrorRemedy(http.StatusNotFound, []byte(`{"error":"tab SOMEONE-ELSE not found"}`)); got != "" {- t.Errorf("remedy %q offered for a tab the cache never held", got)++ if got := resolveTabArg([]string{"TYPED-TAB"}); got != "TYPED-TAB" {+ t.Fatalf("resolveTabArg = %q, want the explicit argument", got)}- if _, err := os.Stat(tabStateFile()); err != nil {- t.Errorf("unrelated 404 cleared the cache: %v", err)+ if got := apiclient.AnnouncedCachedTab().TabID; got != "" {+ t.Errorf("announced %q for a tab the user typed; the remedy would claim it came from the cache", got)+ }++ cmd := tabFlagCommand()+ if err := cmd.Flags().Set("tab", "TYPED-TAB"); err != nil {+ t.Fatal(err)+ }+ defaultTabFlagFromState(cmd)+ if got := apiclient.AnnouncedCachedTab().TabID; got != "" {+ t.Errorf("announced %q when --tab was set explicitly", got)}}diff --git a/internal/cli/apiclient/apierror.go b/internal/cli/apiclient/apierror.goindex 8601a478..f2745a70 100644--- a/internal/cli/apiclient/apierror.go+++ b/internal/cli/apiclient/apierror.go@@ -1,6 +1,7 @@package apiclientimport (+ "bytes""encoding/json""fmt""net/http"@@ -18,9 +19,12 @@ func mustRequest(client *http.Client, token string, r request) (int, []byte) {return status, body}+// exitOnAPIError is a terminal path: the command is ending, so this is where the+// failure is HANDLED rather than formatted, and where the cached tab that produced+// a dead id is dropped.func exitOnAPIError(r request, status int, body []byte) {if status >= 400 {- fmt.Fprint(os.Stderr, renderAPIError(r, status, body))+ fmt.Fprint(os.Stderr, renderAPIError(r, status, body)+clearCachedTabOnFailure(status, body))os.Exit(1)}}@@ -56,28 +60,68 @@ func routeNotFoundMessage(method, rawURL string) string {addr, method, path)}+// ExitWithAPIError is the other terminal path. See exitOnAPIError.func ExitWithAPIError(statusCode int, body []byte) {- handleAPIError(statusCode, body)+ fmt.Fprint(os.Stderr, renderAPIErrorBody(statusCode, body)+clearCachedTabOnFailure(statusCode, body))os.Exit(1)}-func handleAPIError(statusCode int, body []byte) {- fmt.Fprint(os.Stderr, renderAPIErrorBody(statusCode, body))+// CachedTab is what the CLI knows before it issues a request and the server does+// not: this tab id came from the CLI's own cache rather than from the user, which+// server that cache belongs to, and which file holds it.+//+// It is data, not an installed callback. The remedy it feeds used to arrive as a+// func the command layer assigned to a package variable, and that func read the+// config and deleted the state file — so building an error string performed+// filesystem I/O on every render, including the returning paths a poll loop drives+// ten times a second. As data, rendering it cannot do either, by construction.+//+// The zero value asks for nothing: a binary that never sets it renders exactly as+// before, so behaviour no longer depends on which binary linked this package.+type CachedTab struct {+ TabID string // the id the CLI substituted for one the user did not type+ Base string // the server the cache belongs to, for the message+ StateFile string // the file the terminal path removes}-// ErrorRemedy lets the command layer append a remedy the server cannot know about.-// A tab-not-found 404 naming an ID the user never typed is the case: only the CLI-// knows the ID came from its cached current tab, so only the CLI can say what to do-// about it. Unset by default; cmd/pinchtab installs one at startup.-var ErrorRemedy func(statusCode int, body []byte) string+var cachedTab CachedTab-func appendClientRemedy(b *strings.Builder, statusCode int, body []byte) {- if ErrorRemedy == nil {- return+// UseCachedTab records the cached tab the following requests target. The CLI calls+// it at the moment it substitutes its cached id, which is where both facts are+// already resolved — not while an error is being formatted.+func UseCachedTab(c CachedTab) { cachedTab = c }++// namesCachedTab is the one classifier both consumers share: the formatter for the+// wording, the terminal path for the clearing. Pure.+func namesCachedTab(statusCode int, body []byte) bool {+ return statusCode == http.StatusNotFound &&+ cachedTab.TabID != "" &&+ bytes.Contains(body, []byte(cachedTab.TabID))+}++// staleTabRemedy says where the id came from, and claims nothing about the cache's+// current state — it is emitted on returning paths too, where nothing is cleared.+// A retry is still the right advice there: the cached id is re-probed at the start+// of every command, so the next one drops it.+func staleTabRemedy(statusCode int, body []byte) string {+ if !namesCachedTab(statusCode, body) {+ return ""}- if remedy := ErrorRemedy(statusCode, body); remedy != "" {- fmt.Fprintf(b, " Remedy: %s\n", remedy)+ return fmt.Sprintf(" Remedy: that tab id is this CLI's cached current tab for %s, not something you asked for; retry the command (or run `pinchtab nav <url>` to open a fresh tab)\n", cachedTab.Base)+}++// clearCachedTabOnFailure drops the cache that produced the dead id and reports+// that it did. Terminal paths only, and the past-tense sentence is returned only+// when the file is actually gone, so the text can never claim a clearing that did+// not happen.+func clearCachedTabOnFailure(statusCode int, body []byte) string {+ if !namesCachedTab(statusCode, body) || cachedTab.StateFile == "" {+ return ""+ }+ if err := os.Remove(cachedTab.StateFile); err != nil && !os.IsNotExist(err) {+ return ""}+ return " The cached current tab is now cleared, so that retry will target the server's current tab.\n"}func renderAPIErrorBody(statusCode int, body []byte) string {@@ -106,7 +150,7 @@ func renderAPIErrorBody(statusCode int, body []byte) string {fmt.Fprintf(&b, " Remedy: %s\n", remedy)}}- appendClientRemedy(&b, statusCode, body)+ b.WriteString(staleTabRemedy(statusCode, body))return b.String()}@@ -114,3 +158,8 @@ func fatal(format string, args ...any) {fmt.Fprintf(os.Stderr, format+"\n", args...)os.Exit(1)}++// AnnouncedCachedTab reports the cached tab the CLI last announced. It exists for+// the command layer's tests: the handoff is the seam between the two packages, and+// asserting on it is what pins that the CLI still performs it.+func AnnouncedCachedTab() CachedTab { return cachedTab }diff --git a/internal/cli/apiclient/apierror_test.go b/internal/cli/apiclient/apierror_test.goindex 5990ef62..73f66d26 100644--- a/internal/cli/apiclient/apierror_test.go+++ b/internal/cli/apiclient/apierror_test.go@@ -1,9 +1,17 @@package apiclientimport (+ "errors"+ "fmt"+ "go/ast"+ "go/parser"+ "go/token""io""net/http""net/http/httptest"+ "os"+ "os/exec"+ "path/filepath""strings""testing")@@ -99,3 +107,237 @@ func TestRenderAPIErrorBodyShowsNavigationChangedHintAndRemedy(t *testing.T) {}}}++// cachedTabFile installs a cached-tab context pointing at a real file, so a render+// that still performed the old os.Remove would be visible as a missing file rather+// than as an assertion about a string.+func cachedTabFile(t *testing.T, tabID string) string {+ t.Helper()+ path := filepath.Join(t.TempDir(), "current-tab-127.0.0.1-9867")+ if err := os.WriteFile(path, []byte(tabID+"\n"), 0600); err != nil {+ t.Fatal(err)+ }+ previous := cachedTab+ UseCachedTab(CachedTab{TabID: tabID, Base: "http://127.0.0.1:9867", StateFile: path})+ t.Cleanup(func() { UseCachedTab(previous) })+ return path+}++// Formatting an error must not mutate anything. The remedy used to arrive as an+// installed callback that deleted the state file and read the config, so every+// render — including the ones a poll loop throws away — cleared persistent state.+func TestRenderingAStaleTab404TwiceLeavesTheCacheIntact(t *testing.T) {+ path := cachedTabFile(t, "CACHED-TAB")+ body := []byte(`{"code":"tab_not_found","error":"tab CACHED-TAB not found"}`)++ first := renderAPIErrorBody(http.StatusNotFound, body)+ second := renderAPIErrorBody(http.StatusNotFound, body)++ if first != second {+ t.Errorf("rendering the same error twice differs, so something is carrying state:\n%s\n---\n%s", first, second)+ }+ for _, want := range []string{"cached current tab", "127.0.0.1:9867", "retry the command", "pinchtab nav"} {+ if !strings.Contains(first, want) {+ t.Errorf("remedy missing %q:\n%s", want, first)+ }+ }+ if strings.Contains(first, "now cleared") {+ t.Errorf("a render claims a completed clearing it did not perform:\n%s", first)+ }+ if data, err := os.ReadFile(path); err != nil || strings.TrimSpace(string(data)) != "CACHED-TAB" {+ t.Fatalf("rendering an error mutated the cached tab file (%v, %q)", err, string(data))+ }+}++// A 404 about a tab this CLI never cached is not this cache's business.+func TestUnrelatedTabNotFoundGetsNoRemedy(t *testing.T) {+ path := cachedTabFile(t, "CACHED-TAB")+ out := renderAPIErrorBody(http.StatusNotFound, []byte(`{"error":"tab SOMEONE-ELSE not found"}`))+ if strings.Contains(out, "cached current tab") {+ t.Errorf("remedy offered for a tab the cache never held:\n%s", out)+ }+ if _, err := os.Stat(path); err != nil {+ t.Errorf("unrelated 404 cleared the cache: %v", err)+ }+}++// DoGetRawE and DoPostRawE return instead of terminating — one caller polls them+// ten times a second — so rendering their error must leave the cache alone.+func TestReturningRequestPathsLeaveTheCacheIntact(t *testing.T) {+ path := cachedTabFile(t, "CACHED-TAB")+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusNotFound)+ _, _ = w.Write([]byte(`{"code":"tab_not_found","error":"tab CACHED-TAB not found"}`))+ }))+ defer srv.Close()++ for _, tc := range []struct {+ name string+ call func() ([]byte, error)+ }{+ {"DoGetRawE", func() ([]byte, error) { return DoGetRawE(srv.Client(), srv.URL, "", "/tabs/CACHED-TAB/text", nil) }},+ {"DoPostRawE", func() ([]byte, error) {+ return DoPostRawE(srv.Client(), srv.URL, "", "/action", map[string]any{"kind": "click"})+ }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ _, err := tc.call()+ if err == nil {+ t.Fatal("expected the 404 to be returned as an error")+ }+ if !strings.Contains(err.Error(), "cached current tab") {+ t.Errorf("returned error lost the remedy:\n%v", err)+ }+ if strings.Contains(err.Error(), "now cleared") {+ t.Errorf("a returning path claims the cache was cleared:\n%v", err)+ }+ if _, statErr := os.Stat(path); statErr != nil {+ t.Fatalf("%s cleared the cached tab: %v", tc.name, statErr)+ }+ })+ }+}++// The remedy used to be an installed func the command layer assigned at init(), so+// this package's behaviour depended on which binary linked it and its own tests+// were side-effect free only because the variable happened to be nil here. Data+// cannot carry behaviour; a func variable can, so none may come back.+func TestNoMutablePackageLevelFunctionVariables(t *testing.T) {+ paths, err := filepath.Glob("*.go")+ if err != nil {+ t.Fatal(err)+ }+ fileSet := token.NewFileSet()+ scanned := 0+ for _, path := range paths {+ if strings.HasSuffix(path, "_test.go") {+ continue+ }+ file, err := parser.ParseFile(fileSet, path, nil, 0)+ if err != nil {+ t.Fatalf("parse %s: %v", path, err)+ }+ scanned+++ for _, decl := range file.Decls {+ gen, ok := decl.(*ast.GenDecl)+ if !ok || gen.Tok != token.VAR {+ continue+ }+ for _, spec := range gen.Specs {+ value, ok := spec.(*ast.ValueSpec)+ if !ok {+ continue+ }+ for i, name := range value.Names {+ if declaresFunc(value.Type) || (i < len(value.Values) && declaresFunc(value.Values[i])) {+ t.Errorf("%s:%d declares the package-level function variable %s; the command layer must hand this package DATA, not behaviour it installs",+ path, fileSet.Position(name.Pos()).Line, name.Name)+ }+ }+ }+ }+ }+ if scanned < 2 {+ t.Fatalf("scanned %d source files; this census matched almost nothing and would pass vacuously", scanned)+ }+}++func declaresFunc(expr ast.Expr) bool {+ switch expr.(type) {+ case *ast.FuncType, *ast.FuncLit:+ return true+ }+ return false+}++const terminalChildEnv = "PINCHTAB_TEST_TERMINAL_API_ERROR"++// The clearing moved to the terminal paths, and those end in os.Exit, so the only+// honest way to test them is to be a different process. Criterion two of the card+// is kept verbatim: the purity cleanup must not quietly drop the feature — the+// remedy tells the user to retry, and the retry works because the dead id is gone.+func TestTerminalPathsClearTheCachedTabAndSayTheyDid(t *testing.T) {+ if mode := os.Getenv(terminalChildEnv); mode != "" {+ runTerminalChild(mode)+ return+ }++ for _, mode := range []string{"ExitWithAPIError", "DoGetRaw"} {+ t.Run(mode, func(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "current-tab-127.0.0.1-9867")+ if err := os.WriteFile(path, []byte("CACHED-TAB\n"), 0600); err != nil {+ t.Fatal(err)+ }++ child := exec.Command(os.Args[0], "-test.run=TestTerminalPathsClearTheCachedTabAndSayTheyDid", "-test.timeout=60s") // #nosec G204 -- re-executes this test binary.+ child.Env = append(os.Environ(), terminalChildEnv+"="+mode, "PINCHTAB_TEST_TAB_STATE_FILE="+path)+ raw, err := child.CombinedOutput()+ out := string(raw)++ var exitErr *exec.ExitError+ if !errors.As(err, &exitErr) {+ t.Fatalf("child exited with %v, want the terminal path's os.Exit(1); output:\n%s", err, out)+ }+ if code := exitErr.ExitCode(); code != 1 {+ t.Fatalf("child exit code = %d, want 1; output:\n%s", code, out)+ }+ if !strings.Contains(out, "cached current tab") || !strings.Contains(out, "retry the command") {+ t.Errorf("the terminal path lost the remedy:\n%s", out)+ }+ if !strings.Contains(out, "now cleared") {+ t.Errorf("the terminal path cleared the cache without saying so:\n%s", out)+ }+ if _, statErr := os.Stat(path); !os.IsNotExist(statErr) {+ t.Fatalf("the cached tab survived a command that failed on it (%v), so the remedy's retry advice is false", statErr)+ }+ })+ }+}++// runTerminalChild drives a real terminal path with a real cached-tab context, and+// exits through it.+func runTerminalChild(mode string) {+ body := []byte(`{"code":"tab_not_found","error":"tab CACHED-TAB not found"}`)+ UseCachedTab(CachedTab{+ TabID: "CACHED-TAB",+ Base: "http://127.0.0.1:9867",+ StateFile: os.Getenv("PINCHTAB_TEST_TAB_STATE_FILE"),+ })++ switch mode {+ case "ExitWithAPIError":+ ExitWithAPIError(http.StatusNotFound, body)+ case "DoGetRaw":+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusNotFound)+ _, _ = w.Write(body)+ }))+ defer srv.Close()+ DoGetRaw(srv.Client(), srv.URL, "", "/tabs/CACHED-TAB/text", nil)+ }+ fmt.Fprintf(os.Stderr, "child mode %q returned instead of exiting\n", mode)+ os.Exit(9)+}++// The past-tense sentence is a claim about a completed deletion, so it may only be+// emitted when the file is actually gone. A removal that fails must stay silent+// rather than tell the user to retry a command that will fail the same way.+func TestAFailedClearingSaysNothing(t *testing.T) {+ dir := t.TempDir()+ unremovable := filepath.Join(dir, "state-dir")+ if err := os.MkdirAll(filepath.Join(unremovable, "child"), 0755); err != nil {+ t.Fatal(err)+ }+ previous := cachedTab+ UseCachedTab(CachedTab{TabID: "CACHED-TAB", Base: "http://127.0.0.1:9867", StateFile: unremovable})+ t.Cleanup(func() { UseCachedTab(previous) })++ got := clearCachedTabOnFailure(http.StatusNotFound, []byte(`{"error":"tab CACHED-TAB not found"}`))+ if got != "" {+ t.Errorf("clearCachedTabOnFailure reported %q although the removal failed", got)+ }+ if _, err := os.Stat(unremovable); err != nil {+ t.Fatalf("precondition: the path was removable after all, so this test proves nothing: %v", err)+ }+}