High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: add session and agent scoped current tab routing
Luigi Agosti74154e71189a
diff --git a/cmd/pinchtab/cmd_cli_current_tab_test.go b/cmd/pinchtab/cmd_cli_current_tab_test.gonew file mode 100644index 00000000..13b1c078--- /dev/null+++ b/cmd/pinchtab/cmd_cli_current_tab_test.go@@ -0,0 +1,77 @@+package main++import (+ "testing"++ "github.com/spf13/cobra"+)++func TestUseLocalTabStateFileDisabledForIdentifiedCallers(t *testing.T) {+ oldAgentID := cliAgentID+ defer func() { cliAgentID = oldAgentID }()++ t.Run("session", func(t *testing.T) {+ cliAgentID = ""+ t.Setenv("PINCHTAB_AGENT_ID", "")+ t.Setenv("PINCHTAB_SESSION", "ses_test")+ if useLocalTabStateFile() {+ t.Fatal("session-authenticated callers should not use local current-tab state")+ }+ })++ t.Run("agent flag", func(t *testing.T) {+ cliAgentID = "agent-flag"+ t.Setenv("PINCHTAB_AGENT_ID", "")+ t.Setenv("PINCHTAB_SESSION", "")+ if useLocalTabStateFile() {+ t.Fatal("--agent-id callers should not use local current-tab state")+ }+ })++ t.Run("agent env", func(t *testing.T) {+ cliAgentID = ""+ t.Setenv("PINCHTAB_AGENT_ID", "agent-env")+ t.Setenv("PINCHTAB_SESSION", "")+ if useLocalTabStateFile() {+ t.Fatal("PINCHTAB_AGENT_ID callers should not use local current-tab state")+ }+ })+}++func TestDefaultTabFlagFromStateOnlyForAnonymousCallers(t *testing.T) {+ oldAgentID := cliAgentID+ defer func() { cliAgentID = oldAgentID }()++ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Setenv("PINCHTAB_AGENT_ID", "")+ t.Setenv("PINCHTAB_SESSION", "")+ cliAgentID = ""+ WriteTabStateFile("tab-local")++ anonymous := &cobra.Command{Use: "anonymous"}+ anonymous.Flags().String("tab", "", "Tab ID")+ defaultTabFlagFromState(anonymous)+ if got, _ := anonymous.Flags().GetString("tab"); got != "tab-local" {+ t.Fatalf("anonymous tab flag = %q, want tab-local", got)+ }+ if anonymous.Flags().Changed("tab") {+ t.Fatal("state-backed tab default should not mark --tab as explicitly changed")+ }++ t.Setenv("PINCHTAB_SESSION", "ses_test")+ sessionScoped := &cobra.Command{Use: "session"}+ sessionScoped.Flags().String("tab", "", "Tab ID")+ defaultTabFlagFromState(sessionScoped)+ if got, _ := sessionScoped.Flags().GetString("tab"); got != "" {+ t.Fatalf("session tab flag = %q, want empty", got)+ }++ t.Setenv("PINCHTAB_SESSION", "")+ cliAgentID = "agent-flag"+ agentScoped := &cobra.Command{Use: "agent"}+ agentScoped.Flags().String("tab", "", "Tab ID")+ defaultTabFlagFromState(agentScoped)+ if got, _ := agentScoped.Flags().GetString("tab"); got != "" {+ t.Fatalf("agent tab flag = %q, want empty", got)+ }+}diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.goindex a70dfab4..22772025 100644--- a/cmd/pinchtab/cmd_cli_register.go+++ b/cmd/pinchtab/cmd_cli_register.go@@ -434,29 +434,61 @@ func addRootCommands(cmds ...*cobra.Command) {rootCmd.AddCommand(cmds...)}-// 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:+// addTabFlag wires a --tab flag onto the given commands. Anonymous CLI calls+// default its value from the state file written by `nav`, which lets local+// single-agent workflows 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 no state file is set,-// the server picks the active tab as before.+// Explicit --tab still wins (cobra flag precedence). Identified callers+// (PINCHTAB_SESSION, --agent-id, or PINCHTAB_AGENT_ID) leave --tab unset so the+// server-side scoped current-tab store is authoritative. 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 !useLocalTabStateFile() {+ return ""+ }return readTabStateFile()}func addTabFlag(cmds ...*cobra.Command) {- defaultTab := readTabStateFile()for _, cmd := range cmds {- cmd.Flags().String("tab", defaultTab, "Tab ID")+ cmd.Flags().String("tab", "", "Tab ID")+ existingPreRun := cmd.PreRun+ cmd.PreRun = func(cmd *cobra.Command, args []string) {+ defaultTabFlagFromState(cmd)+ if existingPreRun != nil {+ existingPreRun(cmd, args)+ }+ }+ }+}++func defaultTabFlagFromState(cmd *cobra.Command) {+ if cmd == nil || !useLocalTabStateFile() {+ return+ }+ flag := cmd.Flags().Lookup("tab")+ if flag == nil || flag.Changed || flag.Value.String() != "" {+ return+ }+ if tabID := readTabStateFile(); tabID != "" {+ _ = cmd.Flags().Set("tab", tabID)+ flag.Changed = false+ }+}++func useLocalTabStateFile() bool {+ if strings.TrimSpace(os.Getenv("PINCHTAB_SESSION")) != "" {+ return false}+ return resolveCLIAgentID() == ""}// tabStateFile returns the path to the tab state file.@@ -481,7 +513,7 @@ func readTabStateFile() string {// WriteTabStateFile persists the tab ID to the state file for subsequent commands.func WriteTabStateFile(tabID string) {- if tabID == "" {+ if tabID == "" || !useLocalTabStateFile() {return}path := tabStateFile()@@ -492,7 +524,7 @@ func WriteTabStateFile(tabID string) {// ClearTabStateFileIfCurrent clears the current-tab state when the saved tab is// known to have been closed.func ClearTabStateFileIfCurrent(tabID string) {- if tabID == "" || readTabStateFile() != tabID {+ if tabID == "" || !useLocalTabStateFile() || readTabStateFile() != tabID {return}_ = os.Remove(tabStateFile())diff --git a/docs/commands.md b/docs/commands.mdindex dbe54fee..a316abd6 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -49,6 +49,11 @@ pinchtab click --tab <id> <selector>pinchtab pdf --tab <id> -o page.pdf```+Unscoped tab commands use server-side current-tab state when the caller is+identified: `PINCHTAB_SESSION` scopes current tabs by session, while+`--agent-id` or `PINCHTAB_AGENT_ID` scopes them by agent ID when no session is+present. Anonymous CLI calls keep using the shared local current-tab state file.+## InteractionMost element commands accept a unified selector:diff --git a/docs/endpoints.md b/docs/endpoints.mdindex c25a3f7b..da2b61b8 100644--- a/docs/endpoints.md+++ b/docs/endpoints.md@@ -90,9 +90,11 @@ Navigation request fields:Important behavior:-- `POST /navigate` creates a new tab when `tabId` is omitted+- `POST /navigate` creates a new tab when `tabId` is omitted for anonymous callers+- session-authenticated callers keep a current tab per session; omitted `tabId` reuses that session's current tab when one exists, otherwise creates one+- bearer-token callers with `X-Agent-Id` keep a current tab per agent ID when no session is present- `POST /tab` supports `new` and `focus`-- `POST /close` closes the `tabId` supplied in the JSON body, or the current/default tab when `tabId` is omitted+- `POST /close` closes the `tabId` supplied in the JSON body, or the caller's current/default tab when `tabId` is omitted## Handoff And Manual Interventiondiff --git a/docs/guides/agent-identity.md b/docs/guides/agent-identity.mdindex ac1ae2ea..bb818b2b 100644--- a/docs/guides/agent-identity.md+++ b/docs/guides/agent-identity.md@@ -38,6 +38,8 @@ pinchtab nav https://example.comThe `X-Agent-Id` header is sent with every request. No server-side setup required — any string works.+When a request has an agent ID but no agent session, PinchTab also keeps that agent's current tab separately from other agents. You can omit `tabId` in a multi-step flow without stealing another agent's current tab.+**When to use:** Multiple agents sharing one server where you want to see who did what, but don't need session management.**Limitation:** No revocation, no idle tracking, no labels. The agent ID is self-declared — any caller can claim any identity.@@ -120,6 +122,8 @@ curl -X POST http://localhost:9867/navigate \No need to set `--agent-id` — the session carries the agent identity.+Current-tab state is session-scoped. Two sessions for the same `agentId` keep separate current tabs, and session scope takes priority over any `X-Agent-Id` header.+### Manage Sessions```bashdiff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex 03f3978f..71d262b3 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -158,7 +158,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {var err errorctx, resolvedTabID, err = h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if req.TabID == "" {@@ -442,7 +442,7 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, revar err errorctx, resolvedTabID, err = h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if err := h.enforceTabLease(resolvedTabID, owner); err != nil {@@ -679,7 +679,7 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {var err errorctx, resolvedTabID, err = h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if err := h.enforceTabLease(resolvedTabID, owner); err != nil {diff --git a/internal/handlers/activity_helpers.go b/internal/handlers/activity_helpers.goindex f30b3f02..2b7a22ce 100644--- a/internal/handlers/activity_helpers.go+++ b/internal/handlers/activity_helpers.go@@ -3,14 +3,36 @@ package handlersimport ("context""net/http"+ "strings""github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/bridge")func (h *Handlers) tabContext(r *http.Request, tabID string) (context.Context, string, error) {+ tabID = strings.TrimSpace(tabID)+ scope := currentTabScopeFromRequest(r)+ explicitTab := tabID != ""++ if !explicitTab && !scope.IsGlobal() {+ storedTabID, ok := h.CurrentTabs.Get(scope)+ if !ok {+ return nil, "", noCurrentTabError(scope.Description())+ }+ tabID = storedTabID+ }+ctx, resolvedID, err := h.Bridge.TabContext(tabID)+ if err != nil && !explicitTab && !scope.IsGlobal() {+ // The stored pointer references a tab the bridge no longer knows+ // about: drop the pointer and surface the canonical empty-pointer+ // error so the caller sees 409 no_current_tab rather than a stale+ // "tab not found" 404.+ h.CurrentTabs.Clear(scope)+ return nil, "", noCurrentTabError(scope.Description())+ }if err == nil {+ h.setCurrentTabForRequest(r, resolvedID)h.recordActivity(r, activity.Update{TabID: resolvedID})}return ctx, resolvedID, err@@ -65,3 +87,24 @@ func (h *Handlers) recordEngine(r *http.Request, engine string) {func (h *Handlers) recordResolvedTab(r *http.Request, tabID string) {h.recordActivity(r, activity.Update{TabID: tabID})}++func (h *Handlers) setCurrentTabForRequest(r *http.Request, tabID string) {+ if h == nil || h.CurrentTabs == nil {+ return+ }+ h.CurrentTabs.Set(currentTabScopeFromRequest(r), tabID)+}++func (h *Handlers) clearCurrentTabReferences(tabID string) {+ if h == nil || h.CurrentTabs == nil {+ return+ }+ h.CurrentTabs.ClearTab(tabID)+}++func (h *Handlers) scopedCurrentTabForRequest(r *http.Request) (string, bool) {+ if h == nil || h.CurrentTabs == nil {+ return "", false+ }+ return h.CurrentTabs.Get(currentTabScopeFromRequest(r))+}diff --git a/internal/handlers/console.go b/internal/handlers/console.goindex d42f7894..1e4bd2ff 100644--- a/internal/handlers/console.go+++ b/internal/handlers/console.go@@ -2,7 +2,6 @@ package handlersimport ("context"- "fmt""net/http""strconv"@@ -16,17 +15,17 @@ const maxLogLimit = 1000func (h *Handlers) resolveConsoleTab(w http.ResponseWriter, r *http.Request) (context.Context, string, bool) {tabID := r.URL.Query().Get("tabId")if tabID == "" {- ctx, resolvedID, err := h.Bridge.TabContext("")+ ctx, resolvedID, err := h.tabContext(r, "")if err != nil {- httpx.Error(w, http.StatusBadRequest, err)+ WriteTabContextError(w, err, http.StatusBadRequest)return nil, "", false}return ctx, resolvedID, true}- ctx, resolvedID, err := h.Bridge.TabContext(tabID)+ ctx, resolvedID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, http.StatusNotFound, fmt.Errorf("tab not found"))+ WriteTabContextError(w, err, http.StatusNotFound)return nil, "", false}return ctx, resolvedID, truediff --git a/internal/handlers/cookies.go b/internal/handlers/cookies.goindex 5b106ead..dd0ef48b 100644--- a/internal/handlers/cookies.go+++ b/internal/handlers/cookies.go@@ -25,7 +25,7 @@ func (h *Handlers) HandleGetCookies(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {@@ -147,7 +147,7 @@ func (h *Handlers) HandleSetCookies(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {diff --git a/internal/handlers/current_tab.go b/internal/handlers/current_tab.gonew file mode 100644index 00000000..fad74870--- /dev/null+++ b/internal/handlers/current_tab.go@@ -0,0 +1,193 @@+package handlers++import (+ "fmt"+ "net/http"+ "strings"+ "sync"+ "time"++ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/session"+)++const (+ currentTabScopeGlobal = "global"+ currentTabScopeSession = "session"+ currentTabScopeAgent = "agent"+)++type currentTabScope struct {+ kind string+ key string+ label string+}++func (s currentTabScope) IsGlobal() bool {+ return s.kind == currentTabScopeGlobal+}++func (s currentTabScope) Description() string {+ if s.label != "" {+ return s.label+ }+ return "global"+}++// defaultCurrentTabCap caps the number of session/agent → tab entries+// the instance keeps in memory. When new entries push past the cap, the+// least-recently-touched one is evicted. The cap exists because we no+// longer push session-revoke notices over the wire — entries for dead+// sessions accumulate until pushed out by normal traffic, and the cap+// keeps that bounded.+const defaultCurrentTabCap = 5000++// currentTabEntry holds a tab id plus a per-entry timestamp used as the+// LRU recency signal. lastTouched is updated on Get, Set, and any access+// that proves the entry is still in active use.+type currentTabEntry struct {+ tabID string+ lastTouched time.Time+}++// CurrentTabStore tracks server-side current-tab pointers for identified+// automation callers. The anonymous/global current tab remains owned by the+// bridge's existing current-tab behavior for backward compatibility.+type CurrentTabStore struct {+ mu sync.RWMutex+ entries map[string]currentTabEntry+ cap int+ now func() time.Time+}++func NewCurrentTabStore() *CurrentTabStore {+ return &CurrentTabStore{+ entries: make(map[string]currentTabEntry),+ cap: defaultCurrentTabCap,+ now: time.Now,+ }+}++// SetCap overrides the eviction cap (mainly for tests). A cap of 0 or+// less leaves the existing cap unchanged.+func (s *CurrentTabStore) SetCap(n int) {+ if s == nil || n <= 0 {+ return+ }+ s.mu.Lock()+ s.cap = n+ s.evictExcessLocked()+ s.mu.Unlock()+}++func (s *CurrentTabStore) Get(scope currentTabScope) (string, bool) {+ if s == nil || scope.IsGlobal() || scope.key == "" {+ return "", false+ }+ s.mu.Lock()+ entry, ok := s.entries[scope.key]+ if !ok || entry.tabID == "" {+ s.mu.Unlock()+ return "", false+ }+ entry.lastTouched = s.now()+ s.entries[scope.key] = entry+ s.mu.Unlock()+ return entry.tabID, true+}++func (s *CurrentTabStore) Set(scope currentTabScope, tabID string) {+ if s == nil || scope.IsGlobal() || scope.key == "" {+ return+ }+ tabID = strings.TrimSpace(tabID)+ if tabID == "" {+ return+ }+ s.mu.Lock()+ s.entries[scope.key] = currentTabEntry{tabID: tabID, lastTouched: s.now()}+ s.evictExcessLocked()+ s.mu.Unlock()+}++// evictExcessLocked drops least-recently-touched entries until the map+// fits within s.cap. Caller must hold s.mu (write).+func (s *CurrentTabStore) evictExcessLocked() {+ if s.cap <= 0 || len(s.entries) <= s.cap {+ return+ }+ // Single-pass scan to find the oldest entry, drop, repeat. Cheap+ // because evictions are rare (only fire on Set when at the cap).+ for len(s.entries) > s.cap {+ var (+ oldestKey string+ oldestAt time.Time+ first = true+ )+ for k, e := range s.entries {+ if first || e.lastTouched.Before(oldestAt) {+ oldestKey = k+ oldestAt = e.lastTouched+ first = false+ }+ }+ delete(s.entries, oldestKey)+ }+}++func (s *CurrentTabStore) Clear(scope currentTabScope) {+ if s == nil || scope.IsGlobal() || scope.key == "" {+ return+ }+ s.mu.Lock()+ delete(s.entries, scope.key)+ s.mu.Unlock()+}++func (s *CurrentTabStore) ClearTab(tabID string) {+ if s == nil {+ return+ }+ tabID = strings.TrimSpace(tabID)+ if tabID == "" {+ return+ }+ s.mu.Lock()+ for key, entry := range s.entries {+ if entry.tabID == tabID {+ delete(s.entries, key)+ }+ }+ s.mu.Unlock()+}++func currentTabScopeFromRequest(r *http.Request) currentTabScope {+ if sess, ok := session.FromRequest(r); ok && sess != nil {+ if id := strings.TrimSpace(sess.ID); id != "" {+ return scopedCurrentTab(currentTabScopeSession, id)+ }+ }+ if r != nil {+ // X-PinchTab-Session-Id is internal metadata; honor it only on+ // trusted-internal-proxy hops (orchestrator → instance) where the+ // strip middleware preserved the header. Public requests have it+ // stripped at ingress, but defense in depth.+ if IsTrustedInternalProxy(r) {+ if id := strings.TrimSpace(r.Header.Get(activity.HeaderPTSessionID)); id != "" {+ return scopedCurrentTab(currentTabScopeSession, id)+ }+ }+ if id := strings.TrimSpace(r.Header.Get(activity.HeaderAgentID)); id != "" {+ return scopedCurrentTab(currentTabScopeAgent, id)+ }+ }+ return currentTabScope{kind: currentTabScopeGlobal, key: currentTabScopeGlobal, label: "global"}+}++func scopedCurrentTab(kind, id string) currentTabScope {+ return currentTabScope{+ kind: kind,+ key: kind + ":" + id,+ label: fmt.Sprintf("%s %q", kind, id),+ }+}diff --git a/internal/handlers/current_tab_test.go b/internal/handlers/current_tab_test.gonew file mode 100644index 00000000..874e62f5--- /dev/null+++ b/internal/handlers/current_tab_test.go@@ -0,0 +1,288 @@+package handlers++import (+ "bytes"+ "context"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/chromedp/cdproto/target"+ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/session"+)++type scopedCurrentTabBridge struct {+ bridge.BridgeAPI+ tabs map[string]context.Context+ requested []string+ created []string+ closed []string+ globalTab string+ ensureCall int+}++func newScopedCurrentTabBridge() *scopedCurrentTabBridge {+ return &scopedCurrentTabBridge{+ tabs: map[string]context.Context{+ "global": context.Background(),+ "tab-agent": context.Background(),+ "tab-session": context.Background(),+ "tab-explicit": context.Background(),+ },+ globalTab: "global",+ }+}++func (b *scopedCurrentTabBridge) TabContext(tabID string) (context.Context, string, error) {+ if tabID == "" {+ tabID = b.globalTab+ }+ b.requested = append(b.requested, tabID)+ ctx, ok := b.tabs[tabID]+ if !ok {+ return nil, "", fmt.Errorf("tab not found")+ }+ return ctx, tabID, nil+}++func (b *scopedCurrentTabBridge) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {+ b.created = append(b.created, url)+ tabID := fmt.Sprintf("tab-created-%d", len(b.created))+ ctx := context.Background()+ b.tabs[tabID] = ctx+ return tabID, ctx, func() {}, nil+}++func (b *scopedCurrentTabBridge) CloseTab(tabID string) error {+ b.closed = append(b.closed, tabID)+ delete(b.tabs, tabID)+ return nil+}++func (b *scopedCurrentTabBridge) FocusTab(tabID string) error {+ if _, ok := b.tabs[tabID]; !ok {+ return fmt.Errorf("tab not found")+ }+ return nil+}++func (b *scopedCurrentTabBridge) EnsureChrome(*config.RuntimeConfig) error {+ b.ensureCall+++ return nil+}++func (b *scopedCurrentTabBridge) RestartBrowser(*config.RuntimeConfig) error { return nil }++func (b *scopedCurrentTabBridge) ListTargets() ([]*target.Info, error) {+ return []*target.Info{+ {TargetID: target.ID("global"), Type: "page"},+ {TargetID: target.ID("tab-agent"), Type: "page"},+ {TargetID: target.ID("tab-session"), Type: "page"},+ {TargetID: target.ID("tab-explicit"), Type: "page"},+ }, nil+}++func (b *scopedCurrentTabBridge) AvailableActions() []string { return nil }+func (b *scopedCurrentTabBridge) TabLockInfo(string) *bridge.LockInfo { return nil }+func (b *scopedCurrentTabBridge) DeleteRefCache(string) {}+func (b *scopedCurrentTabBridge) NetworkMonitor() *bridge.NetworkMonitor { return nil }++func newScopedCurrentTabHandler() (*Handlers, *scopedCurrentTabBridge) {+ b := newScopedCurrentTabBridge()+ return New(b, &config.RuntimeConfig{}, nil, nil, nil), b+}++func TestScopedCurrentTabSessionBeatsAgentID(t *testing.T) {+ h, _ := newScopedCurrentTabHandler()++ agentReq := httptest.NewRequest("GET", "/text", nil)+ agentReq.Header.Set(activity.HeaderAgentID, "agent-1")+ h.setCurrentTabForRequest(agentReq, "tab-agent")++ sessionReq := httptest.NewRequest("GET", "/text", nil)+ sessionReq.Header.Set(activity.HeaderAgentID, "agent-1")+ sessionReq = session.WithSession(sessionReq, &session.Session{ID: "ses_1", AgentID: "agent-1"})+ h.setCurrentTabForRequest(sessionReq, "tab-session")++ _, got, err := h.tabContext(sessionReq, "")+ if err != nil {+ t.Fatalf("session tabContext error = %v", err)+ }+ if got != "tab-session" {+ t.Fatalf("session scoped tab = %q, want tab-session", got)+ }++ _, got, err = h.tabContext(agentReq, "")+ if err != nil {+ t.Fatalf("agent tabContext error = %v", err)+ }+ if got != "tab-agent" {+ t.Fatalf("agent scoped tab = %q, want tab-agent", got)+ }+}++func TestScopedCurrentTabDoesNotFallBackToGlobal(t *testing.T) {+ h, b := newScopedCurrentTabHandler()++ req := httptest.NewRequest("GET", "/text", nil)+ req.Header.Set(activity.HeaderAgentID, "agent-without-current")++ if _, _, err := h.tabContext(req, ""); err == nil {+ t.Fatal("expected missing scoped current tab to fail")+ }+ if len(b.requested) != 0 {+ t.Fatalf("bridge should not be asked for global tab, got requests %v", b.requested)+ }+}++// trustedSessionRequest builds a request that mimics a trusted-internal-proxy+// hop carrying a session id header. Public callers cannot fabricate this;+// the marker is set on the orchestrator → instance hop after auth.+func trustedSessionRequest(method, path, sessionID string, body []byte) *http.Request {+ var req *http.Request+ if body != nil {+ req = httptest.NewRequest(method, path, bytes.NewReader(body))+ } else {+ req = httptest.NewRequest(method, path, nil)+ }+ req.Header.Set(activity.HeaderPTSessionID, sessionID)+ return req.WithContext(MarkTrustedInternalProxy(req.Context()))+}++func TestExplicitTabUpdatesScopedCurrentTab(t *testing.T) {+ h, _ := newScopedCurrentTabHandler()++ req := trustedSessionRequest("GET", "/text", "ses_header", nil)++ if _, got, err := h.tabContext(req, "tab-explicit"); err != nil || got != "tab-explicit" {+ t.Fatalf("explicit tabContext = %q, %v; want tab-explicit, nil", got, err)+ }++ if _, got, err := h.tabContext(req, ""); err != nil || got != "tab-explicit" {+ t.Fatalf("scoped current after explicit = %q, %v; want tab-explicit, nil", got, err)+ }+}++func TestClearCurrentTabReferencesClearsAllScopesForTab(t *testing.T) {+ h, _ := newScopedCurrentTabHandler()++ sessionReq := trustedSessionRequest("GET", "/text", "ses_1", nil)+ agentReq := httptest.NewRequest("GET", "/text", nil)+ agentReq.Header.Set(activity.HeaderAgentID, "agent-1")++ h.setCurrentTabForRequest(sessionReq, "tab-explicit")+ h.setCurrentTabForRequest(agentReq, "tab-explicit")+ h.clearCurrentTabReferences("tab-explicit")++ if _, _, err := h.tabContext(sessionReq, ""); err == nil {+ t.Fatal("expected cleared session current tab to fail")+ }+ if _, _, err := h.tabContext(agentReq, ""); err == nil {+ t.Fatal("expected cleared agent current tab to fail")+ }+}++func TestNavigateUsesScopedCurrentTabWhenPresent(t *testing.T) {+ h, b := newScopedCurrentTabHandler()++ req := trustedSessionRequest("POST", "/navigate", "ses_1", []byte(`{"url":"about:blank"}`))+ h.setCurrentTabForRequest(req, "tab-session")++ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if len(b.created) != 0 {+ t.Fatalf("navigate should reuse scoped current tab, created tabs %v", b.created)+ }+ if len(b.requested) == 0 || b.requested[0] != "tab-session" {+ t.Fatalf("navigate requested tabs = %v, want first tab-session", b.requested)+ }+}++func TestNavigateCreatesTabWhenIdentifiedCallerHasNoCurrentTab(t *testing.T) {+ h, b := newScopedCurrentTabHandler()++ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`{"url":"about:blank"}`)))+ req.Header.Set(activity.HeaderAgentID, "agent-without-current")++ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if len(b.created) != 1 {+ t.Fatalf("navigate should create a tab when scoped current is absent, created %v", b.created)+ }+}++func TestCurrentTabStore_LRUCapEvictsOldest(t *testing.T) {+ store := NewCurrentTabStore()+ store.SetCap(2)++ scopes := []currentTabScope{+ scopedCurrentTab(currentTabScopeAgent, "a"),+ scopedCurrentTab(currentTabScopeAgent, "b"),+ scopedCurrentTab(currentTabScopeAgent, "c"),+ }+ for i, sc := range scopes {+ store.Set(sc, fmt.Sprintf("tab-%d", i))+ }++ // First entry must be evicted; last two survive.+ if _, ok := store.Get(scopes[0]); ok {+ t.Fatal("oldest entry should have been evicted by LRU cap")+ }+ if _, ok := store.Get(scopes[1]); !ok {+ t.Fatal("middle entry should remain")+ }+ if _, ok := store.Get(scopes[2]); !ok {+ t.Fatal("newest entry should remain")+ }+}++func TestCurrentTabStore_GetBumpsRecency(t *testing.T) {+ store := NewCurrentTabStore()+ store.SetCap(2)++ a := scopedCurrentTab(currentTabScopeAgent, "a")+ b := scopedCurrentTab(currentTabScopeAgent, "b")+ c := scopedCurrentTab(currentTabScopeAgent, "c")++ store.Set(a, "tab-a")+ store.Set(b, "tab-b")+ // Touch 'a' so it's now the most recently used; b is the LRU.+ if _, ok := store.Get(a); !ok {+ t.Fatal("a should still be present")+ }+ store.Set(c, "tab-c") // forces eviction of LRU = b++ if _, ok := store.Get(b); ok {+ t.Fatal("b should have been evicted, not a")+ }+ if _, ok := store.Get(a); !ok {+ t.Fatal("a should have survived because Get bumped recency")+ }+ if _, ok := store.Get(c); !ok {+ t.Fatal("c should be present")+ }+}++// TestUntrustedSessionHeaderIgnored guards the spoof case: a public client+// who manages to set X-PinchTab-Session-Id without the trusted-internal+// marker must NOT have the header honored as identity.+func TestUntrustedSessionHeaderIgnored(t *testing.T) {+ h, _ := newScopedCurrentTabHandler()++ trusted := trustedSessionRequest("GET", "/text", "ses_owner", nil)+ h.setCurrentTabForRequest(trusted, "tab-explicit")++ // Untrusted request claims the same session id but lacks the marker.+ spoofed := httptest.NewRequest("GET", "/text", nil)+ spoofed.Header.Set(activity.HeaderPTSessionID, "ses_owner")++ if got, ok := h.scopedCurrentTabForRequest(spoofed); ok {+ t.Fatalf("untrusted header must not resolve to %q", got)+ }+}diff --git a/internal/handlers/dialog.go b/internal/handlers/dialog.goindex 97f32c71..34166266 100644--- a/internal/handlers/dialog.go+++ b/internal/handlers/dialog.go@@ -36,9 +36,9 @@ func (h *Handlers) HandleDialog(w http.ResponseWriter, r *http.Request) {return}- ctx, resolvedID, err := h.Bridge.TabContext(req.TabID)+ ctx, resolvedID, err := h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}diff --git a/internal/handlers/download.go b/internal/handlers/download.goindex fe52efd1..dd8200d3 100644--- a/internal/handlers/download.go+++ b/internal/handlers/download.go@@ -57,7 +57,7 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {if tabID != "" {ctx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}owner := resolveOwner(r, "")@@ -373,8 +373,8 @@ func (h *Handlers) HandleTabDownload(w http.ResponseWriter, r *http.Request) {httpx.Error(w, 400, fmt.Errorf("tab id required"))return}- if _, _, err := h.Bridge.TabContext(tabID); err != nil {- httpx.Error(w, 404, err)+ if _, _, err := h.tabContext(r, tabID); err != nil {+ WriteTabContextError(w, err, 404)return}diff --git a/internal/handlers/empty_pointer_policy.go b/internal/handlers/empty_pointer_policy.gonew file mode 100644index 00000000..c5cac5ec--- /dev/null+++ b/internal/handlers/empty_pointer_policy.go@@ -0,0 +1,62 @@+package handlers++import (+ "errors"+ "fmt"+ "net/http"++ "github.com/pinchtab/pinchtab/internal/httpx"+)++// EmptyPointerPolicy controls behavior when an identified caller omits+// `tabId` and has no stored scoped current tab. Configured server-side at+// startup; not exposed as a per-request header.+type EmptyPointerPolicy string++const (+ // EmptyPointerLazy is the default. Read-only requests return+ // 409 no_current_tab; POST /navigate creates a new tab and stores it+ // as the caller's current tab.+ EmptyPointerLazy EmptyPointerPolicy = "lazy"++ // EmptyPointerStrict treats every unscoped identified request as an+ // error, including POST /navigate. Callers must pin a tab explicitly.+ EmptyPointerStrict EmptyPointerPolicy = "strict"+)++// ErrNoCurrentTab signals that an identified caller asked an unscoped+// handler to operate on the current tab, but no current tab is stored for+// the caller's scope. Handlers map this to 409 with code `no_current_tab`.+var ErrNoCurrentTab = errors.New("no current tab")++// noCurrentTabError wraps ErrNoCurrentTab with a scope description so the+// resulting message is useful while still matching errors.Is(err, ErrNoCurrentTab).+func noCurrentTabError(scope string) error {+ if scope == "" {+ return ErrNoCurrentTab+ }+ return fmt.Errorf("%w for %s", ErrNoCurrentTab, scope)+}++// IsNoCurrentTab reports whether err signals an empty scoped current tab.+func IsNoCurrentTab(err error) bool {+ return errors.Is(err, ErrNoCurrentTab)+}++// WriteTabContextError maps tabContext errors to the right HTTP response.+// ErrNoCurrentTab → 409 with code "no_current_tab"; everything else falls+// back to notFoundStatus (or 404 when zero) for the historical+// tab-not-found behavior.+func WriteTabContextError(w http.ResponseWriter, err error, notFoundStatus int) {+ if err == nil {+ return+ }+ if IsNoCurrentTab(err) {+ httpx.ErrorCode(w, http.StatusConflict, "no_current_tab", err.Error(), false, nil)+ return+ }+ if notFoundStatus == 0 {+ notFoundStatus = http.StatusNotFound+ }+ httpx.Error(w, notFoundStatus, err)+}diff --git a/internal/handlers/empty_pointer_policy_test.go b/internal/handlers/empty_pointer_policy_test.gonew file mode 100644index 00000000..9d2d91f8--- /dev/null+++ b/internal/handlers/empty_pointer_policy_test.go@@ -0,0 +1,153 @@+package handlers++import (+ "bytes"+ "errors"+ "fmt"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/pinchtab/pinchtab/internal/activity"+)++func TestIsNoCurrentTab(t *testing.T) {+ if !IsNoCurrentTab(ErrNoCurrentTab) {+ t.Fatal("ErrNoCurrentTab itself should match")+ }+ wrapped := fmt.Errorf("ctx: %w", ErrNoCurrentTab)+ if !IsNoCurrentTab(wrapped) {+ t.Fatal("wrapped ErrNoCurrentTab should match")+ }+ if IsNoCurrentTab(errors.New("unrelated")) {+ t.Fatal("unrelated error should not match")+ }+ if IsNoCurrentTab(nil) {+ t.Fatal("nil should not match")+ }+}++func TestWriteTabContextError_NoCurrentTabIs409(t *testing.T) {+ w := httptest.NewRecorder()+ WriteTabContextError(w, noCurrentTabError(`session "ses_1"`), 0)++ if w.Code != http.StatusConflict {+ t.Fatalf("status = %d, want 409", w.Code)+ }+ if got := w.Body.String(); got == "" || !bytes.Contains([]byte(got), []byte(`"no_current_tab"`)) {+ t.Fatalf("body should include code no_current_tab, got %q", got)+ }+}++func TestWriteTabContextError_OtherErrorsUseFallbackStatus(t *testing.T) {+ w := httptest.NewRecorder()+ WriteTabContextError(w, errors.New("tab not found"), http.StatusBadRequest)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400", w.Code)+ }+}++func TestWriteTabContextError_DefaultsTo404WhenZero(t *testing.T) {+ w := httptest.NewRecorder()+ WriteTabContextError(w, errors.New("oops"), 0)+ if w.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want 404", w.Code)+ }+}++func TestWriteTabContextError_NilNoOp(t *testing.T) {+ w := httptest.NewRecorder()+ WriteTabContextError(w, nil, 0)+ if w.Code != http.StatusOK {+ t.Fatalf("nil err should not write a response; got status %d", w.Code)+ }+}++func TestTabContext_NoCurrentTabReturnsSentinel(t *testing.T) {+ h, _ := newScopedCurrentTabHandler()++ req := trustedSessionRequest("GET", "/text", "ses_orphan", nil)+ _, _, err := h.tabContext(req, "")+ if !IsNoCurrentTab(err) {+ t.Fatalf("expected ErrNoCurrentTab, got %v", err)+ }+}++func TestTabContext_StalePointerReturnsSentinelAndClears(t *testing.T) {+ h, _ := newScopedCurrentTabHandler()++ // Seed a pointer to a tab the bridge mock does not know about.+ req := trustedSessionRequest("GET", "/text", "ses_2", nil)+ h.CurrentTabs.Set(currentTabScopeFromRequest(req), "tab-does-not-exist")++ _, _, err := h.tabContext(req, "")+ if !IsNoCurrentTab(err) {+ t.Fatalf("stale pointer should produce ErrNoCurrentTab, got %v", err)+ }+ // Pointer should have been cleared.+ if got, ok := h.CurrentTabs.Get(currentTabScopeFromRequest(req)); ok {+ t.Fatalf("pointer should be cleared, still %q", got)+ }+}++func TestNavigateStrict_RejectsIdentifiedCallerWithoutScopedTab(t *testing.T) {+ h, b := newScopedCurrentTabHandler()+ h.SetEmptyPointerPolicy(EmptyPointerStrict)++ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`{"url":"about:blank"}`)))+ req.Header.Set(activity.HeaderAgentID, "agent-strict")++ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code != http.StatusConflict {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+ if !bytes.Contains(w.Body.Bytes(), []byte(`"no_current_tab"`)) {+ t.Fatalf("body should include code no_current_tab, got %s", w.Body.String())+ }+ if len(b.created) != 0 {+ t.Fatalf("strict mode must not create a tab, created %v", b.created)+ }+}++func TestNavigateStrict_PassesAnonymousCallersThrough(t *testing.T) {+ h, b := newScopedCurrentTabHandler()+ h.SetEmptyPointerPolicy(EmptyPointerStrict)++ // Anonymous (no agent / session) — strict policy applies only to+ // identified callers; the bridge mock cannot complete a real navigate+ // so we ignore the eventual error and just check CreateTab was called.+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`{"url":"about:blank"}`)))++ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code == http.StatusConflict {+ t.Fatalf("anonymous request must not be rejected by strict policy; got 409 %s", w.Body.String())+ }+ if len(b.created) != 1 {+ t.Fatalf("anonymous strict should still create a tab, created %v", b.created)+ }+}++func TestNavigateLazy_IdentifiedCallerStillCreatesTab(t *testing.T) {+ h, b := newScopedCurrentTabHandler()+ if h.EmptyPointerPolicy() != EmptyPointerLazy {+ t.Fatalf("default policy = %q, want lazy", h.EmptyPointerPolicy())+ }++ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`{"url":"about:blank"}`)))+ req.Header.Set(activity.HeaderAgentID, "agent-lazy")++ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code == http.StatusConflict {+ t.Fatalf("lazy mode must not return 409; got %s", w.Body.String())+ }+ if len(b.created) != 1 {+ t.Fatalf("lazy identified should create a tab, created %v", b.created)+ }+}diff --git a/internal/handlers/evaluate.go b/internal/handlers/evaluate.goindex 40bef0d2..d24c8654 100644--- a/internal/handlers/evaluate.go+++ b/internal/handlers/evaluate.go@@ -48,7 +48,7 @@ func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {diff --git a/internal/handlers/find.go b/internal/handlers/find.goindex dea04fe6..708919f8 100644--- a/internal/handlers/find.go+++ b/internal/handlers/find.go@@ -89,7 +89,7 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {// Keep ctxTab so we can reuse it for CDP operations (e.g. auto-refresh).ctxTab, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctxTab, resolvedTabID); !ok {diff --git a/internal/handlers/frame.go b/internal/handlers/frame.goindex 71ec7ad5..868e4de5 100644--- a/internal/handlers/frame.go+++ b/internal/handlers/frame.go@@ -351,7 +351,7 @@ func (h *Handlers) HandleFrame(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex 30a56a3c..37b992a0 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -33,9 +33,14 @@ type Handlers struct {Recovery *recovery.RecoveryEngineRouter *engine.Router // optional; nil ⇒ chrome-onlyIDPIGuard idpi.Guard+ CurrentTabs *CurrentTabStoreVersion string // build version injected at startupclipboard clipboardStore+ // emptyPointerPolicy controls behavior when an identified caller omits+ // tabId and has no stored scoped current tab. See EmptyPointerPolicy.+ emptyPointerPolicy EmptyPointerPolicy+// Optional dependency injection (for unit testing)evalJS func(ctx context.Context, expression string, out *string) errorautoSolverRunner func(ctx context.Context, tabID string) error@@ -56,6 +61,7 @@ func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService,Matcher: matcher,IntentCache: intentCache,IDPIGuard: idpi.NewGuard(cfg.IDPI, cfg.AllowedDomains),+ CurrentTabs: NewCurrentTabStore(),}// Wire up the recovery engine with callbacks that delegate back to@@ -100,6 +106,27 @@ func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService,return h}+// SetEmptyPointerPolicy configures behavior when an identified caller+// omits tabId and has no stored scoped current tab. Default is lazy.+func (h *Handlers) SetEmptyPointerPolicy(p EmptyPointerPolicy) {+ if h == nil {+ return+ }+ if p == "" {+ p = EmptyPointerLazy+ }+ h.emptyPointerPolicy = p+}++// EmptyPointerPolicy returns the active empty-pointer policy. Defaults to+// lazy when not configured.+func (h *Handlers) EmptyPointerPolicy() EmptyPointerPolicy {+ if h == nil || h.emptyPointerPolicy == "" {+ return EmptyPointerLazy+ }+ return h.emptyPointerPolicy+}+type restartStatusProvider interface {RestartStatus() (bool, time.Duration)}diff --git a/internal/handlers/handoff.go b/internal/handlers/handoff.goindex 7a29edc5..49fdc5d1 100644--- a/internal/handlers/handoff.go+++ b/internal/handlers/handoff.go@@ -101,7 +101,7 @@ func (h *Handlers) HandleTabHandoff(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}owner := resolveOwner(r, "")@@ -161,7 +161,7 @@ func (h *Handlers) HandleTabResume(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}owner := resolveOwner(r, "")@@ -213,7 +213,7 @@ func (h *Handlers) HandleTabHandoffStatus(w http.ResponseWriter, r *http.Request_, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}diff --git a/internal/handlers/health_tabs.go b/internal/handlers/health_tabs.goindex fef03bc5..1ff2765d 100644--- a/internal/handlers/health_tabs.go+++ b/internal/handlers/health_tabs.go@@ -132,8 +132,8 @@ func (h *Handlers) HandleTabMetrics(w http.ResponseWriter, r *http.Request) {return}- if _, _, err := h.Bridge.TabContext(tabID); err != nil {- httpx.Error(w, http.StatusNotFound, fmt.Errorf("tab not found"))+ if _, _, err := h.tabContext(r, tabID); err != nil {+ WriteTabContextError(w, err, http.StatusNotFound)return}@@ -169,7 +169,7 @@ func (h *Handlers) HandleTabs(w http.ResponseWriter, r *http.Request) {}currentTabID := ""- if _, resolvedID, err := h.Bridge.TabContext(""); err == nil {+ if _, resolvedID, err := h.tabContext(r, ""); err == nil {currentTabID = resolvedID}diff --git a/internal/handlers/history.go b/internal/handlers/history.goindex 4617270b..860c72ee 100644--- a/internal/handlers/history.go+++ b/internal/handlers/history.go@@ -41,9 +41,9 @@ func (h *Handlers) HandleBack(w http.ResponseWriter, r *http.Request) {return}tabID := r.URL.Query().Get("tabId")- ctx, resolvedID, err := h.Bridge.TabContext(tabID)+ ctx, resolvedID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}@@ -79,9 +79,9 @@ func (h *Handlers) HandleForward(w http.ResponseWriter, r *http.Request) {return}tabID := r.URL.Query().Get("tabId")- ctx, resolvedID, err := h.Bridge.TabContext(tabID)+ ctx, resolvedID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}@@ -115,9 +115,9 @@ func (h *Handlers) HandleReload(w http.ResponseWriter, r *http.Request) {return}tabID := r.URL.Query().Get("tabId")- ctx, resolvedID, err := h.Bridge.TabContext(tabID)+ ctx, resolvedID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}diff --git a/internal/handlers/inspect.go b/internal/handlers/inspect.goindex ed8bc5c5..1cc284e9 100644--- a/internal/handlers/inspect.go+++ b/internal/handlers/inspect.go@@ -86,7 +86,7 @@ func (h *Handlers) handleInspect(w http.ResponseWriter, r *http.Request, kind inctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.goindex 864ff429..d4cc3212 100644--- a/internal/handlers/middleware.go+++ b/internal/handlers/middleware.go@@ -168,6 +168,21 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *browsersess})}+// StripInternalHeadersMiddleware removes any X-PinchTab-* headers that arrived+// from the public network. These headers are reserved for trusted internal+// propagation (orchestrator → instance) after auth, and accepting them from+// public clients would let a bearer-authenticated caller spoof another+// session's identity.+//+// Mount as the outermost middleware on every public-facing server. Trusted+// internal hops re-add the headers after the strip layer.+func StripInternalHeadersMiddleware(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ stripPinchtabHeaders(r.Header)+ next.ServeHTTP(w, r)+ })+}+func RequestIDMiddleware(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {rid := r.Header.Get("X-Request-Id")diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.goindex c6d58a64..69ee158d 100644--- a/internal/handlers/middleware_test.go+++ b/internal/handlers/middleware_test.go@@ -828,6 +828,122 @@ func TestLoggingMiddleware_RecordsFailure(t *testing.T) {}}+func TestStripInternalHeadersMiddleware_RemovesPinchtabHeaders(t *testing.T) {+ var seen http.Header+ handler := StripInternalHeadersMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ seen = r.Header.Clone()+ w.WriteHeader(200)+ }))++ req := httptest.NewRequest("GET", "/test", nil)+ req.Header.Set("X-PinchTab-Session-Id", "spoofed")+ req.Header.Set("X-PinchTab-Tab-Id", "tab-spoof")+ req.Header.Set("x-pinchtab-source", "evil")+ req.Header.Set("Authorization", "Session abc")+ req.Header.Set("X-Other", "keep-me")++ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ for _, h := range []string{"X-PinchTab-Session-Id", "X-PinchTab-Tab-Id", "X-Pinchtab-Source"} {+ if seen.Get(h) != "" {+ t.Fatalf("expected %s to be stripped, got %q", h, seen.Get(h))+ }+ }+ if seen.Get("Authorization") != "Session abc" {+ t.Fatal("Authorization should be preserved")+ }+ if seen.Get("X-Other") != "keep-me" {+ t.Fatal("non-pinchtab headers should be preserved")+ }+}++func TestTrustedInternalProxyStripMiddleware_ValidTokenMarksContextAndPreservesHeaders(t *testing.T) {+ const secret = "shared-internal-secret"+ var (+ seenSession string+ seenTrusted bool+ seenToken string+ )+ mw := TrustedInternalProxyStripMiddleware(secret)+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ seenSession = r.Header.Get("X-PinchTab-Session-Id")+ seenTrusted = IsTrustedInternalProxy(r)+ seenToken = r.Header.Get(InternalTokenHeader)+ w.WriteHeader(200)+ }))++ req := httptest.NewRequest("GET", "/x", nil)+ req.Header.Set(InternalTokenHeader, secret)+ req.Header.Set("X-PinchTab-Session-Id", "ses_propagated")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if !seenTrusted {+ t.Fatal("expected request to be marked trusted-internal-proxy")+ }+ if seenSession != "ses_propagated" {+ t.Fatalf("session header = %q, want ses_propagated", seenSession)+ }+ if seenToken != "" {+ t.Fatalf("internal token header should be removed, got %q", seenToken)+ }+}++func TestTrustedInternalProxyStripMiddleware_BadTokenStripsHeaders(t *testing.T) {+ var (+ seenSession string+ seenTrusted bool+ )+ mw := TrustedInternalProxyStripMiddleware("expected-secret")+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ seenSession = r.Header.Get("X-PinchTab-Session-Id")+ seenTrusted = IsTrustedInternalProxy(r)+ w.WriteHeader(200)+ }))++ req := httptest.NewRequest("GET", "/x", nil)+ req.Header.Set(InternalTokenHeader, "wrong-secret")+ req.Header.Set("X-PinchTab-Session-Id", "spoofed")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if seenTrusted {+ t.Fatal("expected untrusted request not to be marked")+ }+ if seenSession != "" {+ t.Fatalf("session header should be stripped, got %q", seenSession)+ }+}++func TestTrustedInternalProxyStripMiddleware_EmptySecretAlwaysStrips(t *testing.T) {+ var (+ seenSession string+ seenTrusted bool+ )+ mw := TrustedInternalProxyStripMiddleware("")+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ seenSession = r.Header.Get("X-PinchTab-Session-Id")+ seenTrusted = IsTrustedInternalProxy(r)+ w.WriteHeader(200)+ }))++ // Even when the request looks like it has the right header, an empty+ // configured secret means trust verification is disabled — always strip.+ req := httptest.NewRequest("GET", "/x", nil)+ req.Header.Set(InternalTokenHeader, "anything")+ req.Header.Set("X-PinchTab-Session-Id", "spoofed")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)++ if seenTrusted {+ t.Fatal("empty secret must never mark trusted")+ }+ if seenSession != "" {+ t.Fatal("empty secret must still strip pinchtab headers")+ }+}+func TestRequestIDMiddleware_SetsHeader(t *testing.T) {handler := RequestIDMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(200)diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.goindex 5d987d6c..ae3cbc80 100644--- a/internal/handlers/navigation.go+++ b/internal/handlers/navigation.go@@ -7,6 +7,7 @@ import ("errors""fmt""io"+ "net""net/http""net/netip""strconv"@@ -147,8 +148,26 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {return}+ explicitTabID := strings.TrimSpace(req.TabID) != ""+ scopedCurrentForNavigate := false+ identifiedCaller := !currentTabScopeFromRequest(r).IsGlobal()+ if !explicitTabID && !req.NewTab {+ if scopedTabID, ok := h.scopedCurrentTabForRequest(r); ok {+ req.TabID = scopedTabID+ scopedCurrentForNavigate = true+ } else if identifiedCaller && h.EmptyPointerPolicy() == EmptyPointerStrict {+ // Strict empty-pointer policy: identified callers must pin a+ // tab explicitly. Refuse to lazily create one.+ httpx.ErrorCode(w, http.StatusConflict, "no_current_tab",+ "no current tab; explicit tabId required under strict empty-pointer policy",+ false, nil)+ return+ }+ }+// Default to creating new tab (API design: /navigate always creates new tab)- // Unless explicitly reusing an existing tab by specifying TabID+ // unless explicitly reusing an existing tab, or an identified caller has a+ // scoped current tab.if req.TabID == "" {req.NewTab = true}@@ -197,65 +216,35 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {}if req.NewTab {- // Create a blank tab first so the requested URL becomes the first- // real history entry.- newTabID, newCtx, _, err := h.Bridge.CreateTab("")- if err != nil {- httpx.Error(w, 500, fmt.Errorf("new tab: %w", err))- return- }-- tCtx, tCancel := context.WithTimeout(newCtx, navTimeout)- defer tCancel()- go httpx.CancelOnClientDone(r.Context(), tCancel)- navGuard, err := installNavigateRuntimeGuard(tCtx, tCancel, target, trustedCIDRs)- if err != nil {- httpx.Error(w, 500, fmt.Errorf("navigation guard: %w", err))- return- }-- if len(blockPatterns) > 0 {- _ = bridge.SetResourceBlocking(tCtx, blockPatterns)- }-- if err := bridge.NavigatePageWithRedirectLimit(tCtx, req.URL, h.Config.MaxRedirects); err != nil {- if navGuard != nil {- if blockedErr := navGuard.blocked(); blockedErr != nil {- httpx.Error(w, http.StatusForbidden, blockedErr)- return- }- }- code := 500- errMsg := err.Error()- if errors.Is(err, bridge.ErrTooManyRedirects) {- code = 422- } else if strings.Contains(errMsg, "invalid URL") || strings.Contains(errMsg, "Cannot navigate to invalid URL") || strings.Contains(errMsg, "ERR_INVALID_URL") {- code = 400- }- navigateErrorWithHint(w, code, err, req.URL)- return- }-- if err := h.waitForNavigationState(tCtx, req.WaitFor, req.WaitSelector); err != nil {- httpx.ErrorCode(w, 400, "bad_wait_for", err.Error(), false, nil)- return- }-- h.maybeAutoSolve(tCtx, newTabID, autoSolverTriggerNavigate)-- var navURL string- _ = chromedp.Run(tCtx, chromedp.Location(&navURL))- title, _ := bridge.WaitForTitle(tCtx, titleWait)- h.recordResolvedTab(r, newTabID)- h.recordResolvedURL(r, navURL)-- httpx.JSON(w, 200, map[string]any{"tabId": newTabID, "url": navURL, "title": title})+ h.navigateNewTabChrome(w, r, navigateChromeOptions{+ URL: req.URL,+ WaitFor: req.WaitFor,+ WaitSelector: req.WaitSelector,+ NavTimeout: navTimeout,+ TitleWait: titleWait,+ Target: target,+ TrustedCIDRs: trustedCIDRs,+ BlockPatterns: blockPatterns,+ })return}ctx, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ if scopedCurrentForNavigate {+ h.navigateNewTabChrome(w, r, navigateChromeOptions{+ URL: req.URL,+ WaitFor: req.WaitFor,+ WaitSelector: req.WaitSelector,+ NavTimeout: navTimeout,+ TitleWait: titleWait,+ Target: target,+ TrustedCIDRs: trustedCIDRs,+ BlockPatterns: blockPatterns,+ })+ return+ }+ WriteTabContextError(w, err, 404)return}// Navigate signals fresh work on this tab — drop any pending auto-close@@ -306,11 +295,80 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {var navURL string_ = chromedp.Run(tCtx, chromedp.Location(&navURL))title, _ := bridge.WaitForTitle(tCtx, titleWait)+ h.setCurrentTabForRequest(r, resolvedTabID)h.recordResolvedURL(r, navURL)httpx.JSON(w, 200, map[string]any{"tabId": resolvedTabID, "url": navURL, "title": title})}+type navigateChromeOptions struct {+ URL string+ WaitFor string+ WaitSelector string+ NavTimeout time.Duration+ TitleWait time.Duration+ Target *validatedNavigateTarget+ TrustedCIDRs []*net.IPNet+ BlockPatterns []string+}++func (h *Handlers) navigateNewTabChrome(w http.ResponseWriter, r *http.Request, opts navigateChromeOptions) {+ // Create a blank tab first so the requested URL becomes the first+ // real history entry.+ newTabID, newCtx, _, err := h.Bridge.CreateTab("")+ if err != nil {+ httpx.Error(w, 500, fmt.Errorf("new tab: %w", err))+ return+ }++ tCtx, tCancel := context.WithTimeout(newCtx, opts.NavTimeout)+ defer tCancel()+ go httpx.CancelOnClientDone(r.Context(), tCancel)+ navGuard, err := installNavigateRuntimeGuard(tCtx, tCancel, opts.Target, opts.TrustedCIDRs)+ if err != nil {+ httpx.Error(w, 500, fmt.Errorf("navigation guard: %w", err))+ return+ }++ if len(opts.BlockPatterns) > 0 {+ _ = bridge.SetResourceBlocking(tCtx, opts.BlockPatterns)+ }++ if err := bridge.NavigatePageWithRedirectLimit(tCtx, opts.URL, h.Config.MaxRedirects); err != nil {+ if navGuard != nil {+ if blockedErr := navGuard.blocked(); blockedErr != nil {+ httpx.Error(w, http.StatusForbidden, blockedErr)+ return+ }+ }+ code := 500+ errMsg := err.Error()+ if errors.Is(err, bridge.ErrTooManyRedirects) {+ code = 422+ } else if strings.Contains(errMsg, "invalid URL") || strings.Contains(errMsg, "Cannot navigate to invalid URL") || strings.Contains(errMsg, "ERR_INVALID_URL") {+ code = 400+ }+ navigateErrorWithHint(w, code, err, opts.URL)+ return+ }++ if err := h.waitForNavigationState(tCtx, opts.WaitFor, opts.WaitSelector); err != nil {+ httpx.ErrorCode(w, 400, "bad_wait_for", err.Error(), false, nil)+ return+ }++ h.maybeAutoSolve(tCtx, newTabID, autoSolverTriggerNavigate)++ var navURL string+ _ = chromedp.Run(tCtx, chromedp.Location(&navURL))+ title, _ := bridge.WaitForTitle(tCtx, opts.TitleWait)+ h.setCurrentTabForRequest(r, newTabID)+ h.recordResolvedTab(r, newTabID)+ h.recordResolvedURL(r, navURL)++ httpx.JSON(w, 200, map[string]any{"tabId": newTabID, "url": navURL, "title": title})+}+// HandleTabNavigate navigates an existing tab identified by path ID.//// @Endpoint POST /tabs/{id}/navigatediff --git a/internal/handlers/network.go b/internal/handlers/network.goindex d79bb153..565745bb 100644--- a/internal/handlers/network.go+++ b/internal/handlers/network.go@@ -48,7 +48,7 @@ func (h *Handlers) HandleNetwork(w http.ResponseWriter, r *http.Request) {tabID := r.URL.Query().Get("tabId")tabCtx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, tabCtx, resolvedTabID); !ok {@@ -127,7 +127,7 @@ func (h *Handlers) HandleNetworkByID(w http.ResponseWriter, r *http.Request) {tabID := r.URL.Query().Get("tabId")tabCtx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, tabCtx, resolvedTabID); !ok {@@ -188,9 +188,9 @@ func (h *Handlers) HandleNetworkClear(w http.ResponseWriter, r *http.Request) {tabID := r.URL.Query().Get("tabId")if tabID != "" {- _, resolvedTabID, err := h.Bridge.TabContext(tabID)+ _, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}nm.ClearTab(resolvedTabID)@@ -236,7 +236,7 @@ func (h *Handlers) HandleNetworkStream(w http.ResponseWriter, r *http.Request) {tabID := r.URL.Query().Get("tabId")tabCtx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, tabCtx, resolvedTabID); !ok {diff --git a/internal/handlers/network_export.go b/internal/handlers/network_export.goindex d702af13..9008e0c5 100644--- a/internal/handlers/network_export.go+++ b/internal/handlers/network_export.go@@ -83,7 +83,7 @@ func (h *Handlers) HandleNetworkExport(w http.ResponseWriter, r *http.Request) {tabID := r.URL.Query().Get("tabId")tabCtx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, tabCtx, resolvedTabID); !ok {diff --git a/internal/handlers/network_export_stream.go b/internal/handlers/network_export_stream.goindex ee2507b1..9a3a2b4b 100644--- a/internal/handlers/network_export_stream.go+++ b/internal/handlers/network_export_stream.go@@ -47,7 +47,7 @@ func (h *Handlers) HandleNetworkExportStream(w http.ResponseWriter, r *http.RequtabID := r.URL.Query().Get("tabId")tabCtx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, tabCtx, resolvedTabID); !ok {diff --git a/internal/handlers/network_route.go b/internal/handlers/network_route.goindex 1bf2efd3..cd6f71e2 100644--- a/internal/handlers/network_route.go+++ b/internal/handlers/network_route.go@@ -117,7 +117,7 @@ func (h *Handlers) requireRouteContext(w http.ResponseWriter, r *http.Request, t}ctx, id, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return nil, "", false}return ctx, id, true@@ -209,7 +209,7 @@ func (h *Handlers) handleNetworkUnrouteFor(w http.ResponseWriter, r *http.Requesremoved, err := h.Bridge.RemoveRouteRule(resolvedID, pattern)if err != nil {if errors.Is(err, bridge.ErrTabNotRouted) {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}httpx.Error(w, 500, err)diff --git a/internal/handlers/pdf.go b/internal/handlers/pdf.goindex d6c2b6cc..6616b95c 100644--- a/internal/handlers/pdf.go+++ b/internal/handlers/pdf.go@@ -72,7 +72,7 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.goindex f082d574..618ba92d 100644--- a/internal/handlers/screenshot.go+++ b/internal/handlers/screenshot.go@@ -39,7 +39,7 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex cab5cfcd..a9e55956 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -121,7 +121,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {diff --git a/internal/handlers/solver.go b/internal/handlers/solver.goindex 004f991e..72bc98cb 100644--- a/internal/handlers/solver.go+++ b/internal/handlers/solver.go@@ -76,7 +76,7 @@ func (h *Handlers) HandleSolve(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}diff --git a/internal/handlers/state.go b/internal/handlers/state.goindex 5f477b9c..4acef262 100644--- a/internal/handlers/state.go+++ b/internal/handlers/state.go@@ -116,7 +116,7 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}@@ -352,7 +352,7 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}diff --git a/internal/handlers/stealth.go b/internal/handlers/stealth.goindex ae925474..2f6528fe 100644--- a/internal/handlers/stealth.go+++ b/internal/handlers/stealth.go@@ -37,7 +37,7 @@ func (h *Handlers) HandleFingerprintRotate(w http.ResponseWriter, r *http.Requesctx, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {diff --git a/internal/handlers/storage.go b/internal/handlers/storage.goindex 47471c72..f1440a17 100644--- a/internal/handlers/storage.go+++ b/internal/handlers/storage.go@@ -60,7 +60,7 @@ func (h *Handlers) handleStorageGet(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {@@ -130,7 +130,7 @@ func (h *Handlers) handleStorageSet(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {@@ -225,7 +225,7 @@ func (h *Handlers) handleStorageDelete(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {diff --git a/internal/handlers/tab_lifecycle.go b/internal/handlers/tab_lifecycle.goindex 9e8156ab..dd0c1d62 100644--- a/internal/handlers/tab_lifecycle.go+++ b/internal/handlers/tab_lifecycle.go@@ -97,6 +97,8 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {var curURL, title string_ = chromedp.Run(ctx, chromedp.Location(&curURL), chromedp.Title(&title))+ h.setCurrentTabForRequest(r, newTabID)+ h.recordActivity(r, activity.Update{Action: "tab.new", TabID: newTabID, URL: curURL})httpx.JSON(w, 200, map[string]any{"tabId": newTabID, "url": curURL, "title": title})case "focus":@@ -108,10 +110,11 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {return}if err := h.Bridge.FocusTab(req.TabID); err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}+ h.setCurrentTabForRequest(r, req.TabID)h.recordActivity(r, activity.Update{Action: "tab.focus", TabID: req.TabID})httpx.JSON(w, 200, map[string]any{"focused": true, "tabId": req.TabID})@@ -169,7 +172,7 @@ func (h *Handlers) closeTab(w http.ResponseWriter, r *http.Request, tabID stringif tabID == "" {_, resolvedTabID, err := h.tabContext(r, "")if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}tabID = resolvedTabID@@ -180,6 +183,7 @@ func (h *Handlers) closeTab(w http.ResponseWriter, r *http.Request, tabID stringreturn}+ h.clearCurrentTabReferences(tabID)h.recordActivity(r, activity.Update{Action: "tab.close", TabID: tabID})w.Header().Set(activity.HeaderPTTabID, tabID)diff --git a/internal/handlers/text.go b/internal/handlers/text.goindex e2294547..ca7d79b9 100644--- a/internal/handlers/text.go+++ b/internal/handlers/text.go@@ -62,7 +62,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {diff --git a/internal/handlers/trust.go b/internal/handlers/trust.gonew file mode 100644index 00000000..7133db09--- /dev/null+++ b/internal/handlers/trust.go@@ -0,0 +1,73 @@+package handlers++import (+ "context"+ "crypto/subtle"+ "net/http"+ "strings"+)++// InternalTokenHeader carries the shared secret on orchestrator → instance+// proxy hops. The instance verifies it against PINCHTAB_INTERNAL_TOKEN and+// marks the request context as trusted-internal-proxy when it matches.+const InternalTokenHeader = "X-PinchTab-Internal-Token"++type trustCtxKey struct{}++// MarkTrustedInternalProxy returns a context marked as a trusted internal+// proxy hop (orchestrator → instance after auth).+func MarkTrustedInternalProxy(ctx context.Context) context.Context {+ return context.WithValue(ctx, trustCtxKey{}, true)+}++// IsTrustedInternalProxy reports whether the request was marked as a trusted+// internal proxy hop.+func IsTrustedInternalProxy(r *http.Request) bool {+ if r == nil {+ return false+ }+ v, _ := r.Context().Value(trustCtxKey{}).(bool)+ return v+}++// TrustedInternalProxyStripMiddleware combines two responsibilities for+// instance ingress:+//+// 1. If the request carries a valid internal token, mark the context as a+// trusted-internal-proxy hop. The token header is removed so it never+// reaches handlers.+// 2. Otherwise, strip every X-PinchTab-* header from the request so a+// public client cannot spoof internal metadata.+//+// Pass an empty secret to disable trust verification entirely (always+// strips). The secret is compared in constant time.+func TrustedInternalProxyStripMiddleware(secret string) func(http.Handler) http.Handler {+ secretBytes := []byte(secret)+ return func(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ trusted := false+ if len(secretBytes) > 0 {+ if got := r.Header.Get(InternalTokenHeader); got != "" &&+ subtle.ConstantTimeCompare([]byte(got), secretBytes) == 1 {+ trusted = true+ }+ }+ r.Header.Del(InternalTokenHeader)++ if trusted {+ r = r.WithContext(MarkTrustedInternalProxy(r.Context()))+ } else {+ stripPinchtabHeaders(r.Header)+ }+ next.ServeHTTP(w, r)+ })+ }+}++func stripPinchtabHeaders(h http.Header) {+ for name := range h {+ if strings.HasPrefix(http.CanonicalHeaderKey(name), "X-Pinchtab-") {+ h.Del(name)+ }+ }+}diff --git a/internal/handlers/upload.go b/internal/handlers/upload.goindex e085c5a4..fc00146d 100644--- a/internal/handlers/upload.go+++ b/internal/handlers/upload.go@@ -129,7 +129,7 @@ func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {ctx, resolvedTabID, err := h.tabContext(r, tabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}owner := resolveOwner(r, "")diff --git a/internal/handlers/wait.go b/internal/handlers/wait.goindex cbbf2b54..abcfabfa 100644--- a/internal/handlers/wait.go+++ b/internal/handlers/wait.go@@ -214,7 +214,7 @@ func (h *Handlers) handleWaitCore(w http.ResponseWriter, r *http.Request, req wa// All other modes need a browser tab.ctx, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {- httpx.Error(w, 404, err)+ WriteTabContextError(w, err, 404)return}if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {diff --git a/internal/orchestrator/bindings.go b/internal/orchestrator/bindings.gonew file mode 100644index 00000000..7733b096--- /dev/null+++ b/internal/orchestrator/bindings.go@@ -0,0 +1,182 @@+package orchestrator++import (+ "sort"+ "sync"+ "time"+)++// Bindings tracks identity → instance mappings used to route subsequent+// unscoped requests for a given session or agent to the same instance that+// served their first successful request. Bindings are written only after a+// successful proxy and validated against running instances on read.+//+// Sessions have a lifecycle (revoke / expire / prune) that the orchestrator+// hooks into via session.Store, so sessions can be evicted promptly. Agents+// have no lifecycle signal, so agent bindings are bounded by an idle TTL and+// an LRU cap to prevent unbounded growth.+type Bindings struct {+ mu sync.RWMutex+ session map[string]string // sessionID → instanceID+ agent map[string]string // agentID → instanceID+ agentSeen map[string]time.Time // agentID → last access+ now func() time.Time+}++// NewBindings returns an empty bindings table. Pass nil for `now` to use+// time.Now; tests can inject a deterministic clock.+func NewBindings(now func() time.Time) *Bindings {+ if now == nil {+ now = time.Now+ }+ return &Bindings{+ session: make(map[string]string),+ agent: make(map[string]string),+ agentSeen: make(map[string]time.Time),+ now: now,+ }+}++// ResolveSession returns the instance bound to the given session id, if any.+func (b *Bindings) ResolveSession(id string) (string, bool) {+ if b == nil || id == "" {+ return "", false+ }+ b.mu.RLock()+ defer b.mu.RUnlock()+ inst, ok := b.session[id]+ return inst, ok && inst != ""+}++// ResolveAgent returns the instance bound to the given agent id, if any,+// and bumps its idle timestamp on hit.+func (b *Bindings) ResolveAgent(id string) (string, bool) {+ if b == nil || id == "" {+ return "", false+ }+ b.mu.Lock()+ defer b.mu.Unlock()+ inst, ok := b.agent[id]+ if !ok || inst == "" {+ return "", false+ }+ b.agentSeen[id] = b.now()+ return inst, true+}++// BindSession associates a session id with an instance. Pass an empty+// instance id to no-op; pass an empty session id to no-op.+func (b *Bindings) BindSession(id, instanceID string) {+ if b == nil || id == "" || instanceID == "" {+ return+ }+ b.mu.Lock()+ b.session[id] = instanceID+ b.mu.Unlock()+}++// BindAgent associates an agent id with an instance and updates its idle+// timestamp.+func (b *Bindings) BindAgent(id, instanceID string) {+ if b == nil || id == "" || instanceID == "" {+ return+ }+ b.mu.Lock()+ b.agent[id] = instanceID+ b.agentSeen[id] = b.now()+ b.mu.Unlock()+}++// ClearSession removes a session binding. No-op if absent.+func (b *Bindings) ClearSession(id string) {+ if b == nil || id == "" {+ return+ }+ b.mu.Lock()+ delete(b.session, id)+ b.mu.Unlock()+}++// ClearAgent removes an agent binding. No-op if absent.+func (b *Bindings) ClearAgent(id string) {+ if b == nil || id == "" {+ return+ }+ b.mu.Lock()+ delete(b.agent, id)+ delete(b.agentSeen, id)+ b.mu.Unlock()+}++// ClearInstance removes every binding pointing at the given instance.+// Called from the orchestrator's instance-stopped/error handler so a+// crashed or restarted instance does not keep receiving routed traffic.+func (b *Bindings) ClearInstance(instanceID string) {+ if b == nil || instanceID == "" {+ return+ }+ b.mu.Lock()+ for id, target := range b.session {+ if target == instanceID {+ delete(b.session, id)+ }+ }+ for id, target := range b.agent {+ if target == instanceID {+ delete(b.agent, id)+ delete(b.agentSeen, id)+ }+ }+ b.mu.Unlock()+}++// PruneAgents drops agent bindings that have been idle longer than the+// given duration, then enforces an LRU cap by evicting the oldest entries+// until the count fits. A non-positive `idle` disables the TTL pass; a+// non-positive `max` disables the cap pass.+func (b *Bindings) PruneAgents(idle time.Duration, max int) {+ if b == nil {+ return+ }+ b.mu.Lock()+ defer b.mu.Unlock()++ if idle > 0 {+ cutoff := b.now().Add(-idle)+ for id, seen := range b.agentSeen {+ if seen.Before(cutoff) {+ delete(b.agent, id)+ delete(b.agentSeen, id)+ }+ }+ }+ if max > 0 && len(b.agent) > max {+ type entry struct {+ id string+ seen time.Time+ }+ entries := make([]entry, 0, len(b.agentSeen))+ for id, seen := range b.agentSeen {+ entries = append(entries, entry{id, seen})+ }+ sort.Slice(entries, func(i, j int) bool {+ return entries[i].seen.Before(entries[j].seen)+ })+ excess := len(entries) - max+ for i := 0; i < excess; i++ {+ delete(b.agent, entries[i].id)+ delete(b.agentSeen, entries[i].id)+ }+ }+}++// Counts returns the current number of session and agent bindings. Useful+// for metrics and tests.+func (b *Bindings) Counts() (sessions, agents int) {+ if b == nil {+ return 0, 0+ }+ b.mu.RLock()+ defer b.mu.RUnlock()+ return len(b.session), len(b.agent)+}diff --git a/internal/orchestrator/bindings_test.go b/internal/orchestrator/bindings_test.gonew file mode 100644index 00000000..0507c612--- /dev/null+++ b/internal/orchestrator/bindings_test.go@@ -0,0 +1,133 @@+package orchestrator++import (+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/bridge"+)++func TestBindings_SessionRoundTrip(t *testing.T) {+ b := NewBindings(nil)+ b.BindSession("ses_1", "inst_a")+ if got, ok := b.ResolveSession("ses_1"); !ok || got != "inst_a" {+ t.Fatalf("ResolveSession = %q, %v; want inst_a, true", got, ok)+ }+ b.ClearSession("ses_1")+ if _, ok := b.ResolveSession("ses_1"); ok {+ t.Fatal("expected session binding cleared")+ }+}++func TestBindings_AgentResolveBumpsIdle(t *testing.T) {+ t0 := time.Unix(1_700_000_000, 0)+ clock := t0+ b := NewBindings(func() time.Time { return clock })+ b.BindAgent("agent-1", "inst_a")++ clock = t0.Add(30 * time.Minute)+ if _, ok := b.ResolveAgent("agent-1"); !ok {+ t.Fatal("expected agent binding to resolve")+ }+ clock = t0.Add(90 * time.Minute) // would be older than 1h cutoff from t0+ b.PruneAgents(1*time.Hour, 0)+ if _, ok := b.ResolveAgent("agent-1"); !ok {+ t.Fatal("Resolve should have bumped idle past cutoff and survived prune")+ }+}++func TestBindings_PruneIdleAgents(t *testing.T) {+ t0 := time.Unix(1_700_000_000, 0)+ clock := t0+ b := NewBindings(func() time.Time { return clock })++ b.BindAgent("stale", "inst_a")+ clock = t0.Add(2 * time.Hour)+ b.BindAgent("fresh", "inst_b")++ b.PruneAgents(1*time.Hour, 0)++ if _, ok := b.ResolveAgent("stale"); ok {+ t.Fatal("stale agent should have been pruned")+ }+ if _, ok := b.ResolveAgent("fresh"); !ok {+ t.Fatal("fresh agent should have survived")+ }+}++func TestBindings_PruneLRUCap(t *testing.T) {+ t0 := time.Unix(1_700_000_000, 0)+ clock := t0+ b := NewBindings(func() time.Time { return clock })++ for i, id := range []string{"a", "b", "c", "d"} {+ clock = t0.Add(time.Duration(i) * time.Minute)+ b.BindAgent(id, "inst_x")+ }+ b.PruneAgents(0, 2)++ if _, ok := b.ResolveAgent("a"); ok {+ t.Fatal("oldest 'a' should be evicted by LRU cap")+ }+ if _, ok := b.ResolveAgent("b"); ok {+ t.Fatal("oldest 'b' should be evicted by LRU cap")+ }+ if _, ok := b.ResolveAgent("c"); !ok {+ t.Fatal("'c' should survive cap")+ }+ if _, ok := b.ResolveAgent("d"); !ok {+ t.Fatal("'d' should survive cap")+ }+}++func TestBindings_ClearInstanceDropsEveryReference(t *testing.T) {+ b := NewBindings(nil)+ b.BindSession("ses_1", "inst_a")+ b.BindSession("ses_2", "inst_b")+ b.BindAgent("agent-1", "inst_a")+ b.BindAgent("agent-2", "inst_b")++ b.ClearInstance("inst_a")++ if _, ok := b.ResolveSession("ses_1"); ok {+ t.Fatal("session pointing at cleared instance should be dropped")+ }+ if _, ok := b.ResolveAgent("agent-1"); ok {+ t.Fatal("agent pointing at cleared instance should be dropped")+ }+ if _, ok := b.ResolveSession("ses_2"); !ok {+ t.Fatal("session for surviving instance should remain")+ }+ if _, ok := b.ResolveAgent("agent-2"); !ok {+ t.Fatal("agent for surviving instance should remain")+ }+}++func TestBindings_NilSafe(t *testing.T) {+ var b *Bindings+ b.BindSession("a", "b")+ b.BindAgent("a", "b")+ if _, ok := b.ResolveSession("a"); ok {+ t.Fatal("nil should resolve nothing")+ }+ if _, ok := b.ResolveAgent("a"); ok {+ t.Fatal("nil should resolve nothing")+ }+ b.ClearInstance("anything")+ b.PruneAgents(time.Hour, 1)+}++func TestOrchestrator_InstanceStoppedClearsBindings(t *testing.T) {+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{})+ o.bindings.BindSession("ses_1", "inst_a")+ o.bindings.BindAgent("agent-1", "inst_a")++ o.EmitEvent("instance.stopped", &bridge.Instance{ID: "inst_a"})++ if _, ok := o.bindings.ResolveSession("ses_1"); ok {+ t.Fatal("instance.stopped should clear session bindings")+ }+ if _, ok := o.bindings.ResolveAgent("agent-1"); ok {+ t.Fatal("instance.stopped should clear agent bindings")+ }+}diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.goindex ba31c94a..46edaaf9 100644--- a/internal/orchestrator/handlers.go+++ b/internal/orchestrator/handlers.go@@ -128,7 +128,8 @@ func (o *Orchestrator) handleList(w http.ResponseWriter, r *http.Request) {}func (o *Orchestrator) handleAllTabs(w http.ResponseWriter, r *http.Request) {- httpx.JSON(w, 200, o.AllTabs())+ fresh := r.URL.Query().Get("fresh") == "1"+ httpx.JSON(w, 200, o.allTabs(fresh))}func (o *Orchestrator) handleAllMetrics(w http.ResponseWriter, r *http.Request) {diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.goindex 7ee44cef..07e5df79 100644--- a/internal/orchestrator/handlers_instances.go+++ b/internal/orchestrator/handlers_instances.go@@ -315,7 +315,8 @@ func (o *Orchestrator) handleInstanceTabs(w http.ResponseWriter, r *http.Requestreturn}- tabs, err := o.fetchTabs(inst)+ fresh := r.URL.Query().Get("fresh") == "1"+ tabs, err := o.instanceTabsCached(inst, fresh)if err != nil {httpx.Error(w, 502, fmt.Errorf("failed to fetch tabs for instance %q: %w", id, err))returndiff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.goindex 78177790..3f167cdf 100644--- a/internal/orchestrator/orchestrator.go+++ b/internal/orchestrator/orchestrator.go@@ -2,7 +2,9 @@ package orchestratorimport ("context"+ "crypto/rand""crypto/subtle"+ "encoding/hex""encoding/json""fmt""io"@@ -45,11 +47,24 @@ type Orchestrator struct {client *http.ClientchildAuthToken stringallowEvaluate bool- portAllocator *PortAllocator- idMgr *ids.Manager- eventHandlers []EventHandler- instanceMgr *instance.Manager- runtimeCfg *config.RuntimeConfig+ internalToken string+ bindings *Bindings++ // strictCrossInstanceTab toggles the cross-instance explicit-tab rule.+ // When false (default), a request that targets a tab on a different+ // instance than the caller's existing identity binding rebinds the+ // caller to the owner instance. When true, such requests return+ // 409 cross_instance_tab and the binding is left untouched.+ strictCrossInstanceTab bool++ // tabsCache stores per-instance snapshots of /tabs results to absorb+ // repeated dashboard visibility queries. Routing never reads it.+ tabsCache *TabsCache+ portAllocator *PortAllocator+ idMgr *ids.Manager+ eventHandlers []EventHandler+ instanceMgr *instance.Manager+ runtimeCfg *config.RuntimeConfig}// OnEvent adds an event handler for instance lifecycle events.@@ -95,6 +110,20 @@ type LaunchOptions struct {SecurityPolicy *bridge.SecurityPolicy}+// generateInternalToken returns a random hex string used as the shared+// secret between the orchestrator and its spawned instances. The token+// authorizes orchestrator → instance proxy hops as trusted-internal,+// allowing X-PinchTab-* identity headers to flow through.+func generateInternalToken() string {+ b := make([]byte, 32)+ if _, err := rand.Read(b); err != nil {+ // Best effort: an empty token disables trusted-internal-proxy and+ // falls back to header stripping on the instance side.+ return ""+ }+ return hex.EncodeToString(b)+}+func NewOrchestrator(baseDir string) *Orchestrator {return NewOrchestratorWithRunner(baseDir, &LocalRunner{})}@@ -143,10 +172,26 @@ func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *Orchestratorclient: &http.Client{Timeout: 60 * time.Second},childAuthToken: "",allowEvaluate: false,+ internalToken: generateInternalToken(),+ bindings: NewBindings(nil),+ tabsCache: NewTabsCache(0, nil),portAllocator: NewPortAllocator(9868, 9968),idMgr: ids.NewManager(),}+ // Drop identity → instance bindings and any cached tab snapshots when+ // an instance stops or errors so a restarted instance does not keep+ // receiving routed traffic and dashboards do not show ghost tabs.+ orch.OnEvent(func(evt InstanceEvent) {+ switch evt.Type {+ case "instance.stopped", "instance.error":+ if evt.Instance != nil {+ orch.bindings.ClearInstance(evt.Instance.ID)+ orch.tabsCache.Invalidate(evt.Instance.ID)+ }+ }+ })+bridgeClient := instance.NewBridgeClient()orch.instanceMgr = instance.NewManager(&orchestratorLauncher{orch: orch},@@ -156,6 +201,50 @@ func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *Orchestratorreturn orch}+// RunMaintenance runs periodic background maintenance tasks for the+// orchestrator (currently: pruning idle agent bindings). Returns when ctx+// is cancelled.+func (o *Orchestrator) RunMaintenance(ctx context.Context) {+ if o == nil {+ return+ }+ const (+ tick = 5 * time.Minute+ idleTTL = 1 * time.Hour+ maxAgent = 10000+ )+ t := time.NewTicker(tick)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ o.bindings.PruneAgents(idleTTL, maxAgent)+ }+ }+}++// Bindings returns the identity → instance binding map. Exposed for tests+// and for handlers that need to inspect routing state.+func (o *Orchestrator) Bindings() *Bindings {+ if o == nil {+ return nil+ }+ return o.bindings+}++// SetStrictCrossInstanceTab toggles strict cross-instance handling. See+// the strictCrossInstanceTab field for semantics.+func (o *Orchestrator) SetStrictCrossInstanceTab(strict bool) {+ if o == nil {+ return+ }+ o.mu.Lock()+ o.strictCrossInstanceTab = strict+ o.mu.Unlock()+}+// InstanceManager returns the decomposed instance manager.func (o *Orchestrator) InstanceManager() *instance.Manager {return o.instanceMgr@@ -363,6 +452,9 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts"PINCHTAB_PORT": port,"PINCHTAB_CONFIG": childConfigPath,}+ if o.internalToken != "" {+ envOverrides["PINCHTAB_INTERNAL_TOKEN"] = o.internalToken+ }env := mergeEnvWithOverrides(filterEnvWithPrefixes(os.Environ(), "PINCHTAB_"), envOverrides)logBuf := newRingBuffer(256 * 1024)@@ -862,7 +954,41 @@ func (o *Orchestrator) FirstRunningURL() string {return candidates[0].url}+// instanceTabsCached returns the tab list for inst using the per-instance+// cache. fresh=true forces a bypass and refresh. Returned tabs are+// InstanceTab-shaped (with InstanceID set) so callers can hand them+// straight to JSON encoders.+func (o *Orchestrator) instanceTabsCached(inst *InstanceInternal, fresh bool) ([]bridge.InstanceTab, error) {+ if inst == nil {+ return nil, fmt.Errorf("nil instance")+ }+ if !fresh {+ if cached, ok := o.tabsCache.Get(inst.ID); ok {+ return cached, nil+ }+ }+ tabs, err := o.fetchTabs(inst)+ if err != nil {+ return nil, err+ }+ out := make([]bridge.InstanceTab, 0, len(tabs))+ for _, tab := range tabs {+ out = append(out, bridge.InstanceTab{+ ID: tab.ID,+ InstanceID: inst.ID,+ URL: tab.URL,+ Title: tab.Title,+ })+ }+ o.tabsCache.Set(inst.ID, out)+ return out, nil+}+func (o *Orchestrator) AllTabs() []bridge.InstanceTab {+ return o.allTabs(false)+}++func (o *Orchestrator) allTabs(fresh bool) []bridge.InstanceTab {o.mu.RLock()instances := make([]*InstanceInternal, 0)for _, inst := range o.instances {@@ -874,18 +1000,11 @@ func (o *Orchestrator) AllTabs() []bridge.InstanceTab {all := make([]bridge.InstanceTab, 0)for _, inst := range instances {- tabs, err := o.fetchTabs(inst)+ tabs, err := o.instanceTabsCached(inst, fresh)if err != nil {continue}- for _, tab := range tabs {- all = append(all, bridge.InstanceTab{- ID: tab.ID,- InstanceID: inst.ID,- URL: tab.URL,- Title: tab.Title,- })- }+ all = append(all, tabs...)}return all}diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.goindex 38ee6e04..98a56d29 100644--- a/internal/orchestrator/proxy.go+++ b/internal/orchestrator/proxy.go@@ -134,8 +134,14 @@ func (o *Orchestrator) proxyToURL(w http.ResponseWriter, r *http.Request, targeto.applyInstanceAuth(req, inst)}},- OnResponseHeaders: o.handleProxyResponseHeaders,- OnResponse: enrichActivityFromResponse,+ OnResponseHeaders: func(origReq *http.Request, resp *http.Response) {+ var targetInstanceID string+ if inst := o.proxyTargetInstance(targetURL); inst != nil {+ targetInstanceID = inst.ID+ }+ o.handleProxyResponseHeaders(origReq, resp, targetInstanceID)+ },+ OnResponse: enrichActivityFromResponse,})}@@ -312,6 +318,13 @@ func (o *Orchestrator) applyInstanceAuth(req *http.Request, inst *InstanceInternif token != "" {req.Header.Set("Authorization", "Bearer "+token)}+ // Mark spawned-child hops as trusted-internal-proxy so the instance+ // honors X-PinchTab-* identity headers we propagate. Attached external+ // bridges have their own auth domain and won't recognize the token,+ // which is the desired behavior.+ if inst.authToken == "" && o.internalToken != "" {+ req.Header.Set(handlers.InternalTokenHeader, o.internalToken)+ }}// classifyLaunchError returns appropriate HTTP status code for launch errors.@@ -349,22 +362,109 @@ func enrichActivityFromResponse(origReq *http.Request, body []byte) {}}-func (o *Orchestrator) handleProxyResponseHeaders(origReq *http.Request, resp *http.Response) {- if o == nil || o.instanceMgr == nil || origReq == nil || resp == nil {+func (o *Orchestrator) handleProxyResponseHeaders(origReq *http.Request, resp *http.Response, targetInstanceID string) {+ if o == nil || origReq == nil || resp == nil {return}if resp.StatusCode < 200 || resp.StatusCode >= 300 {return}- if tabID := tabClosePathID(origReq); tabID != "" {- o.instanceMgr.InvalidateTab(tabID)- return- }- if origReq.Method == http.MethodPost && strings.TrimSpace(origReq.URL.Path) == "/close" {- if tabID := strings.TrimSpace(resp.Header.Get(activity.HeaderPTTabID)); tabID != "" {++ // Tab close → invalidate locator entry. Pre-existing behavior, kept+ // here so callers continue to get cache freshness for free.+ if o.instanceMgr != nil {+ if tabID := tabClosePathID(origReq); tabID != "" {o.instanceMgr.InvalidateTab(tabID)+ } else if origReq.Method == http.MethodPost && strings.TrimSpace(origReq.URL.Path) == "/close" {+ if tabID := strings.TrimSpace(resp.Header.Get(activity.HeaderPTTabID)); tabID != "" {+ o.instanceMgr.InvalidateTab(tabID)+ }+ }+ }++ // Identity → instance binding writes. Bindings are persisted only after+ // a successful proxy response so failed requests never create or move+ // routing state.+ if o.bindings != nil && targetInstanceID != "" {+ if id := sessionIDForRouting(origReq); id != "" {+ o.bindings.BindSession(id, targetInstanceID)+ }+ if id := strings.TrimSpace(origReq.Header.Get(activity.HeaderAgentID)); id != "" {+ o.bindings.BindAgent(id, targetInstanceID)+ }+ }++ // Tabs cache invalidation. Any successful response that may have+ // changed the instance's tab list (open/close/navigate/history) drops+ // the cached snapshot so the next dashboard read picks up fresh data.+ if o.tabsCache != nil && targetInstanceID != "" && tabsCacheRequestAffectsTabs(origReq, resp) {+ o.tabsCache.Invalidate(targetInstanceID)+ }+}++// tabsCacheRequestAffectsTabs reports whether a successful response should+// invalidate the per-instance tabs cache. Errs on the side of invalidating+// rather than serving stale data — the cache is a perf optimization, not+// a correctness guarantee.+func tabsCacheRequestAffectsTabs(req *http.Request, resp *http.Response) bool {+ if req == nil {+ return false+ }+ // X-PinchTab-Tab-Id is a strong signal something changed; invalidate+ // regardless of the route the request hit.+ if resp != nil {+ if strings.TrimSpace(resp.Header.Get(activity.HeaderPTTabID)) != "" {+ return true+ }+ }+ if req.Method != http.MethodPost {+ return false+ }+ path := strings.TrimSpace(req.URL.Path)+ switch path {+ case "/tab", "/close", "/navigate", "/reload", "/back", "/forward":+ return true+ }+ if subpath := instanceRouteSubpath(path); subpath != "" {+ switch subpath {+ case "/tabs/open", "/tab", "/close", "/navigate", "/reload", "/back", "/forward":+ return true+ }+ if strings.HasPrefix(subpath, "/tabs/") {+ switch {+ case strings.HasSuffix(subpath, "/close"),+ strings.HasSuffix(subpath, "/navigate"),+ strings.HasSuffix(subpath, "/reload"),+ strings.HasSuffix(subpath, "/back"),+ strings.HasSuffix(subpath, "/forward"):+ return true+ }+ }+ }+ if strings.HasPrefix(path, "/tabs/") {+ // Sub-routes that mutate tab state: /tabs/{id}/{close,navigate,reload,back,forward}+ switch {+ case strings.HasSuffix(path, "/close"),+ strings.HasSuffix(path, "/navigate"),+ strings.HasSuffix(path, "/reload"),+ strings.HasSuffix(path, "/back"),+ strings.HasSuffix(path, "/forward"):+ return true}}+ return false+}++func instanceRouteSubpath(path string) string {+ if !strings.HasPrefix(path, "/instances/") {+ return ""+ }+ rest := strings.TrimPrefix(path, "/instances/")+ _, subpath, ok := strings.Cut(rest, "/")+ if !ok || subpath == "" {+ return ""+ }+ return "/" + subpath}func tabClosePathID(r *http.Request) string {diff --git a/internal/orchestrator/route.go b/internal/orchestrator/route.gonew file mode 100644index 00000000..f023809c--- /dev/null+++ b/internal/orchestrator/route.go@@ -0,0 +1,210 @@+package orchestrator++import (+ "fmt"+ "net/http"+ "strings"++ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/handlers"+ "github.com/pinchtab/pinchtab/internal/httpx"+ "github.com/pinchtab/pinchtab/internal/session"+)++// RoutingDecision identifies which precedence rule selected the target+// instance for a shorthand request. Used for metrics and logging.+type RoutingDecision string++const (+ RoutingDecisionTabOwner RoutingDecision = "tab_owner"+ RoutingDecisionSession RoutingDecision = "session"+ RoutingDecisionAgent RoutingDecision = "agent"+ RoutingDecisionFallback RoutingDecision = "fallback"+)++// WrapShorthand wraps a strategy-supplied fallback handler with the routing+// precedence defined in tab-spec.md:+//+// 1. Explicit tab id (path / query / JSON body): route to the owning+// instance. Not found + multiple instances → 404; not found + single+// instance → fall through to the only instance for legacy ergonomics.+// 2. Session binding: route to the bound instance if still running.+// 3. Agent binding: route to the bound instance if still running.+// 4. Fallback: invoke the strategy handler.+//+// The wrapper does not write or move bindings — that is step 1.5's job and+// happens in the proxy response hook after a successful response.+func (o *Orchestrator) WrapShorthand(fallback http.HandlerFunc) http.HandlerFunc {+ if o == nil {+ return fallback+ }+ return func(w http.ResponseWriter, r *http.Request) {+ if tabID, _ := ExtractExplicitTabID(r); tabID != "" {+ if o.routeByTabOwner(w, r, tabID) {+ return+ }+ // routeByTabOwner already wrote a 404 / single-instance proxy;+ // only return false when no decision could be made.+ return+ }++ if instanceID, decision, ok := o.resolveIdentityBinding(r); ok {+ if o.routeToInstanceID(w, r, instanceID, decision) {+ return+ }+ }++ fallback(w, r)+ }+}++// routeByTabOwner handles precedence rule 1. Returns true if a response was+// already written (either a successful proxy or an error).+func (o *Orchestrator) routeByTabOwner(w http.ResponseWriter, r *http.Request, tabID string) bool {+ // Fast path via locator cache.+ if o.instanceMgr != nil {+ if inst, err := o.instanceMgr.FindInstanceByTabID(tabID); err == nil && inst != nil {+ if !o.allowCrossInstance(w, r, inst.ID) {+ return true+ }+ o.proxyToInstanceForRoute(w, r, inst, tabID, RoutingDecisionTabOwner)+ return true+ }+ }+ // Slow path: enumerate running instances.+ if internal, err := o.findRunningInstanceByTabID(tabID); err == nil && internal != nil {+ if o.instanceMgr != nil {+ o.instanceMgr.Locator.Register(tabID, internal.ID)+ }+ if !o.allowCrossInstance(w, r, internal.ID) {+ return true+ }+ o.proxyToInstanceForRoute(w, r, &internal.Instance, tabID, RoutingDecisionTabOwner)+ return true+ }++ // Tab not found. If exactly one instance is running, fall through to it+ // — preserves legacy ergonomics for users running `--tab` against a+ // just-created tab whose id has not propagated to the dashboard yet.+ if only := o.singleRunningInstance(); only != nil {+ o.proxyToInstanceForRoute(w, r, &only.Instance, tabID, RoutingDecisionFallback)+ return true+ }++ // Multiple instances and no owner found — refuse to guess.+ httpx.Error(w, http.StatusNotFound, fmt.Errorf("tab %q not found", tabID))+ return true+}++// resolveIdentityBinding implements precedence rules 2 and 3. Public+// session-authenticated requests resolve from the authenticated session+// context. Trusted internal proxy hops resolve from the propagated session+// header. Raw public X-PinchTab-Session-Id is never trusted.+func (o *Orchestrator) resolveIdentityBinding(r *http.Request) (string, RoutingDecision, bool) {+ if r == nil || o.bindings == nil {+ return "", "", false+ }+ if id := sessionIDForRouting(r); id != "" {+ if inst, ok := o.bindings.ResolveSession(id); ok {+ return inst, RoutingDecisionSession, true+ }+ }+ if id := strings.TrimSpace(r.Header.Get(activity.HeaderAgentID)); id != "" {+ if inst, ok := o.bindings.ResolveAgent(id); ok {+ return inst, RoutingDecisionAgent, true+ }+ }+ return "", "", false+}++func sessionIDForRouting(r *http.Request) string {+ if r == nil {+ return ""+ }+ if sess, ok := session.FromRequest(r); ok && sess != nil {+ if id := strings.TrimSpace(sess.ID); id != "" {+ return id+ }+ }+ if handlers.IsTrustedInternalProxy(r) {+ return strings.TrimSpace(r.Header.Get(activity.HeaderPTSessionID))+ }+ return ""+}++// routeToInstanceID validates the bound instance is still running, then+// proxies. Stale bindings (instance gone) are cleared and a fall-through+// signal is returned (false means "let fallback handle it").+func (o *Orchestrator) routeToInstanceID(w http.ResponseWriter, r *http.Request, instanceID string, decision RoutingDecision) bool {+ o.mu.RLock()+ internal, ok := o.instances[instanceID]+ o.mu.RUnlock()+ if !ok || internal == nil || internal.Status != "running" || !instanceIsActive(internal) {+ // Stale binding: clear and let fallback decide.+ if o.bindings != nil {+ o.bindings.ClearInstance(instanceID)+ }+ return false+ }+ o.proxyToInstanceForRoute(w, r, &internal.Instance, "", decision)+ return true+}++// allowCrossInstance decides whether a tab-owner-routed request is allowed+// to land on ownerID when the caller's identity is currently bound to a+// different instance. Returns false (and writes a 409) only when strict+// cross-instance routing is enabled. The default rule rebinds silently;+// the actual rebind happens in the proxy response hook on success.+func (o *Orchestrator) allowCrossInstance(w http.ResponseWriter, r *http.Request, ownerID string) bool {+ o.mu.RLock()+ strict := o.strictCrossInstanceTab+ o.mu.RUnlock()+ if !strict || o.bindings == nil || ownerID == "" {+ return true+ }+ if id := sessionIDForRouting(r); id != "" {+ if existing, ok := o.bindings.ResolveSession(id); ok && existing != ownerID {+ httpx.ErrorCode(w, http.StatusConflict, "cross_instance_tab",+ fmt.Sprintf("session %q is bound to instance %q; tab lives on %q", id, existing, ownerID),+ false, nil)+ return false+ }+ }+ if id := strings.TrimSpace(r.Header.Get(activity.HeaderAgentID)); id != "" {+ if existing, ok := o.bindings.ResolveAgent(id); ok && existing != ownerID {+ httpx.ErrorCode(w, http.StatusConflict, "cross_instance_tab",+ fmt.Sprintf("agent %q is bound to instance %q; tab lives on %q", id, existing, ownerID),+ false, nil)+ return false+ }+ }+ return true+}++// proxyToInstanceForRoute handles activity enrichment and the actual proxy+// for a shorthand request that the routing layer resolved to a specific+// instance. tabID may be empty when routing came from an identity binding.+func (o *Orchestrator) proxyToInstanceForRoute(w http.ResponseWriter, r *http.Request, inst *bridge.Instance, tabID string, decision RoutingDecision) {+ if inst == nil {+ httpx.Error(w, http.StatusInternalServerError, fmt.Errorf("nil instance for routing decision %q", decision))+ return+ }+ activity.EnrichRouteActivity(r)+ update := activity.Update{+ InstanceID: inst.ID,+ ProfileID: inst.ProfileID,+ ProfileName: inst.ProfileName,+ }+ if tabID != "" {+ update.TabID = tabID+ }+ activity.EnrichRequest(r, update)++ targetURL, err := o.instancePathURLFromBridge(inst, r.URL.Path, r.URL.RawQuery)+ if err != nil {+ httpx.Error(w, http.StatusBadGateway, err)+ return+ }+ o.proxyToURL(w, r, targetURL)+}diff --git a/internal/orchestrator/route_test.go b/internal/orchestrator/route_test.gonew file mode 100644index 00000000..b48fa2ad--- /dev/null+++ b/internal/orchestrator/route_test.go@@ -0,0 +1,258 @@+package orchestrator++import (+ "bytes"+ "io"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/handlers"+ "github.com/pinchtab/pinchtab/internal/session"+)++// alwaysAlive replaces processAliveFunc so mockCmd-backed instances satisfy+// instanceIsActive without depending on real process state.+func alwaysAlive(t *testing.T) {+ t.Helper()+ orig := processAliveFunc+ processAliveFunc = func(int) bool { return true }+ t.Cleanup(func() { processAliveFunc = orig })+}++// newBackendInstance spins up an httptest server that records the request+// path it received, registers it on the orchestrator under instanceID, and+// returns a teardown.+func newBackendInstance(t *testing.T, o *Orchestrator, instanceID string) (*httptest.Server, *string) {+ t.Helper()+ gotPath := new(string)+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ *gotPath = r.URL.Path+ _, _ = io.WriteString(w, "ok")+ }))+ t.Cleanup(srv.Close)+ o.client = srv.Client()+ inst := &InstanceInternal{+ Instance: bridge.Instance{ID: instanceID, Status: "running", URL: srv.URL},+ URL: srv.URL,+ cmd: &mockCmd{pid: 1, isAlive: true},+ }+ o.instances[instanceID] = inst+ o.syncInstanceToManager(&inst.Instance)+ return srv, gotPath+}++func TestWrapShorthand_TabOwnerWins(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ _, pathA := newBackendInstance(t, o, "inst_a")+ _, pathB := newBackendInstance(t, o, "inst_b")++ o.instanceMgr.Locator.Register("tab-x", "inst_b")++ called := false+ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ called = true+ w.WriteHeader(599)+ })++ body := []byte(`{"tabId":"tab-x"}`)+ r := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ r.Header.Set("Content-Type", "application/json")+ r.ContentLength = int64(len(body))+ w := httptest.NewRecorder()++ wrapped(w, r)++ if called {+ t.Fatal("fallback should not have been called when tab owner is known")+ }+ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", w.Code)+ }+ if *pathA != "" {+ t.Fatalf("instance A should not have been hit, got path %q", *pathA)+ }+ if *pathB != "/navigate" {+ t.Fatalf("instance B path = %q, want /navigate", *pathB)+ }+}++func TestWrapShorthand_TabNotFoundMultipleInstancesIs404(t *testing.T) {+ o := NewOrchestrator(t.TempDir())+ alwaysAlive(t)+ newBackendInstance(t, o, "inst_a")+ newBackendInstance(t, o, "inst_b")++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("fallback must not run when explicit tab id misses with multiple instances")+ })++ r := httptest.NewRequest("GET", "/text?tabId=ghost", nil)+ w := httptest.NewRecorder()+ wrapped(w, r)++ if w.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want 404", w.Code)+ }+}++func TestWrapShorthand_TabNotFoundSingleInstanceFallsThrough(t *testing.T) {+ o := NewOrchestrator(t.TempDir())+ alwaysAlive(t)+ _, gotPath := newBackendInstance(t, o, "inst_only")++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("legacy ergonomics: orchestrator should proxy directly, not call fallback")+ })++ r := httptest.NewRequest("GET", "/text?tabId=ghost", nil)+ w := httptest.NewRecorder()+ wrapped(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", w.Code)+ }+ if *gotPath != "/text" {+ t.Fatalf("backend path = %q, want /text", *gotPath)+ }+}++func TestWrapShorthand_SessionBindingHonoredOnTrustedHop(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ newBackendInstance(t, o, "inst_a")+ _, pathB := newBackendInstance(t, o, "inst_b")++ o.bindings.BindSession("ses_1", "inst_b")++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("session binding should have routed; fallback must not run")+ })++ r := httptest.NewRequest("GET", "/text", nil)+ r.Header.Set(activity.HeaderPTSessionID, "ses_1")+ r = r.WithContext(handlers.MarkTrustedInternalProxy(r.Context()))+ w := httptest.NewRecorder()+ wrapped(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", w.Code)+ }+ if *pathB != "/text" {+ t.Fatalf("instance B path = %q, want /text", *pathB)+ }+}++func TestWrapShorthand_SessionBindingHonoredFromAuthenticatedContext(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ newBackendInstance(t, o, "inst_a")+ _, pathB := newBackendInstance(t, o, "inst_b")++ o.bindings.BindSession("ses_public", "inst_b")++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("session binding should have routed; fallback must not run")+ })++ r := httptest.NewRequest("GET", "/text", nil)+ r = session.WithSession(r, &session.Session{ID: "ses_public", AgentID: "agent-1"})+ w := httptest.NewRecorder()+ wrapped(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", w.Code)+ }+ if *pathB != "/text" {+ t.Fatalf("instance B path = %q, want /text", *pathB)+ }+}++func TestWrapShorthand_SessionHeaderIgnoredWithoutTrust(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ newBackendInstance(t, o, "inst_a")+ newBackendInstance(t, o, "inst_b")++ o.bindings.BindSession("ses_1", "inst_b")++ called := false+ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ called = true+ w.WriteHeader(http.StatusTeapot)+ })++ // No trusted-internal marker — header is internal metadata, must be ignored.+ r := httptest.NewRequest("GET", "/text", nil)+ r.Header.Set(activity.HeaderPTSessionID, "ses_1")+ w := httptest.NewRecorder()+ wrapped(w, r)++ if !called {+ t.Fatal("fallback must run when session header is untrusted")+ }+ if w.Code != http.StatusTeapot {+ t.Fatalf("status = %d, want 418 (fallback signal)", w.Code)+ }+}++func TestWrapShorthand_AgentBindingHonored(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ newBackendInstance(t, o, "inst_a")+ _, pathB := newBackendInstance(t, o, "inst_b")++ o.bindings.BindAgent("agent-1", "inst_b")++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("agent binding should have routed; fallback must not run")+ })++ r := httptest.NewRequest("GET", "/text", nil)+ r.Header.Set(activity.HeaderAgentID, "agent-1")+ w := httptest.NewRecorder()+ wrapped(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", w.Code)+ }+ if *pathB != "/text" {+ t.Fatalf("instance B path = %q, want /text", *pathB)+ }+}++func TestWrapShorthand_StaleBindingFallsThrough(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ _, pathA := newBackendInstance(t, o, "inst_a")++ // Bind to an instance that no longer exists.+ o.bindings.BindAgent("agent-1", "inst_gone")++ called := false+ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ called = true+ // Simulate the strategy fallback proxying to the only running instance.+ o.ProxyToTarget(w, r, o.instances["inst_a"].URL+r.URL.Path)+ })++ r := httptest.NewRequest("GET", "/text", nil)+ r.Header.Set(activity.HeaderAgentID, "agent-1")+ w := httptest.NewRecorder()+ wrapped(w, r)++ if !called {+ t.Fatal("stale binding should fall through to fallback")+ }+ if *pathA != "/text" {+ t.Fatalf("fallback path on instance A = %q, want /text", *pathA)+ }+ // The successful fallback proxy rebinds the agent to the instance that+ // actually served the request (inst_a), replacing the stale entry.+ if got, ok := o.bindings.ResolveAgent("agent-1"); !ok || got != "inst_a" {+ t.Fatalf("agent binding after stale fallthrough = %q, %v; want inst_a, true", got, ok)+ }+}diff --git a/internal/orchestrator/route_writes_test.go b/internal/orchestrator/route_writes_test.gonew file mode 100644index 00000000..4f5c67ff--- /dev/null+++ b/internal/orchestrator/route_writes_test.go@@ -0,0 +1,238 @@+package orchestrator++import (+ "bytes"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/handlers"+ "github.com/pinchtab/pinchtab/internal/session"+)++func instWithURL(id, url string) bridge.Instance {+ return bridge.Instance{ID: id, Status: "running", URL: url}+}++func TestWrapShorthand_AgentBindingWrittenOnSuccess(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ _, gotPath := newBackendInstance(t, o, "inst_only")++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ // Simulate the strategy's plain proxy to the only instance.+ o.ProxyToTarget(w, r, o.instances["inst_only"].URL+r.URL.Path)+ })++ r := httptest.NewRequest("GET", "/text", nil)+ r.Header.Set(activity.HeaderAgentID, "agent-1")+ w := httptest.NewRecorder()+ wrapped(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", w.Code)+ }+ if *gotPath != "/text" {+ t.Fatalf("path = %q, want /text", *gotPath)+ }+ if got, ok := o.bindings.ResolveAgent("agent-1"); !ok || got != "inst_only" {+ t.Fatalf("agent binding = %q, %v; want inst_only, true", got, ok)+ }+}++func TestWrapShorthand_SessionBindingWrittenOnTrustedSuccess(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ _, gotPath := newBackendInstance(t, o, "inst_only")++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ o.ProxyToTarget(w, r, o.instances["inst_only"].URL+r.URL.Path)+ })++ r := httptest.NewRequest("GET", "/text", nil)+ r.Header.Set(activity.HeaderPTSessionID, "ses_1")+ r = r.WithContext(handlers.MarkTrustedInternalProxy(r.Context()))+ w := httptest.NewRecorder()+ wrapped(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+ if *gotPath != "/text" {+ t.Fatalf("backend path = %q, want /text", *gotPath)+ }+ if got, ok := o.bindings.ResolveSession("ses_1"); !ok || got != "inst_only" {+ t.Fatalf("session binding = %q, %v; want inst_only, true", got, ok)+ }+}++func TestWrapShorthand_SessionBindingWrittenFromAuthenticatedContext(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ _, gotPath := newBackendInstance(t, o, "inst_only")++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ o.ProxyToTarget(w, r, o.instances["inst_only"].URL+r.URL.Path)+ })++ r := httptest.NewRequest("GET", "/text", nil)+ r = session.WithSession(r, &session.Session{ID: "ses_public", AgentID: "agent-1"})+ w := httptest.NewRecorder()+ wrapped(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+ if *gotPath != "/text" {+ t.Fatalf("backend path = %q, want /text", *gotPath)+ }+ if got, ok := o.bindings.ResolveSession("ses_public"); !ok || got != "inst_only" {+ t.Fatalf("session binding = %q, %v; want inst_only, true", got, ok)+ }+}++func TestWrapShorthand_SessionBindingNotWrittenWithoutTrust(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ newBackendInstance(t, o, "inst_only")++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ o.ProxyToTarget(w, r, o.instances["inst_only"].URL+r.URL.Path)+ })++ r := httptest.NewRequest("GET", "/text", nil)+ r.Header.Set(activity.HeaderPTSessionID, "spoofer")+ w := httptest.NewRecorder()+ wrapped(w, r)++ if _, ok := o.bindings.ResolveSession("spoofer"); ok {+ t.Fatal("untrusted session header must not write a binding")+ }+}++func TestWrapShorthand_TabOwnerRouteRebindsIdentityOnSuccess(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ newBackendInstance(t, o, "inst_a")+ _, pathB := newBackendInstance(t, o, "inst_b")++ o.bindings.BindAgent("agent-1", "inst_a")+ o.instanceMgr.Locator.Register("tab-on-b", "inst_b")++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("tab-owner routing should not fall back")+ })++ body := []byte(`{"tabId":"tab-on-b"}`)+ r := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ r.Header.Set("Content-Type", "application/json")+ r.ContentLength = int64(len(body))+ r.Header.Set(activity.HeaderAgentID, "agent-1")+ w := httptest.NewRecorder()+ wrapped(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+ if *pathB != "/navigate" {+ t.Fatalf("backend path = %q, want /navigate", *pathB)+ }+ if got, _ := o.bindings.ResolveAgent("agent-1"); got != "inst_b" {+ t.Fatalf("agent binding after cross-instance success = %q, want inst_b", got)+ }+}++func TestWrapShorthand_StrictRejectsCrossInstance(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ o.SetStrictCrossInstanceTab(true)+ newBackendInstance(t, o, "inst_a")+ _, pathB := newBackendInstance(t, o, "inst_b")++ o.bindings.BindAgent("agent-1", "inst_a")+ o.instanceMgr.Locator.Register("tab-on-b", "inst_b")++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("strict mode must reject before fallback")+ })++ body := []byte(`{"tabId":"tab-on-b"}`)+ r := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ r.Header.Set("Content-Type", "application/json")+ r.ContentLength = int64(len(body))+ r.Header.Set(activity.HeaderAgentID, "agent-1")+ w := httptest.NewRecorder()+ wrapped(w, r)++ if w.Code != http.StatusConflict {+ t.Fatalf("status = %d, want 409", w.Code)+ }+ if *pathB != "" {+ t.Fatalf("instance B should not have been hit, got path %q", *pathB)+ }+ if got, _ := o.bindings.ResolveAgent("agent-1"); got != "inst_a" {+ t.Fatalf("strict mode must not move binding; got %q, want inst_a", got)+ }+}++func TestWrapShorthand_StrictAllowsSameInstance(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())+ o.SetStrictCrossInstanceTab(true)+ _, gotPath := newBackendInstance(t, o, "inst_a")++ o.bindings.BindAgent("agent-1", "inst_a")+ o.instanceMgr.Locator.Register("tab-on-a", "inst_a")++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ t.Fatal("tab-owner must succeed when binding matches owner")+ })++ r := httptest.NewRequest("GET", "/text?tabId=tab-on-a", nil)+ r.Header.Set(activity.HeaderAgentID, "agent-1")+ w := httptest.NewRecorder()+ wrapped(w, r)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", w.Code)+ }+ if *gotPath != "/text" {+ t.Fatalf("path = %q, want /text", *gotPath)+ }+}++func TestWrapShorthand_BindingNotWrittenOnFailure(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())++ // Backend that always fails.+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusInternalServerError)+ }))+ t.Cleanup(srv.Close)+ o.client = srv.Client()+ o.instances["inst_fail"] = &InstanceInternal{+ Instance: instWithURL("inst_fail", srv.URL),+ URL: srv.URL,+ cmd: &mockCmd{pid: 1, isAlive: true},+ }+ o.syncInstanceToManager(&o.instances["inst_fail"].Instance)++ wrapped := o.WrapShorthand(func(w http.ResponseWriter, r *http.Request) {+ o.ProxyToTarget(w, r, srv.URL+r.URL.Path)+ })++ r := httptest.NewRequest("GET", "/text", nil)+ r.Header.Set(activity.HeaderAgentID, "agent-1")+ w := httptest.NewRecorder()+ wrapped(w, r)++ if w.Code != http.StatusInternalServerError {+ t.Fatalf("status = %d, want 500", w.Code)+ }+ if _, ok := o.bindings.ResolveAgent("agent-1"); ok {+ t.Fatal("binding must not be written on failed proxy")+ }+}diff --git a/internal/orchestrator/session_lifecycle.go b/internal/orchestrator/session_lifecycle.gonew file mode 100644index 00000000..36f27f4d--- /dev/null+++ b/internal/orchestrator/session_lifecycle.go@@ -0,0 +1,27 @@+package orchestrator++import (+ "github.com/pinchtab/pinchtab/internal/session"+)++// SessionLifecycleHook returns a session.LifecycleHook the caller can wire+// into a session.Store via OnLifecycle. The hook drops the session →+// instance binding so a future request that reuses the same session id+// will be re-routed via the normal precedence rules instead of resurrecting+// the old binding.+//+// The instance-side scoped current-tab map is bounded (LRU cap + stale+// detection on the bridge), so we deliberately do NOT propagate eviction+// over the network. Dead entries on the instance get pushed out by normal+// traffic; this avoids a separate trusted internal HTTP surface.+func (o *Orchestrator) SessionLifecycleHook() session.LifecycleHook {+ if o == nil {+ return func(session.LifecycleEvent) {}+ }+ return func(evt session.LifecycleEvent) {+ if evt.SessionID == "" {+ return+ }+ o.bindings.ClearSession(evt.SessionID)+ }+}diff --git a/internal/orchestrator/session_lifecycle_test.go b/internal/orchestrator/session_lifecycle_test.gonew file mode 100644index 00000000..46029d42--- /dev/null+++ b/internal/orchestrator/session_lifecycle_test.go@@ -0,0 +1,29 @@+package orchestrator++import (+ "testing"++ "github.com/pinchtab/pinchtab/internal/session"+)++func TestSessionLifecycleHook_ClearsBinding(t *testing.T) {+ o := NewOrchestrator(t.TempDir())+ o.bindings.BindSession("ses_dead", "inst_a")++ hook := o.SessionLifecycleHook()+ hook(session.LifecycleEvent{SessionID: "ses_dead", AgentID: "agent-x", Reason: session.LifecycleReasonRevoked})++ if _, ok := o.bindings.ResolveSession("ses_dead"); ok {+ t.Fatal("binding should have been cleared")+ }+}++func TestSessionLifecycleHook_NoopOnEmptyID(t *testing.T) {+ o := NewOrchestrator(t.TempDir())+ o.bindings.BindSession("ses_a", "inst_a")+ hook := o.SessionLifecycleHook()+ hook(session.LifecycleEvent{SessionID: "", Reason: session.LifecycleReasonExpired})+ if _, ok := o.bindings.ResolveSession("ses_a"); !ok {+ t.Fatal("unrelated binding should not be touched")+ }+}diff --git a/internal/orchestrator/tab_extract.go b/internal/orchestrator/tab_extract.gonew file mode 100644index 00000000..43791fa3--- /dev/null+++ b/internal/orchestrator/tab_extract.go@@ -0,0 +1,89 @@+package orchestrator++import (+ "bytes"+ "encoding/json"+ "io"+ "net/http"+ "strings"+)++// maxBodyPeek caps how much of an inbound JSON request body the orchestrator+// will buffer to look for an explicit "tabId" field. Bodies larger than this+// (or with no Content-Length, or non-JSON content type) are passed through+// without inspection.+const maxBodyPeek = 64 * 1024++// TabIDSource identifies where the explicit tab id was found.+type TabIDSource string++const (+ TabIDSourceNone TabIDSource = ""+ TabIDSourcePath TabIDSource = "path"+ TabIDSourceQuery TabIDSource = "query"+ TabIDSourceBody TabIDSource = "body"+)++// ExtractExplicitTabID inspects the request for a caller-supplied tab id in+// (in order) the routed path value `id`, the `tabId` query parameter, and+// finally a JSON body containing a `tabId` field. The first non-empty value+// wins.+//+// Body inspection is restricted to requests whose Content-Type begins with+// `application/json` and whose declared Content-Length is positive and at+// most maxBodyPeek bytes. Streaming, multipart, oversized, or+// unknown-length bodies are skipped — the body is left untouched. After a+// successful peek, the body is rewound so downstream handlers see it intact.+func ExtractExplicitTabID(r *http.Request) (string, TabIDSource) {+ if r == nil {+ return "", TabIDSourceNone+ }+ if id := strings.TrimSpace(r.PathValue("id")); id != "" {+ return id, TabIDSourcePath+ }+ if id := strings.TrimSpace(r.URL.Query().Get("tabId")); id != "" {+ return id, TabIDSourceQuery+ }+ if id := peekBodyTabID(r); id != "" {+ return id, TabIDSourceBody+ }+ return "", TabIDSourceNone+}++func peekBodyTabID(r *http.Request) string {+ if r == nil || r.Body == nil || r.Body == http.NoBody {+ return ""+ }+ if r.ContentLength <= 0 || r.ContentLength > maxBodyPeek {+ return ""+ }+ ct := r.Header.Get("Content-Type")+ if ct == "" {+ return ""+ }+ if i := strings.IndexByte(ct, ';'); i >= 0 {+ ct = ct[:i]+ }+ if !strings.EqualFold(strings.TrimSpace(ct), "application/json") {+ return ""+ }++ buf, err := io.ReadAll(io.LimitReader(r.Body, maxBodyPeek+1))+ if err != nil {+ // Body may already be partially consumed; do not attempt to repair.+ return ""+ }+ // Always restore the body so downstream handlers see the full payload.+ r.Body = io.NopCloser(bytes.NewReader(buf))+ if len(buf) > maxBodyPeek {+ return ""+ }++ var probe struct {+ TabID string `json:"tabId"`+ }+ if err := json.Unmarshal(buf, &probe); err != nil {+ return ""+ }+ return strings.TrimSpace(probe.TabID)+}diff --git a/internal/orchestrator/tab_extract_test.go b/internal/orchestrator/tab_extract_test.gonew file mode 100644index 00000000..606b229b--- /dev/null+++ b/internal/orchestrator/tab_extract_test.go@@ -0,0 +1,147 @@+package orchestrator++import (+ "bytes"+ "io"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestExtractExplicitTabID_Path(t *testing.T) {+ r := httptest.NewRequest("GET", "/x", nil)+ r.SetPathValue("id", "tab-from-path")+ got, src := ExtractExplicitTabID(r)+ if got != "tab-from-path" || src != TabIDSourcePath {+ t.Fatalf("got %q/%q; want tab-from-path/path", got, src)+ }+}++func TestExtractExplicitTabID_Query(t *testing.T) {+ r := httptest.NewRequest("GET", "/x?tabId=tab-q", nil)+ got, src := ExtractExplicitTabID(r)+ if got != "tab-q" || src != TabIDSourceQuery {+ t.Fatalf("got %q/%q; want tab-q/query", got, src)+ }+}++func TestExtractExplicitTabID_BodyJSON(t *testing.T) {+ body := []byte(`{"url":"about:blank","tabId":"tab-b"}`)+ r := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ r.Header.Set("Content-Type", "application/json")+ r.ContentLength = int64(len(body))++ got, src := ExtractExplicitTabID(r)+ if got != "tab-b" || src != TabIDSourceBody {+ t.Fatalf("got %q/%q; want tab-b/body", got, src)+ }++ // Body must be readable downstream.+ rest, err := io.ReadAll(r.Body)+ if err != nil {+ t.Fatalf("body read after peek: %v", err)+ }+ if !bytes.Equal(rest, body) {+ t.Fatalf("body after peek = %q; want %q", rest, body)+ }+}++func TestExtractExplicitTabID_BodyWithCharset(t *testing.T) {+ body := []byte(`{"tabId":"tab-c"}`)+ r := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ r.Header.Set("Content-Type", "application/json; charset=utf-8")+ r.ContentLength = int64(len(body))++ got, src := ExtractExplicitTabID(r)+ if got != "tab-c" || src != TabIDSourceBody {+ t.Fatalf("got %q/%q; want tab-c/body", got, src)+ }+}++func TestExtractExplicitTabID_BodySkippedForNonJSON(t *testing.T) {+ body := []byte(`{"tabId":"sneaky"}`)+ r := httptest.NewRequest("POST", "/x", bytes.NewReader(body))+ r.Header.Set("Content-Type", "text/plain")+ r.ContentLength = int64(len(body))++ got, src := ExtractExplicitTabID(r)+ if got != "" || src != TabIDSourceNone {+ t.Fatalf("non-JSON body should not be peeked, got %q/%q", got, src)+ }+}++func TestExtractExplicitTabID_BodySkippedWhenOversized(t *testing.T) {+ r := httptest.NewRequest("POST", "/x", bytes.NewReader([]byte(`{"tabId":"too-big"}`)))+ r.Header.Set("Content-Type", "application/json")+ r.ContentLength = maxBodyPeek + 1++ got, _ := ExtractExplicitTabID(r)+ if got != "" {+ t.Fatalf("oversized body should be skipped, got %q", got)+ }+}++func TestExtractExplicitTabID_BodySkippedWhenUnknownLength(t *testing.T) {+ r := httptest.NewRequest("POST", "/x", bytes.NewReader([]byte(`{"tabId":"streaming"}`)))+ r.Header.Set("Content-Type", "application/json")+ r.ContentLength = -1++ got, _ := ExtractExplicitTabID(r)+ if got != "" {+ t.Fatalf("unknown-length body should be skipped, got %q", got)+ }+}++func TestExtractExplicitTabID_QueryWinsOverBody(t *testing.T) {+ body := []byte(`{"tabId":"from-body"}`)+ r := httptest.NewRequest("POST", "/x?tabId=from-query", bytes.NewReader(body))+ r.Header.Set("Content-Type", "application/json")+ r.ContentLength = int64(len(body))++ got, src := ExtractExplicitTabID(r)+ if got != "from-query" || src != TabIDSourceQuery {+ t.Fatalf("query should win; got %q/%q", got, src)+ }+}++func TestExtractExplicitTabID_BadJSONLeavesBodyIntact(t *testing.T) {+ body := []byte(`{not-json`)+ r := httptest.NewRequest("POST", "/x", bytes.NewReader(body))+ r.Header.Set("Content-Type", "application/json")+ r.ContentLength = int64(len(body))++ got, _ := ExtractExplicitTabID(r)+ if got != "" {+ t.Fatalf("bad JSON should yield no tab id, got %q", got)+ }+ rest, _ := io.ReadAll(r.Body)+ if !bytes.Equal(rest, body) {+ t.Fatalf("body after failed peek = %q; want %q", rest, body)+ }+}++func TestExtractExplicitTabID_TrimsWhitespace(t *testing.T) {+ r := httptest.NewRequest("GET", "/x?tabId=%20%20", nil)+ got, _ := ExtractExplicitTabID(r)+ if got != "" {+ t.Fatalf("whitespace-only tab id should be empty, got %q", got)+ }+}++func TestExtractExplicitTabID_LongOKBody(t *testing.T) {+ // Pad body up close to (but under) the budget to exercise the+ // LimitReader sentinel path.+ pad := strings.Repeat(" ", maxBodyPeek-32)+ body := []byte(`{"tabId":"tail"` + pad + `}`)+ if len(body) > maxBodyPeek {+ t.Fatalf("test body %d > budget %d", len(body), maxBodyPeek)+ }+ r := httptest.NewRequest("POST", "/x", bytes.NewReader(body))+ r.Header.Set("Content-Type", "application/json")+ r.ContentLength = int64(len(body))++ got, _ := ExtractExplicitTabID(r)+ if got != "tail" {+ t.Fatalf("got %q, want tail", got)+ }+}diff --git a/internal/orchestrator/tabs_cache.go b/internal/orchestrator/tabs_cache.gonew file mode 100644index 00000000..ca9032f4--- /dev/null+++ b/internal/orchestrator/tabs_cache.go@@ -0,0 +1,111 @@+package orchestrator++import (+ "sync"+ "time"++ "github.com/pinchtab/pinchtab/internal/bridge"+)++// tabsCacheTTL is the default freshness window for cached per-instance tab+// snapshots. Short enough that a stale read at 1Hz dashboard polling+// rarely outlives a single tick, long enough to absorb bursts.+const tabsCacheTTL = 1500 * time.Millisecond++// tabsSnapshot is a per-instance tab list with its expiry deadline.+type tabsSnapshot struct {+ tabs []bridge.InstanceTab+ expiresAt time.Time+}++// TabsCache stores per-instance snapshots of /tabs results for the+// dashboard's aggregate endpoints. Routing decisions never read this cache+// — its only job is to absorb repeated visibility queries.+//+// Invalidation hooks bump entries on any successful proxied response that+// could affect the tab list (open / close / navigate / reload / history).+type TabsCache struct {+ mu sync.RWMutex+ ttl time.Duration+ now func() time.Time+ data map[string]tabsSnapshot+}++// NewTabsCache returns an empty cache. Pass zero ttl to use tabsCacheTTL.+// Pass nil now to use time.Now (tests can inject a deterministic clock).+func NewTabsCache(ttl time.Duration, now func() time.Time) *TabsCache {+ if ttl <= 0 {+ ttl = tabsCacheTTL+ }+ if now == nil {+ now = time.Now+ }+ return &TabsCache{+ ttl: ttl,+ now: now,+ data: make(map[string]tabsSnapshot),+ }+}++// Get returns the cached snapshot for instanceID if it has not expired.+// The returned slice is the cache's storage; callers that mutate it must+// copy first.+func (c *TabsCache) Get(instanceID string) ([]bridge.InstanceTab, bool) {+ if c == nil || instanceID == "" {+ return nil, false+ }+ c.mu.RLock()+ defer c.mu.RUnlock()+ snap, ok := c.data[instanceID]+ if !ok || c.now().After(snap.expiresAt) {+ return nil, false+ }+ return snap.tabs, true+}++// Set stores a fresh snapshot for instanceID.+func (c *TabsCache) Set(instanceID string, tabs []bridge.InstanceTab) {+ if c == nil || instanceID == "" {+ return+ }+ stored := make([]bridge.InstanceTab, len(tabs))+ copy(stored, tabs)+ c.mu.Lock()+ c.data[instanceID] = tabsSnapshot{+ tabs: stored,+ expiresAt: c.now().Add(c.ttl),+ }+ c.mu.Unlock()+}++// Invalidate drops the snapshot for instanceID. No-op if absent.+func (c *TabsCache) Invalidate(instanceID string) {+ if c == nil || instanceID == "" {+ return+ }+ c.mu.Lock()+ delete(c.data, instanceID)+ c.mu.Unlock()+}++// InvalidateAll clears every entry. Used on broad lifecycle events+// (e.g. instance restart) where targeted invalidation is impractical.+func (c *TabsCache) InvalidateAll() {+ if c == nil {+ return+ }+ c.mu.Lock()+ c.data = make(map[string]tabsSnapshot)+ c.mu.Unlock()+}++// Len returns the current number of cached instances. Useful for metrics+// and tests.+func (c *TabsCache) Len() int {+ if c == nil {+ return 0+ }+ c.mu.RLock()+ defer c.mu.RUnlock()+ return len(c.data)+}diff --git a/internal/orchestrator/tabs_cache_test.go b/internal/orchestrator/tabs_cache_test.gonew file mode 100644index 00000000..755103c2--- /dev/null+++ b/internal/orchestrator/tabs_cache_test.go@@ -0,0 +1,190 @@+package orchestrator++import (+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/bridge"+)++func TestTabsCache_GetMissAndHit(t *testing.T) {+ c := NewTabsCache(time.Second, nil)+ if _, ok := c.Get("inst_a"); ok {+ t.Fatal("empty cache should miss")+ }+ c.Set("inst_a", []bridge.InstanceTab{{ID: "tab-1", InstanceID: "inst_a"}})+ got, ok := c.Get("inst_a")+ if !ok || len(got) != 1 || got[0].ID != "tab-1" {+ t.Fatalf("hit = %v / %#v", ok, got)+ }+}++func TestTabsCache_Expiry(t *testing.T) {+ t0 := time.Unix(1_700_000_000, 0)+ clock := t0+ c := NewTabsCache(500*time.Millisecond, func() time.Time { return clock })+ c.Set("inst_a", []bridge.InstanceTab{{ID: "tab-1"}})++ clock = t0.Add(200 * time.Millisecond)+ if _, ok := c.Get("inst_a"); !ok {+ t.Fatal("should still hit before expiry")+ }+ clock = t0.Add(700 * time.Millisecond)+ if _, ok := c.Get("inst_a"); ok {+ t.Fatal("should miss after expiry")+ }+}++func TestTabsCache_Invalidate(t *testing.T) {+ c := NewTabsCache(time.Second, nil)+ c.Set("inst_a", []bridge.InstanceTab{{ID: "tab-1"}})+ c.Invalidate("inst_a")+ if _, ok := c.Get("inst_a"); ok {+ t.Fatal("invalidate should drop entry")+ }+}++func TestTabsCache_InvalidateAll(t *testing.T) {+ c := NewTabsCache(time.Second, nil)+ c.Set("inst_a", []bridge.InstanceTab{{ID: "tab-1"}})+ c.Set("inst_b", []bridge.InstanceTab{{ID: "tab-2"}})+ c.InvalidateAll()+ if c.Len() != 0 {+ t.Fatalf("Len after InvalidateAll = %d", c.Len())+ }+}++func TestTabsCache_NilSafe(t *testing.T) {+ var c *TabsCache+ c.Set("a", nil)+ c.Invalidate("a")+ c.InvalidateAll()+ if _, ok := c.Get("a"); ok {+ t.Fatal("nil cache should always miss")+ }+ if c.Len() != 0 {+ t.Fatal("nil cache Len should be 0")+ }+}++func TestTabsCacheRequestAffectsTabs_PostShorthand(t *testing.T) {+ cases := map[string]bool{+ "/navigate": true,+ "/tab": true,+ "/close": true,+ "/reload": true,+ "/back": true,+ "/forward": true,+ "/instances/inst_a/tabs/open": true,+ "/instances/inst_a/tab": true,+ "/instances/inst_a/tabs/X/navigate": true,+ "/text": false,+ "/snap": false,+ }+ for path, want := range cases {+ req := httptest.NewRequest(http.MethodPost, path, nil)+ got := tabsCacheRequestAffectsTabs(req, nil)+ if got != want {+ t.Errorf("path %q affects = %v, want %v", path, got, want)+ }+ }+}++func TestTabsCacheRequestAffectsTabs_TabSubroutes(t *testing.T) {+ for _, path := range []string{+ "/tabs/X/close",+ "/tabs/X/navigate",+ "/tabs/X/reload",+ "/tabs/X/back",+ "/tabs/X/forward",+ } {+ req := httptest.NewRequest(http.MethodPost, path, nil)+ if !tabsCacheRequestAffectsTabs(req, nil) {+ t.Errorf("expected %q to invalidate", path)+ }+ }+ for _, path := range []string{"/tabs/X/snapshot", "/tabs/X/text"} {+ req := httptest.NewRequest(http.MethodPost, path, nil)+ if tabsCacheRequestAffectsTabs(req, nil) {+ t.Errorf("expected %q NOT to invalidate", path)+ }+ }+}++func TestTabsCacheRequestAffectsTabs_GETIgnoredUnlessHeaderSurfaces(t *testing.T) {+ req := httptest.NewRequest(http.MethodGet, "/tabs", nil)+ if tabsCacheRequestAffectsTabs(req, nil) {+ t.Fatal("plain GET should not invalidate")+ }++ resp := &http.Response{Header: http.Header{}}+ resp.Header.Set(activity.HeaderPTTabID, "tab-just-changed")+ if !tabsCacheRequestAffectsTabs(req, resp) {+ t.Fatal("response carrying X-PinchTab-Tab-Id should invalidate")+ }+}++func TestOrchestrator_InstanceTabsCachedReusesEntry(t *testing.T) {+ alwaysAlive(t)+ o := NewOrchestrator(t.TempDir())++ calls := 0+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/tabs" {+ calls+++ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"tabs":[{"id":"tab-1","url":"about:blank"}]}`))+ return+ }+ w.WriteHeader(404)+ }))+ t.Cleanup(srv.Close)+ o.client = srv.Client()+ inst := &InstanceInternal{+ Instance: bridge.Instance{ID: "inst_a", Status: "running", URL: srv.URL},+ URL: srv.URL,+ cmd: &mockCmd{pid: 1, isAlive: true},+ }+ o.instances["inst_a"] = inst++ if _, err := o.instanceTabsCached(inst, false); err != nil {+ t.Fatalf("first fetch: %v", err)+ }+ if _, err := o.instanceTabsCached(inst, false); err != nil {+ t.Fatalf("second fetch: %v", err)+ }+ if calls != 1 {+ t.Fatalf("expected 1 backend call (cache hit on second), got %d", calls)+ }++ // fresh=true bypasses cache.+ if _, err := o.instanceTabsCached(inst, true); err != nil {+ t.Fatalf("fresh fetch: %v", err)+ }+ if calls != 2 {+ t.Fatalf("fresh=true should bypass, got %d backend calls", calls)+ }++ // Invalidate clears.+ o.tabsCache.Invalidate("inst_a")+ if _, err := o.instanceTabsCached(inst, false); err != nil {+ t.Fatalf("post-invalidate fetch: %v", err)+ }+ if calls != 3 {+ t.Fatalf("after invalidate, expected 3 backend calls, got %d", calls)+ }+}++func TestOrchestrator_InstanceStoppedClearsTabsCache(t *testing.T) {+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{})+ o.tabsCache.Set("inst_a", []bridge.InstanceTab{{ID: "tab-1"}})++ o.EmitEvent("instance.stopped", &bridge.Instance{ID: "inst_a"})++ if _, ok := o.tabsCache.Get("inst_a"); ok {+ t.Fatal("instance.stopped should drop cached tabs for that instance")+ }+}diff --git a/internal/server/bridge.go b/internal/server/bridge.goindex 4b8dd180..1d1f590a 100644--- a/internal/server/bridge.go+++ b/internal/server/bridge.go@@ -69,12 +69,14 @@ func RunBridgeServer(cfg *config.RuntimeConfig, version string) {server := &http.Server{Addr: listenAddr,- Handler: handlers.RequestIDMiddleware(- activity.Middleware(- actStore,- "bridge",- handlers.SecurityHeadersMiddleware(cfg,- handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.AuthMiddleware(cfg, mux))),+ Handler: handlers.TrustedInternalProxyStripMiddleware(os.Getenv("PINCHTAB_INTERNAL_TOKEN"))(+ handlers.RequestIDMiddleware(+ activity.Middleware(+ actStore,+ "bridge",+ handlers.SecurityHeadersMiddleware(cfg,+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.AuthMiddleware(cfg, mux))),+ ),),),),diff --git a/internal/server/server.go b/internal/server/server.goindex 696309da..fd359c73 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -88,6 +88,10 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {Instance: evt.Instance,})})++ // Drop identity → instance bindings and the instance's scoped current+ // tab when a session is revoked, expires, or is pruned.+ sessionStore.OnLifecycle(orch.SessionLifecycleHook())actStore, err := activity.NewRecorder(activity.Config{Enabled: cfg.Observability.Activity.Enabled,RetentionDays: cfg.Observability.Activity.RetentionDays,@@ -231,12 +235,14 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {mux.HandleFunc("GET /health", configAPI.HandleHealth)- handler := handlers.RequestIDMiddleware(- activity.Middleware(- liveActivity,- "server",- handlers.SecurityHeadersMiddleware(cfg,- handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(cfg, handlers.AuthMiddlewareWithSessions(cfg, sessions, sessionStore, mux)))),+ handler := handlers.StripInternalHeadersMiddleware(+ handlers.RequestIDMiddleware(+ activity.Middleware(+ liveActivity,+ "server",+ handlers.SecurityHeadersMiddleware(cfg,+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(cfg, handlers.AuthMiddlewareWithSessions(cfg, sessions, sessionStore, mux)))),+ ),),),)@@ -256,6 +262,9 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {slog.Error("strategy start failed", "strategy", activeStrategy.Name(), "err", err)}+ maintenanceCtx, maintenanceCancel := context.WithCancel(context.Background())+ go orch.RunMaintenance(maintenanceCtx)+shutdownOnce := &sync.Once{}doShutdown := func() {shutdownOnce.Do(func() {@@ -271,6 +280,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {sched.Stop()}syncCancel()+ maintenanceCancel()dash.Shutdown()orch.Shutdown()ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)diff --git a/internal/session/lifecycle_test.go b/internal/session/lifecycle_test.gonew file mode 100644index 00000000..8d17ebf3--- /dev/null+++ b/internal/session/lifecycle_test.go@@ -0,0 +1,152 @@+package session++import (+ "sync"+ "testing"+ "time"+)++// collectingHook returns a hook function plus a goroutine-safe getter for+// the events seen so far. The getter waits up to `wait` for the count+// to reach `want`.+func collectingHook(t *testing.T) (LifecycleHook, func(want int, wait time.Duration) []LifecycleEvent) {+ t.Helper()+ var (+ mu sync.Mutex+ events []LifecycleEvent+ signal = make(chan struct{}, 1024)+ )+ hook := func(evt LifecycleEvent) {+ mu.Lock()+ events = append(events, evt)+ mu.Unlock()+ select {+ case signal <- struct{}{}:+ default:+ }+ }+ wait := func(want int, timeout time.Duration) []LifecycleEvent {+ deadline := time.Now().Add(timeout)+ for {+ mu.Lock()+ if len(events) >= want {+ out := make([]LifecycleEvent, len(events))+ copy(out, events)+ mu.Unlock()+ return out+ }+ mu.Unlock()+ if remaining := time.Until(deadline); remaining > 0 {+ select {+ case <-signal:+ case <-time.After(remaining):+ }+ } else {+ mu.Lock()+ out := make([]LifecycleEvent, len(events))+ copy(out, events)+ mu.Unlock()+ return out+ }+ }+ }+ return hook, wait+}++func TestLifecycle_RevokeFiresHookAfterUnlock(t *testing.T) {+ s := NewStore(Config{Enabled: true, Mode: "preferred"})+ _, token, err := s.Create("agent-1", "test")+ if err != nil {+ t.Fatalf("Create: %v", err)+ }+ sess, ok := s.Authenticate(token)+ if !ok {+ t.Fatal("Authenticate failed")+ }++ hook, wait := collectingHook(t)+ // Hook tries to grab the store mutex — must succeed (i.e. mutex+ // already released by the time we are called).+ wrapped := func(evt LifecycleEvent) {+ if !s.mu.TryLock() {+ t.Errorf("hook ran while store mutex was held")+ return+ }+ s.mu.Unlock()+ hook(evt)+ }+ s.OnLifecycle(wrapped)++ if !s.Revoke(sess.ID) {+ t.Fatal("Revoke returned false")+ }+ got := wait(1, time.Second)+ if len(got) != 1 {+ t.Fatalf("got %d events, want 1: %#v", len(got), got)+ }+ if got[0].SessionID != sess.ID || got[0].Reason != LifecycleReasonRevoked {+ t.Fatalf("event = %#v, want sessionID=%s reason=revoked", got[0], sess.ID)+ }+}++func TestLifecycle_PrunePropagatesEvents(t *testing.T) {+ t0 := time.Unix(1_700_000_000, 0)+ clock := t0+ s := NewStore(Config{Enabled: true, Mode: "preferred", IdleTimeout: time.Hour})+ s.now = func() time.Time { return clock }++ _, token, err := s.Create("agent-stale", "")+ if err != nil {+ t.Fatalf("Create: %v", err)+ }+ if _, ok := s.Authenticate(token); !ok {+ t.Fatal("Authenticate failed")+ }++ hook, wait := collectingHook(t)+ s.OnLifecycle(hook)++ // Advance past idle timeout and trigger a prune via UpdateConfig.+ clock = t0.Add(2 * time.Hour)+ s.UpdateConfig(Config{Enabled: true, Mode: "preferred", IdleTimeout: time.Hour})++ got := wait(1, time.Second)+ if len(got) != 1 || got[0].Reason != LifecycleReasonPruned {+ t.Fatalf("expected one pruned event, got %#v", got)+ }+}++func TestLifecycle_AuthenticateExpiryFiresEvent(t *testing.T) {+ t0 := time.Unix(1_700_000_000, 0)+ clock := t0+ s := NewStore(Config{Enabled: true, Mode: "preferred", IdleTimeout: time.Hour})+ s.now = func() time.Time { return clock }++ _, token, err := s.Create("agent-expire", "")+ if err != nil {+ t.Fatalf("Create: %v", err)+ }++ hook, wait := collectingHook(t)+ s.OnLifecycle(hook)++ clock = t0.Add(2 * time.Hour)+ if _, ok := s.Authenticate(token); ok {+ t.Fatal("expired token should fail auth")+ }++ got := wait(1, time.Second)+ if len(got) != 1 || got[0].Reason != LifecycleReasonExpired {+ t.Fatalf("expected one expired event, got %#v", got)+ }+}++func TestLifecycle_NoSubscribersIsSafe(t *testing.T) {+ s := NewStore(Config{Enabled: true, Mode: "preferred"})+ _, token, _ := s.Create("agent-quiet", "")+ sess, _ := s.Authenticate(token)+ if !s.Revoke(sess.ID) {+ t.Fatal("Revoke")+ }+ // No assertion — just must not panic / deadlock.+}diff --git a/internal/session/store.go b/internal/session/store.goindex 59bccfc5..95f5f3a3 100644--- a/internal/session/store.go+++ b/internal/session/store.go@@ -41,12 +41,32 @@ type Config struct {PersistPath string}+// LifecycleEvent describes a session-state transition that downstream+// components (orchestrator binding eviction, instance current-tab cleanup)+// may want to react to.+type LifecycleEvent struct {+ SessionID string+ AgentID string+ Reason string // "revoked" | "expired" | "pruned"+}++// LifecycleHook receives events after a store mutation has committed.+// Hooks are invoked outside the store lock; they may do I/O but must not+// re-enter the store synchronously in a way that risks recursion.+type LifecycleHook func(LifecycleEvent)+// Store manages authenticated sessions with persistence.type Store struct {mu sync.Mutexsessions map[string]*Session // keyed by session IDcfg Confignow func() time.Time++ // hooksMu protects lifecycleHooks. Held only for very short reads /+ // writes so it never blocks anything else. Separate from `mu` so a+ // caller adding a hook never serializes against in-flight mutations.+ hooksMu sync.RWMutex+ lifecycleHooks []LifecycleHook}const (@@ -56,8 +76,48 @@ const (StatusActive = "active"StatusRevoked = "revoked"StatusExpired = "expired"++ LifecycleReasonRevoked = "revoked"+ LifecycleReasonExpired = "expired"+ LifecycleReasonPruned = "pruned")+// OnLifecycle registers a hook for session lifecycle events. Hooks run+// outside the store lock after a mutation has committed, so they may+// perform I/O without blocking other store operations. Multiple hooks+// run concurrently in separate goroutines.+func (s *Store) OnLifecycle(fn LifecycleHook) {+ if s == nil || fn == nil {+ return+ }+ s.hooksMu.Lock()+ s.lifecycleHooks = append(s.lifecycleHooks, fn)+ s.hooksMu.Unlock()+}++// dispatchLifecycle fires the given events to every registered hook,+// each in its own goroutine. Must be called after the store lock has+// been released — never under s.mu.+func (s *Store) dispatchLifecycle(events []LifecycleEvent) {+ if s == nil || len(events) == 0 {+ return+ }+ s.hooksMu.RLock()+ hooks := make([]LifecycleHook, len(s.lifecycleHooks))+ copy(hooks, s.lifecycleHooks)+ s.hooksMu.RUnlock()+ if len(hooks) == 0 {+ return+ }+ for _, evt := range events {+ evt := evt+ for _, fn := range hooks {+ fn := fn+ go fn(evt)+ }+ }+}+// NewStore creates a new session store.func NewStore(cfg Config) *Store {s := &Store{@@ -142,28 +202,43 @@ func (s *Store) authenticate(token string, touch bool) (*Session, bool) {hash := hashToken(token)now := s.now()- s.mu.Lock()- defer s.mu.Unlock()-- for _, sess := range s.sessions {- if sess.Status != StatusActive {- continue- }- if subtle.ConstantTimeCompare(hash[:], sess.TokenHash[:]) != 1 {- continue- }- if s.isExpired(sess, now) {- sess.Status = StatusExpired- s.saveLocked()- return nil, false+ var (+ match *Session+ ok bool+ expiredEvt *LifecycleEvent+ )++ func() {+ s.mu.Lock()+ defer s.mu.Unlock()++ for _, sess := range s.sessions {+ if sess.Status != StatusActive {+ continue+ }+ if subtle.ConstantTimeCompare(hash[:], sess.TokenHash[:]) != 1 {+ continue+ }+ if s.isExpired(sess, now) {+ sess.Status = StatusExpired+ s.saveLocked()+ expiredEvt = &LifecycleEvent{SessionID: sess.ID, AgentID: sess.AgentID, Reason: LifecycleReasonExpired}+ return+ }+ if touch {+ sess.LastSeenAt = now+ s.saveLocked()+ }+ match = sess+ ok = true+ return}- if touch {- sess.LastSeenAt = now- s.saveLocked()- }- return sess, true+ }()++ if expiredEvt != nil {+ s.dispatchLifecycle([]LifecycleEvent{*expiredEvt})}- return nil, false+ return match, ok}// Touch updates LastSeenAt for an active, unexpired session.@@ -225,15 +300,25 @@ func (s *Store) Revoke(sessionID string) bool {if s == nil {return false}- s.mu.Lock()- defer s.mu.Unlock()- sess, ok := s.sessions[strings.TrimSpace(sessionID)]- if !ok {+ var event LifecycleEvent+ revoked := func() bool {+ s.mu.Lock()+ defer s.mu.Unlock()++ sess, ok := s.sessions[strings.TrimSpace(sessionID)]+ if !ok {+ return false+ }+ sess.Status = StatusRevoked+ s.saveLocked()+ event = LifecycleEvent{SessionID: sess.ID, AgentID: sess.AgentID, Reason: LifecycleReasonRevoked}+ return true+ }()+ if !revoked {return false}- sess.Status = StatusRevoked- s.saveLocked()+ s.dispatchLifecycle([]LifecycleEvent{event})return true}@@ -244,9 +329,10 @@ func (s *Store) UpdateConfig(cfg Config) {}s.mu.Lock()s.applyConfig(cfg)- s.pruneExpiredLocked()+ events := s.pruneExpiredLocked()s.saveLocked()s.mu.Unlock()+ s.dispatchLifecycle(events)}// Enabled reports whether session auth is enabled.@@ -275,17 +361,24 @@ func (s *Store) isExpired(sess *Session, now time.Time) bool {return false}-func (s *Store) pruneExpiredLocked() {+// pruneExpiredLocked removes revoked/expired sessions. Caller must hold+// s.mu. Returns lifecycle events the caller is responsible for dispatching+// AFTER releasing the lock.+func (s *Store) pruneExpiredLocked() []LifecycleEvent {now := s.now()+ var events []LifecycleEventfor id, sess := range s.sessions {if sess.Status == StatusRevoked {delete(s.sessions, id)+ events = append(events, LifecycleEvent{SessionID: sess.ID, AgentID: sess.AgentID, Reason: LifecycleReasonPruned})continue}if s.isExpired(sess, now) {delete(s.sessions, id)+ events = append(events, LifecycleEvent{SessionID: sess.ID, AgentID: sess.AgentID, Reason: LifecycleReasonPruned})}}+ return events}// persistence typesdiff --git a/internal/strategy/routes.go b/internal/strategy/routes.goindex abe2ed73..81cdf07d 100644--- a/internal/strategy/routes.go+++ b/internal/strategy/routes.go@@ -36,15 +36,17 @@ func capabilitySetting(cap routes.Capability) (feature, setting, code string) {//// Routes are sourced from the shared routes.Core() catalogue.func RegisterShorthandRoutes(mux *http.ServeMux, orch *orchestrator.Orchestrator, handler http.HandlerFunc) {+ wrapped := orch.WrapShorthand(handler)+for _, route := range routes.ShorthandRoutes() {- mux.HandleFunc(route, handler)+ mux.HandleFunc(route, wrapped)}for cap, eps := range routes.CapabilityEndpoints() {enabled := orch.Allows(cap)feature, setting, code := capabilitySetting(cap)for _, ep := range eps {- RegisterCapabilityRoute(mux, ep.Route(), enabled, feature, setting, code, handler)+ RegisterCapabilityRoute(mux, ep.Route(), enabled, feature, setting, code, wrapped)}}}diff --git a/skills/pinchtab/references/api.md b/skills/pinchtab/references/api.mdindex 0e8e5247..3258e060 100644--- a/skills/pinchtab/references/api.md+++ b/skills/pinchtab/references/api.md@@ -21,6 +21,7 @@ Notes:- CLI users should prefer `pinchtab --agent-id <agent-id> ...` instead of setting the header manually- scheduler-submitted tasks reuse their `agentId` as `X-Agent-Id` when the task is executed+- omitted `tabId` resolves by caller identity: agent sessions use a session-scoped current tab, `X-Agent-Id` uses an agent-scoped current tab when no session is present, and anonymous requests use the shared global/default tab## Navigate@@ -337,7 +338,7 @@ curl -X POST /close -H 'Content-Type: application/json' -d '{}'curl -X POST /tabs/TARGET_ID/close```-Multi-tab: pass `?tabId=TARGET_ID` to snapshot/screenshot/text, or `"tabId"` in POST body.+Multi-tab: pass `?tabId=TARGET_ID` to snapshot/screenshot/text, or `"tabId"` in POST body. Explicit tab IDs always override and update the caller's current-tab scope.## Tab-specific endpointsdiff --git a/skills/pinchtab/references/commands.md b/skills/pinchtab/references/commands.mdindex 72227744..68917fc4 100644--- a/skills/pinchtab/references/commands.md+++ b/skills/pinchtab/references/commands.md@@ -73,6 +73,8 @@ pinchtab nav <url> --new-tab # Open a new tab and navigate itpinchtab tab close <tabId> # Close specific tab```+Unscoped commands resolve the current tab by caller identity. Session-authenticated callers use a current tab scoped to that session; `--agent-id` / `PINCHTAB_AGENT_ID` callers use a current tab scoped to that agent when no session is present; anonymous CLI calls use the shared local current-tab state file.+---## Interaction Commandsdiff --git a/skills/pinchtab/references/env.md b/skills/pinchtab/references/env.mdindex 2ad77565..8727901d 100644--- a/skills/pinchtab/references/env.md+++ b/skills/pinchtab/references/env.md@@ -34,7 +34,10 @@ PINCHTAB_TOKEN=...```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+unscoped commands. Anonymous CLI calls remember the current tab in a shared+local state file. Identified callers use server-side current-tab state instead:+agent sessions scope the current tab by session, and `--agent-id` /+`PINCHTAB_AGENT_ID` scope it by agent ID when no session is present. 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/tests/e2e/scenarios/cli/files-extended.sh b/tests/e2e/scenarios/cli/files-extended.shindex 133ccc8a..80a39052 100644--- a/tests/e2e/scenarios/cli/files-extended.sh+++ b/tests/e2e/scenarios/cli/files-extended.sh@@ -24,6 +24,7 @@ end_test# ─────────────────────────────────────────────────────────────────start_test "pinchtab screenshot -q 10"+pt_ok nav "${FIXTURES_URL}/index.html"pt_ok screenshot -q 10 -o /tmp/e2e-lowq.jpgrm -f /tmp/e2e-lowq.jpgdiff --git a/tests/tools/runner/internal/e2e/e2e_test.go b/tests/tools/runner/internal/e2e/e2e_test.goindex 80792477..6e27681a 100644--- a/tests/tools/runner/internal/e2e/e2e_test.go+++ b/tests/tools/runner/internal/e2e/e2e_test.go@@ -447,6 +447,97 @@ func TestWriteGitHubActionsMetadataAddsRunnerFailureWithoutSuiteResults(t *testi}}+func TestBuildSharedStackRetriesNoCacheOnBuildKitSnapshotFailure(t *testing.T) {+ tmp := t.TempDir()+ callsPath := filepath.Join(tmp, "calls.txt")+ scriptPath := filepath.Join(tmp, "compose.sh")+ t.Setenv("CALLS_FILE", callsPath)++ script := `#!/bin/sh+printf '%s\n' "$*" >> "$CALLS_FILE"+case "$*" in+ *"build --no-cache"*)+ exit 0+ ;;+ *"build"*)+ echo "failed to solve: failed to stat active key during commit: snapshot abc does not exist: not found" >&2+ exit 17+ ;;+esac+exit 0+`+ if err := os.WriteFile(scriptPath, []byte(script), 0o755); err != nil {+ t.Fatal(err)+ }++ var stdout, stderr bytes.Buffer+ r := &Runner{+ stdout: &stdout,+ stderr: &stderr,+ repoRoot: tmp,+ compose: []string{scriptPath},+ logsMode: "hide",+ }++ if code := r.buildSharedStack("compose.yml"); code != 0 {+ t.Fatalf("buildSharedStack returned %d, stderr: %s", code, stderr.String())+ }+ calls, err := os.ReadFile(callsPath)+ if err != nil {+ t.Fatal(err)+ }+ for _, want := range []string{+ "-f compose.yml build",+ "-f compose.yml build --no-cache",+ } {+ if !strings.Contains(string(calls), want) {+ t.Fatalf("expected compose call %q, got:\n%s", want, calls)+ }+ }+ if !strings.Contains(stdout.String(), "retrying shared-stack build with --no-cache") {+ t.Fatalf("stdout should mention retry, got:\n%s", stdout.String())+ }+}++func TestBuildSharedStackDoesNotRetryNonCacheFailure(t *testing.T) {+ tmp := t.TempDir()+ callsPath := filepath.Join(tmp, "calls.txt")+ scriptPath := filepath.Join(tmp, "compose.sh")+ t.Setenv("CALLS_FILE", callsPath)++ script := `#!/bin/sh+printf '%s\n' "$*" >> "$CALLS_FILE"+echo "real build error" >&2+exit 23+`+ if err := os.WriteFile(scriptPath, []byte(script), 0o755); err != nil {+ t.Fatal(err)+ }++ var stdout, stderr bytes.Buffer+ r := &Runner{+ stdout: &stdout,+ stderr: &stderr,+ repoRoot: tmp,+ compose: []string{scriptPath},+ logsMode: "hide",+ }++ if code := r.buildSharedStack("compose.yml"); code != 23 {+ t.Fatalf("buildSharedStack returned %d, want 23; stderr: %s", code, stderr.String())+ }+ calls, err := os.ReadFile(callsPath)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Count(string(calls), "build") != 1 {+ t.Fatalf("non-cache failure should not retry, calls:\n%s", calls)+ }+ if strings.Contains(stdout.String(), "--no-cache") {+ t.Fatalf("stdout should not mention no-cache retry, got:\n%s", stdout.String())+ }+}+func TestStructuredEventTeeFiltersHumanOutputOnly(t *testing.T) {var human, log bytes.Buffertee := &structuredEventTee{human: &human, log: &log}diff --git a/tests/tools/runner/internal/e2e/runner.go b/tests/tools/runner/internal/e2e/runner.goindex de4a5899..5865db0a 100644--- a/tests/tools/runner/internal/e2e/runner.go+++ b/tests/tools/runner/internal/e2e/runner.go@@ -568,13 +568,39 @@ func (r *Runner) planSuites(defs []suiteDef) ([]suitePlan, int) {}func (r *Runner) bringUpSharedStack(composeFile string, services []string) int {- if code := r.runLoggedCommand("building shared-stack images", stackOutput, r.composeArgs(composeFile, "build")); code != 0 {+ if code := r.buildSharedStack(composeFile); code != 0 {return code}args := append([]string{"up", "-d"}, services...)return r.runLoggedCommand("starting shared stack", stackOutput, r.composeArgs(composeFile, args...))}+func (r *Runner) buildSharedStack(composeFile string) int {+ code := r.runLoggedCommand("building shared-stack images", stackOutput, r.composeArgs(composeFile, "build"))+ if code == 0 {+ return 0+ }+ if !r.stackOutputHasBuildKitCacheFailure() {+ return code+ }+ _, _ = fmt.Fprintln(r.stdout, " build cache looked stale; retrying shared-stack build with --no-cache...")+ return r.runLoggedCommand("rebuilding shared-stack images without cache", stackOutput, r.composeArgs(composeFile, "build", "--no-cache"))+}++func (r *Runner) stackOutputHasBuildKitCacheFailure() bool {+ data, err := os.ReadFile(filepath.Join(r.repoRoot, stackOutput))+ if err != nil {+ return false+ }+ return isBuildKitCacheFailureLog(string(data))+}++func isBuildKitCacheFailureLog(log string) bool {+ log = strings.ToLower(log)+ return strings.Contains(log, "failed to stat active key during commit") ||+ (strings.Contains(log, "snapshot") && strings.Contains(log, "does not exist"))+}+func (r *Runner) restartSharedStack(composeFile string, services []string) int {args := append([]string{"restart"}, services...)return r.runLoggedCommand("restarting shared stack", stackOutput, r.composeArgs(composeFile, args...))