High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: a frame-scoped snapshot and text return child content under the parent's title and URL, with no field disclosing the scope (PIN-208)
Luigi Agosti2000e76f2db4
diff --git a/docs/endpoints.md b/docs/endpoints.mdindex f5c816bb..bfea0ca9 100644--- a/docs/endpoints.md+++ b/docs/endpoints.md@@ -260,6 +260,44 @@ cells stay two fields rather than one number.`/text` is also frame-aware. `frameId` targets a specific iframe for a one-shotread; otherwise the endpoint inherits the tab's current `/frame` scope.+### The `frame` Disclosure On Scoped Reads++A `/frame` scope is per-tab server state, not a per-request argument: it survives every+later command until something clears it, so the caller who reads a scoped tab is often not+the one who scoped it. `/snapshot` and `/text` therefore publish the frame they were served+from:++```json+"frame": {+ "frameId": "886601397BFA0B332880152438BD0153",+ "frameUrl": "http://127.0.0.1:18798/inner.html",+ "frameName": "payment-frame",+ "frameTitle": "Inner",+ "ownerRef": "e3"+}+```++- The key is **absent** on a whole-document read, so nothing changes for an unscoped caller.+- `frameUrl` and `frameTitle` are read from the frame at request time and are what the+ returned content belongs to; a frame that navigated since the scope was set reports where+ it is now.+- Top-level `url` and `title` keep their meaning in every response, scoped or not: they are+ the TAB's document. They are never re-pointed at the frame — a field that meant one thing+ usually and another under invisible state is the defect this disclosure exists to remove.+- `format=compact` and `format=text` carry the same fact in the header, as+ `# Outer | http://127.0.0.1:18798/ | frame e3 | 3 nodes`. The marker names the owner ref+ when one is known, because that is the handle `POST /frame` takes as a `target`; a raw+ frame id is not. Without a known ref it names a shortened frame id.+- The object is the one `GET /frame` returns under `frame`, plus `frameTitle`.++`/capture` reports the same frame id as `epoch.frameId`. That key is unchanged and stays+part of the epoch contract — it pairs a capture with the DOM epoch it was taken against+rather than disclosing a scope — so the two carry the same value under different contracts.++`/html` and `/styles` already disclose their frame as a top-level `frameId`, and their `url`+and `title` come from the frame's own document rather than the tab's, so a scoped read there+was never attributed to the parent.+Find body fields:- `query`diff --git a/internal/handlers/frame.go b/internal/handlers/frame.goindex be3260dd..a455f1a3 100644--- a/internal/handlers/frame.go+++ b/internal/handlers/frame.go@@ -44,6 +44,77 @@ func (h *Handlers) selectorFrameID(tabID string) string {return scope.FrameID}+// frameDisclosure is what a read publishes when the tab is frame-scoped. The scope is+// per-tab server state that outlives the caller who set it, so a reader who did not set it+// — a later turn, or a different caller on a shared tab — otherwise sees child content under+// the parent's title and url with nothing in the payload to say so.+//+// It is the scope object /frame already returns plus the frame's live title, so the wire has+// one spelling of this value rather than a second shape under the same key.+type frameDisclosure struct {+ bridge.FrameScope+ FrameTitle string `json:"frameTitle,omitempty"`+}++// frameIdentityScript reads the frame's own identity at read time. The stored scope carries+// the url the frame had when the scope was set, and a frame that navigated since would have+// the read attributed to a document it no longer holds — which is the defect one level down.+const frameIdentityScript = `({title: document.title || "", url: String(location.href)})`++// frameDisclosureFor answers "what frame was this read served from", nil for a whole-document+// read so an unscoped payload gains nothing. frameID is the frame the caller ALREADY resolved+// and read through, so the disclosure cannot describe a scope the read did not use; the+// stored scope is consulted only to name that frame, through currentFrameScope, the accessor+// the scoping itself goes through. A read scoped by an explicit ?frameId= is disclosed the+// same way, with whatever the stored scope knows about that frame when the two agree.+func (h *Handlers) frameDisclosureFor(ctx context.Context, tabID, frameID string) *frameDisclosure {+ if frameID == "" {+ return nil+ }+ scope := bridge.FrameScope{FrameID: frameID}+ if stored, ok := h.currentFrameScope(tabID); ok && stored.FrameID == frameID {+ scope = stored+ }+ disclosure := &frameDisclosure{FrameScope: scope}+ var identity struct {+ Title string `json:"title"`+ URL string `json:"url"`+ }+ if err := h.Bridge.EvaluateInFrame(ctx, frameID, frameIdentityScript, &identity, bridge.EvalOpts{}); err == nil {+ disclosure.FrameTitle = identity.Title+ if identity.URL != "" {+ disclosure.FrameURL = identity.URL+ }+ }+ return disclosure+}++// marker is the short form the plain-text headers carry. It prefers the owner ref because+// that is the handle `pinchtab frame <target>` accepts — a raw frame id is not a target it+// resolves — so a reader who spots the marker can act on it.+func (d *frameDisclosure) marker() string {+ if d == nil {+ return ""+ }+ if d.OwnerRef != "" {+ return "frame " + d.OwnerRef+ }+ id := d.FrameID+ if len(id) > 12 {+ id = id[:12] + "…"+ }+ return "frame " + id+}++// attach publishes the disclosure on a response map. Absent when unscoped: the third+// acceptance criterion is that nothing new appears in the common case.+func (d *frameDisclosure) attach(payload map[string]any) map[string]any {+ if d != nil {+ payload["frame"] = d+ }+ return payload+}+func (h *Handlers) resolveSelectorNodeID(ctx context.Context, tabID, raw string) (int64, error) {return h.resolveSelectorNodeIDInFrame(ctx, tabID, raw, "")}diff --git a/internal/handlers/frame_disclosure_test.go b/internal/handlers/frame_disclosure_test.gonew file mode 100644index 00000000..96ebe04b--- /dev/null+++ b/internal/handlers/frame_disclosure_test.go@@ -0,0 +1,335 @@+package handlers++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/testbrowser"+)++// frameIdentityBridge answers the in-frame identity read, which is how the disclosure learns+// what the content it is describing actually belongs to.+type frameIdentityBridge struct {+ *mockBridge+ askedFrameID string+ title, url string+ fail bool+}++func (b *frameIdentityBridge) EvaluateInFrame(_ context.Context, frameID string, _ string, result any, _ bridge.EvalOpts) error {+ b.askedFrameID = frameID+ if b.fail {+ return context.Canceled+ }+ payload, err := json.Marshal(map[string]string{"title": b.title, "url": b.url})+ if err != nil {+ return err+ }+ return json.Unmarshal(payload, result)+}++func newScopedHandlers(t *testing.T, scope bridge.FrameScope, identity *frameIdentityBridge) *Handlers {+ t.Helper()+ mb := &mockBridge{frameScopes: map[string]bridge.FrameScope{"tab1": scope}}+ identity.mockBridge = mb+ return New(identity, &config.RuntimeConfig{}, nil, nil, nil)+}++// The common case must gain nothing: an unscoped read has no frame to disclose, and a payload+// that grew a key for every whole-document read would be a change to every caller.+func TestFrameDisclosureIsAbsentForAWholeDocumentRead(t *testing.T) {+ h := newScopedHandlers(t, bridge.FrameScope{}, &frameIdentityBridge{})++ if got := h.frameDisclosureFor(context.Background(), "tab1", ""); got != nil {+ t.Errorf("frameDisclosureFor = %+v, want nil for an unscoped read", got)+ }+ if got := (*frameDisclosure)(nil).attach(map[string]any{"url": "u"}); len(got) != 1 {+ t.Errorf("attach added %v to an unscoped payload", got)+ }+ if marker := (*frameDisclosure)(nil).marker(); marker != "" {+ t.Errorf("marker = %q, want empty for an unscoped read", marker)+ }+}++// The disclosure has to carry the frame's OWN url and title: the complaint this closes is+// attribution, and an id alone does not tell a reader which document the content came from.+func TestFrameDisclosureCarriesTheFramesOwnIdentity(t *testing.T) {+ identity := &frameIdentityBridge{title: "Inner", url: "http://127.0.0.1:1/inner.html"}+ h := newScopedHandlers(t, bridge.FrameScope{+ FrameID: "frame-1",+ FrameURL: "http://127.0.0.1:1/stale.html",+ FrameName: "payment",+ OwnerRef: "e3",+ }, identity)++ got := h.frameDisclosureFor(context.Background(), "tab1", "frame-1")+ if got == nil {+ t.Fatal("a scoped read disclosed nothing")+ }+ if identity.askedFrameID != "frame-1" {+ t.Errorf("the identity was read in frame %q, want the frame the read was served from", identity.askedFrameID)+ }+ if got.FrameTitle != "Inner" {+ t.Errorf("frameTitle = %q, want the frame's own title", got.FrameTitle)+ }+ // The live url wins over the stored one: the scope records the url the frame had when it+ // was set, and a frame that navigated since would be attributed to a document it no+ // longer holds.+ if got.FrameURL != "http://127.0.0.1:1/inner.html" {+ t.Errorf("frameUrl = %q, want the frame's url at read time", got.FrameURL)+ }+ if got.OwnerRef != "e3" || got.FrameName != "payment" {+ t.Errorf("disclosure lost what the stored scope knows: %+v", got)+ }+}++// A cross-origin or torn-down frame cannot be read. The disclosure is still the honest half+// of the answer — the read WAS scoped — so it is published with what the scope knows.+func TestFrameDisclosureSurvivesAFrameItCannotRead(t *testing.T) {+ h := newScopedHandlers(t, bridge.FrameScope{FrameID: "frame-1", FrameURL: "http://stored/"},+ &frameIdentityBridge{fail: true})++ got := h.frameDisclosureFor(context.Background(), "tab1", "frame-1")+ if got == nil {+ t.Fatal("an unreadable frame suppressed the disclosure entirely, so the read looks like a whole-document one")+ }+ if got.FrameURL != "http://stored/" || got.FrameTitle != "" {+ t.Errorf("disclosure = %+v, want the stored url and no invented title", got)+ }+}++// The header is the surface the CLI prints, so this is where a scoped read becomes visible to+// a human reading a terminal. url and title keep meaning the TAB's document in both.+func TestSnapshotHeadersMarkAScopedReadAndLeaveAnUnscopedOneAlone(t *testing.T) {+ const title, pageURL = "Outer", "http://127.0.0.1:18798/"+ scope := &frameDisclosure{FrameScope: bridge.FrameScope{FrameID: "886601397BFA0B332880152438BD0153", OwnerRef: "e3"}}++ unscopedCompact := snapshotCompactHeader(title, pageURL, 7, nil)+ if unscopedCompact != "# Outer | http://127.0.0.1:18798/ | 7 nodes" {+ t.Errorf("an unscoped compact header changed shape: %q", unscopedCompact)+ }+ scopedCompact := snapshotCompactHeader(title, pageURL, 3, scope)+ if scopedCompact == unscopedCompact {+ t.Error("the two headers are identical, so a scoped read is indistinguishable from a whole-document one")+ }+ if !strings.Contains(scopedCompact, "frame e3") {+ t.Errorf("scoped compact header = %q, want it to name the frame", scopedCompact)+ }+ if !strings.HasPrefix(scopedCompact, "# Outer | http://127.0.0.1:18798/ |") {+ t.Errorf("scoped compact header re-pointed title or url at the frame: %q", scopedCompact)+ }++ unscopedText := snapshotTextHeader(title, pageURL, 7, nil)+ if unscopedText != "# Outer\n# http://127.0.0.1:18798/\n# 7 nodes" {+ t.Errorf("an unscoped text header changed shape: %q", unscopedText)+ }+ if !strings.Contains(snapshotTextHeader(title, pageURL, 3, scope), "# frame e3\n") {+ t.Errorf("scoped text header does not name the frame: %q", snapshotTextHeader(title, pageURL, 3, scope))+ }+}++// The owner ref is preferred because it is the handle `pinchtab frame <target>` accepts; a+// raw frame id is not a target that command resolves, so a header carrying only the id names+// something the reader cannot act on. Without a known ref the id is still better than silence.+func TestTheHeaderMarkerPrefersTheHandleTheFrameCommandAccepts(t *testing.T) {+ withRef := &frameDisclosure{FrameScope: bridge.FrameScope{FrameID: "886601397BFA0B33", OwnerRef: "e3"}}+ if got := withRef.marker(); got != "frame e3" {+ t.Errorf("marker = %q, want the owner ref", got)+ }+ withoutRef := &frameDisclosure{FrameScope: bridge.FrameScope{FrameID: "886601397BFA0B332880152438BD0153"}}+ got := withoutRef.marker()+ if !strings.HasPrefix(got, "frame 886601397BFA") {+ t.Errorf("marker = %q, want it to name the frame id", got)+ }+ if len(got) > len("frame ")+16 {+ t.Errorf("marker = %q, want the id shortened for a header line", got)+ }+}++// The text envelope is the other half of the reported defect. Two reads of the same tab and+// url differ in the disclosure, not only in what the text says.+func TestTextEnvelopeDisclosesTheFrameOnlyWhenScoped(t *testing.T) {+ extraction := textExtraction{Text: "inner frame paragraph", Mode: extractionRaw}++ unscoped := decodeTextEnvelope(t, scopedTextResponseRecorder(t, extraction, -1, "", nil))+ if _, ok := unscoped["frame"]; ok {+ t.Errorf("an unscoped text read published a frame key: %v", unscoped["frame"])+ }++ scoped := decodeTextEnvelope(t, scopedTextResponseRecorder(t, extraction, -1, "", &frameDisclosure{+ FrameScope: bridge.FrameScope{FrameID: "frame-1", FrameURL: "http://127.0.0.1:1/inner.html", OwnerRef: "e3"},+ FrameTitle: "Inner",+ }))+ frame, ok := scoped["frame"].(map[string]any)+ if !ok {+ t.Fatalf("a scoped text read published no frame object: %v", scoped)+ }+ for key, want := range map[string]string{+ "frameId": "frame-1",+ "frameUrl": "http://127.0.0.1:1/inner.html",+ "frameTitle": "Inner",+ "ownerRef": "e3",+ } {+ if got, _ := frame[key].(string); got != want {+ t.Errorf("frame[%q] = %q, want %q", key, got, want)+ }+ }+ // The tab document keeps its own fields: that is what stops `url` meaning two things+ // depending on state a reader cannot see.+ if scoped["url"] != unscoped["url"] || scoped["title"] != unscoped["title"] {+ t.Errorf("a scoped read changed the tab's url/title: %v vs %v", scoped["url"], unscoped["url"])+ }+}++// outerFixtureHTML and innerFixtureHTML mirror the reported fixture: two documents that are+// distinguishable only by their content, so a read attributed to the wrong one is visible.+const outerFixtureHTML = `<!doctype html><html><head><title>Outer</title></head><body>+<h1>OuterHeading</h1><input id="oh" value="outerval"><button>OuterBtn</button>+<iframe id="f" src="/inner.html" width="300" height="200"></iframe>+</body></html>`++const innerFixtureHTML = `<!doctype html><html><head><title>Inner</title></head><body>+<h1>InnerHeading</h1><input value="innerval"><button>InnerBtn</button>+<p>Inner frame paragraph text that is unique to the child document.</p>+</body></html>`++func newFrameDisclosureFixture(t *testing.T) (*Handlers, string, string) {+ t.Helper()+ chromePath := testbrowser.Path(t)++ mux := http.NewServeMux()+ mux.HandleFunc("/inner.html", func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "text/html; charset=utf-8")+ _, _ = w.Write([]byte(innerFixtureHTML))+ })+ mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "text/html; charset=utf-8")+ _, _ = w.Write([]byte(outerFixtureHTML))+ })+ server := httptest.NewServer(mux)+ t.Cleanup(server.Close)++ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(+ chromedp.DefaultExecAllocatorOptions[:],+ chromedp.ExecPath(chromePath),+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),+ chromedp.Flag("headless", true),+ chromedp.Flag("no-sandbox", true),+ )...)+ ctx, cancelBrowser := chromedp.NewContext(alloc)+ ctx, cancelTimeout := context.WithTimeout(ctx, 30*time.Second)+ t.Cleanup(func() {+ cancelTimeout()+ cancelBrowser()+ cancelAlloc()+ })++ if err := chromedp.Run(ctx, chromedp.Navigate(server.URL), chromedp.WaitVisible("#f", chromedp.ByID)); err != nil {+ t.Fatal(err)+ }++ cfg := &config.RuntimeConfig{ActionTimeout: 10 * time.Second, DefaultBrowser: config.BrowserChrome, StateDir: t.TempDir()}+ b := bridge.New(context.Background(), ctx, cfg)+ b.RegisterTab("tab-frame", ctx)+ return New(b, cfg, nil, nil, nil), "tab-frame", server.URL+}++func snapshotBody(t *testing.T, h *Handlers, tabID, format string) string {+ t.Helper()+ req := httptest.NewRequest("GET", "/snapshot?tabId="+tabID+"&format="+format, nil)+ w := httptest.NewRecorder()+ h.HandleSnapshot(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("snapshot (%s): status %d body=%s", format, w.Code, w.Body.String())+ }+ return w.Body.String()+}++// The reported defect, end to end: the same tab at the same url read twice, once scoped and+// once not. Before this change the two answers differed only in the node count, which reads+// as a page change rather than a fragment.+func TestAScopedReadIsDistinguishableFromAWholeDocumentRead(t *testing.T) {+ h, tabID, pageURL := newFrameDisclosureFixture(t)++ unscopedHeader := snapshotBody(t, h, tabID, "compact")+ if !strings.Contains(unscopedHeader, "OuterHeading") || !strings.Contains(unscopedHeader, "InnerHeading") {+ t.Fatalf("the unscoped read did not cover both documents: %s", unscopedHeader)+ }+ if header := strings.SplitN(unscopedHeader, "\n", 2)[0]; strings.Contains(header, "frame ") {+ t.Errorf("an unscoped read claims a frame scope: %s", header)+ }++ frameReq := httptest.NewRequest("POST", "/frame?tabId="+tabID, strings.NewReader(`{"target":"inner.html"}`))+ frameRes := httptest.NewRecorder()+ h.HandleFrame(frameRes, frameReq)+ if frameRes.Code != http.StatusOK {+ t.Fatalf("frame scope: status %d body=%s", frameRes.Code, frameRes.Body.String())+ }++ scopedHeader := snapshotBody(t, h, tabID, "compact")+ if strings.Contains(scopedHeader, "OuterHeading") {+ t.Fatalf("the scope did not take effect, so this test proves nothing: %s", scopedHeader)+ }+ if !strings.Contains(strings.SplitN(scopedHeader, "\n", 2)[0], "frame ") {+ t.Errorf("the scoped header does not disclose the scope: %s", scopedHeader)+ }+ if !strings.Contains(scopedHeader, pageURL) {+ t.Errorf("the scoped header stopped reporting the tab's url: %s", scopedHeader)+ }++ var envelope map[string]any+ if err := json.Unmarshal([]byte(snapshotBody(t, h, tabID, "")), &envelope); err != nil {+ t.Fatalf("decode scoped snapshot: %v", err)+ }+ if envelope["title"] != "Outer" || envelope["url"] != pageURL+"/" && envelope["url"] != pageURL {+ t.Errorf("a scoped read re-pointed the tab's own url/title: url=%v title=%v", envelope["url"], envelope["title"])+ }+ frame, ok := envelope["frame"].(map[string]any)+ if !ok {+ t.Fatalf("the scoped snapshot published no frame object: %v", envelope)+ }+ if frame["frameTitle"] != "Inner" {+ t.Errorf("frame.frameTitle = %v, want the child document's title", frame["frameTitle"])+ }+ if url, _ := frame["frameUrl"].(string); !strings.HasSuffix(url, "/inner.html") {+ t.Errorf("frame.frameUrl = %v, want the child document's url", frame["frameUrl"])+ }+ if id, _ := frame["frameId"].(string); id == "" {+ t.Error("frame.frameId is empty, so the disclosure names no frame")+ }++ // /text is the other endpoint the card measured, and it reaches the disclosure through a+ // different path — its frame comes from resolveTargetFrameID, not from the snapshot's+ // scope lookup — so the wiring is asserted here rather than inferred from the snapshot.+ textReq := httptest.NewRequest("GET", "/text?tabId="+tabID, nil)+ textRes := httptest.NewRecorder()+ h.HandleText(textRes, textReq)+ if textRes.Code != http.StatusOK {+ t.Fatalf("text: status %d body=%s", textRes.Code, textRes.Body.String())+ }+ var textEnvelope map[string]any+ if err := json.Unmarshal(textRes.Body.Bytes(), &textEnvelope); err != nil {+ t.Fatalf("decode scoped text: %v", err)+ }+ if text, _ := textEnvelope["text"].(string); !strings.Contains(text, "Inner frame paragraph") {+ t.Fatalf("the scoped text read did not return the child document: %q", text)+ }+ textFrame, ok := textEnvelope["frame"].(map[string]any)+ if !ok {+ t.Fatalf("the scoped text read published no frame object: %v", textEnvelope)+ }+ if textFrame["frameTitle"] != "Inner" {+ t.Errorf("text frame.frameTitle = %v, want the child document's title", textFrame["frameTitle"])+ }+ if textEnvelope["title"] != "Outer" {+ t.Errorf("the scoped text read re-pointed the tab's title: %v", textEnvelope["title"])+ }+}diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex ed43617a..346b4194 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -113,6 +113,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {var scopeNodeID int64frameScope := h.selectorFrameID(resolvedTabID)+ scopeInfo := h.frameDisclosureFor(tCtx, resolvedTabID, frameScope)ghostRoute := snapChromeRoute != nil && snapChromeRoute.UsedBrowser == config.BrowserGhostChromevar modalOpen boolif frameScope != "" || selector != "" || !ghostRoute {@@ -250,19 +251,19 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {switch format {case "text":ext = ".txt"- textContent := fmt.Sprintf("# %s\n# %s\n# %d nodes\n# %s\n\n%s",- title, url, len(flat), time.Now().Format(time.RFC3339),+ textContent := fmt.Sprintf("%s\n# %s\n\n%s",+ snapshotTextHeader(title, url, len(flat), scopeInfo), time.Now().Format(time.RFC3339),bridge.FormatSnapshotText(flat))content = []byte(textContent)case "yaml":ext = ".yaml"- data := map[string]any{+ data := scopeInfo.attach(map[string]any{"url": url,"title": title,"timestamp": time.Now().Format(time.RFC3339),"nodes": flat,"count": len(flat),- }+ })if doDiff && prevNodes != nil {added, changed, removed := bridge.DiffSnapshot(prevNodes, flat)data["diff"] = true@@ -284,13 +285,13 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {}default:ext = ".json"- data := map[string]any{+ data := scopeInfo.attach(map[string]any{"url": url,"title": title,"timestamp": time.Now().Format(time.RFC3339),"nodes": flat,"count": len(flat),- }+ })if doDiff && prevNodes != nil {added, changed, removed := bridge.DiffSnapshot(prevNodes, flat)data["diff"] = true@@ -361,8 +362,8 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {if format == "compact" {w.Header().Set("Content-Type", "text/plain; charset=utf-8")w.WriteHeader(200)- _, _ = fmt.Fprintf(w, "# %s | %s | %d nodes | +%d ~%d -%d",- title, url, len(flat), len(added), len(changed), len(removed))+ _, _ = fmt.Fprintf(w, "%s | +%d ~%d -%d",+ snapshotCompactHeader(title, url, len(flat), scopeInfo), len(added), len(changed), len(removed))if truncated {_, _ = fmt.Fprintf(w, " (truncated to ~%d tokens)", maxTokens)}@@ -375,7 +376,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {return}- httpx.JSON(w, 200, map[string]any{+ httpx.JSON(w, 200, scopeInfo.attach(map[string]any{"url": url,"title": title,"route": snapChromeRoute,@@ -389,7 +390,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {"removed": len(removed),"total": len(flat),},- })+ }))return}@@ -397,7 +398,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {case "compact":w.Header().Set("Content-Type", "text/plain; charset=utf-8")w.WriteHeader(200)- _, _ = fmt.Fprintf(w, "# %s | %s | %d nodes", title, url, len(flat))+ _, _ = fmt.Fprintf(w, "%s", snapshotCompactHeader(title, url, len(flat), scopeInfo))if truncated {_, _ = fmt.Fprintf(w, " (truncated to ~%d tokens)", maxTokens)}@@ -413,7 +414,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {case "text":w.Header().Set("Content-Type", "text/plain; charset=utf-8")w.WriteHeader(200)- _, _ = fmt.Fprintf(w, "# %s\n# %s\n# %d nodes\n", title, url, len(flat))+ _, _ = fmt.Fprintf(w, "%s\n", snapshotTextHeader(title, url, len(flat), scopeInfo))if scopedEmptyHint != "" {_, _ = fmt.Fprintf(w, "# hint: %s\n", scopedEmptyHint)}@@ -424,12 +425,12 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {}_, _ = w.Write([]byte(content))case "yaml":- data := map[string]any{+ data := scopeInfo.attach(map[string]any{"url": url,"title": title,"nodes": flat,"count": len(flat),- }+ })if scopedEmptyHint != "" {data["hint"] = scopedEmptyHint}@@ -442,13 +443,13 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {w.WriteHeader(200)_, _ = w.Write(yamlContent)default:- resp := map[string]any{+ resp := scopeInfo.attach(map[string]any{"url": url,"title": title,"route": snapChromeRoute,"nodes": flat,"count": len(flat),- }+ })if truncated {resp["truncated"] = trueresp["maxTokens"] = maxTokens@@ -467,6 +468,27 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {}}+// snapshotCompactHeader and snapshotTextHeader are the one place each header shape is built,+// so the scope marker cannot reach three of the four sites that print one. The marker keeps+// title and url meaning what they always meant — the TAB's document — and adds the fact that+// the nodes below came from a frame inside it; re-pointing url at the frame would make one+// field mean two things depending on invisible state, which is the defect being fixed.+func snapshotCompactHeader(title, url string, count int, scope *frameDisclosure) string {+ parts := []string{"# " + title, url}+ if marker := scope.marker(); marker != "" {+ parts = append(parts, marker)+ }+ return strings.Join(append(parts, fmt.Sprintf("%d nodes", count)), " | ")+}++func snapshotTextHeader(title, url string, count int, scope *frameDisclosure) string {+ header := fmt.Sprintf("# %s\n# %s\n", title, url)+ if marker := scope.marker(); marker != "" {+ header += "# " + marker + "\n"+ }+ return header + fmt.Sprintf("# %d nodes", count)+}+func (h *Handlers) scopedSnapshotNodes(ctx context.Context,tabID, frameScope, rawSelector string,diff --git a/internal/handlers/text.go b/internal/handlers/text.goindex 63b6459f..cd037d93 100644--- a/internal/handlers/text.go+++ b/internal/handlers/text.go@@ -106,10 +106,11 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {httpx.Error(w, status, err)return}+ scopeInfo := h.frameDisclosureFor(tCtx, resolvedTabID, targetFrameID)if selectorParam != "" || refParam != "" {- h.writeElementTextResponse(w, r, tCtx, text)+ h.writeElementTextResponse(w, r, tCtx, text, scopeInfo)} else {- h.writeTextResponse(w, r, tCtx, extraction, maxChars, format, textRoute)+ h.writeTextResponse(w, r, tCtx, extraction, maxChars, format, textRoute, scopeInfo)}return}@@ -117,15 +118,15 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {}// writeElementTextResponse writes an already scope-validated element read.-func (h *Handlers) writeElementTextResponse(w http.ResponseWriter, r *http.Request, tCtx context.Context, text string) {+func (h *Handlers) writeElementTextResponse(w http.ResponseWriter, r *http.Request, tCtx context.Context, text string, scope *frameDisclosure) {url, _ := h.Bridge.CurrentURL(tCtx)title, _ := h.Bridge.CurrentTitle(tCtx)h.recordResolvedURL(r, url)- httpx.JSON(w, 200, map[string]any{+ httpx.JSON(w, 200, scope.attach(map[string]any{"url": url,"title": title,"text": text,- })+ }))}const rawTextScript = `document.body.innerText`@@ -262,7 +263,7 @@ func truncateChars(s string, limit int) (string, bool) {// writeTextResponse truncates, IDPI-scans, and writes the document text as// plain text (format text/plain) or the JSON envelope.-func (h *Handlers) writeTextResponse(w http.ResponseWriter, r *http.Request, tCtx context.Context, extraction textExtraction, maxChars int, format string, route *browserops.RouteMetadata) {+func (h *Handlers) writeTextResponse(w http.ResponseWriter, r *http.Request, tCtx context.Context, extraction textExtraction, maxChars int, format string, route *browserops.RouteMetadata, scope *frameDisclosure) {text := extraction.Texttruncated := falseif maxChars > -1 {@@ -290,7 +291,7 @@ func (h *Handlers) writeTextResponse(w http.ResponseWriter, r *http.Request, tCtreturn}- resp := map[string]any{+ resp := scope.attach(map[string]any{"url": url,"title": title,"text": text,@@ -298,7 +299,7 @@ func (h *Handlers) writeTextResponse(w http.ResponseWriter, r *http.Request, tCt"route": route,"extraction": extraction.Mode,"textLength": utf8.RuneCountInString(text),- }+ })if extraction.RawKnown {resp["rawLength"] = extraction.RawLength}diff --git a/internal/handlers/text_test.go b/internal/handlers/text_test.goindex 0fea9b14..a828dfd3 100644--- a/internal/handlers/text_test.go+++ b/internal/handlers/text_test.go@@ -241,11 +241,18 @@ func TestReadabilityCollapsed_FloorKeepsShortPages(t *testing.T) {}func textResponseRecorder(t *testing.T, extraction textExtraction, maxChars int, format string) *httptest.ResponseRecorder {+ t.Helper()+ return scopedTextResponseRecorder(t, extraction, maxChars, format, nil)+}++// scopedTextResponseRecorder drives the same writer with a frame disclosure, which is the+// only difference a scoped read makes to this envelope.+func scopedTextResponseRecorder(t *testing.T, extraction textExtraction, maxChars int, format string, scope *frameDisclosure) *httptest.ResponseRecorder {t.Helper()h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)w := httptest.NewRecorder()r := httptest.NewRequest("GET", "/text", nil)- h.writeTextResponse(w, r, context.Background(), extraction, maxChars, format, nil)+ h.writeTextResponse(w, r, context.Background(), extraction, maxChars, format, nil, scope)if w.Code != http.StatusOK {t.Fatalf("status = %d body=%s", w.Code, w.Body.String())}