---
title: Scope the panel to a conversation
description: 'Tell the devtools panel which conversation and run to show: name it with data-scope or window.__WEFT__, or let the panel detect it from the page URL, a data-weft-scope marker or the Weft-Scope header your Go handler sets with package weft/scope.'
url: https://weftgo.dev/docs/observe/devtools/scope/
type: how-to
sources:
  - 'W11-tag3, v0.20.2: weft/studio/web/src/panel/element.ts:3102-3107 (the header''s figures one group, each whole or out of sight, the title giving way to none); weft/studio/web/src/panel/styles.ts:236-237 (.weft-hs); weft/CHANGELOG.md:18 (0.20.2)'
  - weft/scope/scope.go:1-40 (the string form with agent and tags; Parse's first segment; the flow as run metadata), 89-160 (Scope with Agent and Tags, IsZero, Equal, String, Parse)
  - 'weft/scope/flow_test.go:17-44 (TestFlowIsStampedAsRunMetadata: the handler''s scope, the request header, a run''s own option wins); weft/scope/example_test.go (ExampleWithFlow, ExampleScope_tags)'
  - 'weft/studio/web/src/panel/element.ts:1913-1938 (decide: rung order, 4b and the fallback read scope: none), 3420-3425 (the no-runs line names its rung); weft/studio/auth.go:146-163 (a tag scope under a public-id token: the intersection) — v0.20.2'
  - 'weft/studio/README.md:876-960 (the scope and the ladder: tags, agent, flow, the batch header, rung 4b, the footer''s scope words, the fallback''s lines)'
  - 'weft/CHANGELOG.md:46, 48 (0.20.0: tag, agent and flow scopes; the panel''s batch list), 45 (the footer''s rung, the explicit id with no runs), 61 (no-scope fallback), 79 (Scope no longer comparable; Parse''s first segment)'
  - weft/studio/README.md:867-886 (window.__WEFT__; the scope and what each field does)
  - 'weft/studio/README.md:929-957 (the detection ladder: precedence, the footer''s word, the rung table)'
  - weft/studio/README.md:960-970 (rung 3 trusts the DOM; data-weft-untrusted; data-detect=off)
  - 'weft/studio/README.md:971-1003 (rung 2: the fetch wrapper''s rules, narrowing, the path rule, the second look)'
  - 'weft/studio/README.md:1004-1036 (rung 3: the production rung, the observer, focus, light DOM only, route changes, explicit vs marker)'
  - weft/studio/README.md:1037-1049 (the scope switcher)
  - 'weft/studio/web/src/panel/element.ts:1586-1586 (choose: the pick held as chosen), 1638-1647 (focus into a marker drops it), 1862-1881 (a new explicit scope drops it; a new URL scope only with no explicit scope), 629-637 (conversationKey: the serialized scope without its run), 770-771 (chosen wins in scopeNow), 6048-6052 (shown with two known, or one known and the followed one not listed), 6066-6072 (● or ○; the disabled · not on the page entry, latest (dev))'
  - weft/studio/README.md:1050-1060 (the data-detect table)
  - 'weft/studio/README.md:1061-1077 (rung 4: the URL)'
  - 'weft/studio/README.md:1078-1097 (rung 5: the fallback, the agent= stream, the polls)'
  - 'weft/studio/web/src/panel/state.ts:169-170 (DEV_LIMIT 10), 1532 (no public id: runs?limit=10), 745-757 (the session narrows the listed turns)'
  - weft/studio/web/src/panel/element.ts:3553-3575 (no paging without a public id; the newest 10 runs — older ones are in Studio (⤢))
  - weft/studio/README.md:1472-1480 (a session-only scope resolved through GET /api/sessions/{id}/public_id)
  - 'weft/studio/README.md:1626-1663 (the scope header: scope.Header, scope.Set, the golden, CORS, the page URL stamp)'
  - 'weft/AGENTS.md:386-395 (block 7: data-scope, window.__WEFT__, the Weft-Scope header, the marker, data-detect, the URL, the fallback over agent=), 465-475 (block 7b: package weft/scope)'
  - weft/scope/scope.go:1-48 (package doc), 65 (HeaderName), 70 (PageURLKey), 89-98 (Scope), 101 (IsZero), 117 (String), 144 (Parse), 230 (Header), 257 (PageURLFromContext), 270 (PageURL), 319 (Set)
  - weft/scope/example_test.go:ExampleHeader, ExampleParse, ExampleScope_String, ExamplePageURLFromContext
  - weft/examples/studio-local/main.go:567 (scope.Header on /run), 666 (scope.Set with turn.RunID())
  - weft/studio/testdata/scope.golden.json
  - 'weft/scope/scope.go:89-98 (Scope: FlowID, json flow, no godoc of its own)'
  - 'weft/studio/web/src/panel/element.ts:631-637 (conversationKey keeps flow), 3018-3027 (the flow chip: carried, filters nothing yet), 3242-3282 (the switcher label names the flow)'
  - weft/studio/web/src/lib/scope.ts:1-12 (the string form), 19-28 (Scope), 33 (serializeScope), 53 (parseScope)
  - 'weft/studio/web/src/panel/config.ts:23-31 (the scope''s two spellings and window.__WEFT__), 118-122 (detectSetting), 431-551 (readConfig: data-scope before data-public-id per rung), 426-533 (URL_SCOPE_PARAM, urlScope), 537-568 (headerRungOn, markerRungOn)'
  - weft/studio/web/src/panel/detect.ts:1-38 (the header rung's rules), 42 (SCOPE_HEADER)
  - weft/studio/web/src/panel/markers.ts:1-21 (the marker rung's rules), 153 (MARKER_ATTR), 157 (UNTRUSTED_ATTR)
  - 'weft/studio/web/src/panel/main.ts:84-145 (the window.__WEFT__ watch: reassigning or setting scope/publicId rescopes)'
  - 'weft/studio/web/src/panel/element.ts:1357-1357 (the session lookup''s failures: the dev token, has no public id · unknown session, Studio did not answer the lookup), 3372-3380 (these runs carry no session id — not narrowed); weft/studio/web/src/panel/state.ts:1954-1959 (sessionUnrecorded: a session asked for and no listed turn carries a session id)'
  - weft/studio/web/src/panel/element.ts:506-512 (HOW_TO_SCOPE, the four fixes), 1309-1324 (scope(null) restores mount()'s scope), 1339-1342 (only scope() looks a session up), 1886-1887 (detectWord), 6478 (the footer's detect word, chained, fetch not restored)
  - 'weft/studio/web/src/npm/marker.ts:15-25 (HelperOptions; a string scope is a public id), 32-60 (attach: marker, mount only with endpoint or token, scope())'
  - weft/studio/web/src/npm/react.ts:17, vue.ts:18, svelte.ts:13 and 30 (the helpers)
  - weft/studio/web/npm/README.md:129-160 (Framework helpers)
  - weft/CHANGELOG.md:889 (scope.Header stamps weft.page_url), 1201 (a secret in a page path would travel), 2203 (the marker rung and the switcher), 2214 (the URL rung, the live fallback, the pill), 2288 (weft/scope), 2322 (the whole scope; rung 1 and rung 2), 2353 (data-public-id deprecated)
  - docs-site/examples/devtools/main_test.go:TestScopeHeader, TestScopeHeaderOrigin, TestParse, TestParseGolden
  - 'observed: Chromium (Playwright 1.62.0) against docs-site/examples/devtools and a scratch weft studio v0.17.0: the fallback line, then pub_demo from the first /chat response (detect: headers+markers), ?weft_scope= and #weft_scope= (detect: url+headers+markers), data-scope beating data-public-id, weft:scope, window.__WEFT__ and its reassignment, a data-weft-scope marker with one inside data-weft-untrusted ignored, data-detect=off (detect: off, the marker unread), and @weftgo/devtools mount() scoped by examples/devtools-vite''s marker'
---

# Scope the panel to a conversation

The panel follows one [scope](https://weftgo.dev/docs/reference/glossary/#scope): a conversation's [public id](https://weftgo.dev/docs/reference/glossary/#public-id), and optionally the session, flow and run inside it, written `pub_…;session=…;flow=…;run=…`, or a page of unrelated runs named by their agent and their run metadata, `;agent=…;tag.<k>=<v>` ([Tags, agents and flows](#name-a-batch-of-runs-by-tags-agent-or-flow)). Name it yourself with `data-scope` on the panel's tag or `window.__WEFT__`, or let the panel detect it: from the page URL, from a `data-weft-scope` attribute on your chat's element, or from the `Weft-Scope` header your chat handler sets with package [`scope`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope).

Name it on the tag:

```html
<script type="module" src="/studio/panel.js" data-weft data-scope="pub_demo"></script>
```

Or set it from Go, on the chat handler in `docs-site/examples/devtools/main.go`, so every response names the conversation it belongs to:

```go title="devtools/main.go"
mux.Handle("POST /chat", scope.Header(http.HandlerFunc(c.chat), func(r *http.Request) scope.Scope {
	return scope.Scope{PublicID: publicIDOf(r)}
}))
```

[devtools/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/devtools/main.go)

The public id is the one the conversation's session was created with, `thread.PublicID(id)`: its runs carry it as `weft.public_id`, and the panel lists them as the conversation's turns.

## The detection ladder

The panel takes the first scope it finds, in this order:

| Order | Rung | Where the scope comes from | When it is on |
|---|---|---|---|
| 1st | 1 · explicit | `data-scope`, `window.__WEFT__`, `scope()` / `mount({scope})` | always |
| 2nd | 4 · the page URL | `?weft_scope=…`, else `#weft_scope=…` | always |
| 3rd | 3 · DOM markers | `data-weft-scope="…"` on an element of the page | by default everywhere, except a page off loopback under a read-scoped panel token |
| 4th | 2 · response headers | the `Weft-Scope` header of the page's own `fetch` responses | by default only with the page and Studio on loopback, and no token or a dev token |
| 5th | 4b · a panel token's claims | a `weft_pt.` token's `public_id` claim and its `tags`, read as a hint (Studio still enforces the token) | when rungs 1 to 4 name nothing, under a panel token |
| — | 5 · the fallback | nothing names a scope: `no conversation detected on this page · how to scope`, over the newest runs | when nothing names one |

So a page given only `data-token` with a panel token lists exactly what that token can read: its conversation, or its batch.

The rungs are numbered in the order they were added; the order above is how deliberate each one is. Your page's own word comes first, then a link someone followed, then what the page shows passively. `data-detect` switches rungs 2 and 3 ([Detection switches](#detection-switches)); nothing turns rungs 1 and 4 off.

The panel's footer says in one word which rungs are installed: `detect: headers`, `detect: markers` or `detect: headers+markers`, led by `url` (`detect: url+headers+markers`) while it follows the URL's scope. With neither rung installed it reads `detect: off`, `detect: explicit` (rung 1 names the scope) or `detect: none`. Before it, the footer names the rung that chose the scope followed: `scope: explicit`, `scope: url`, `scope: marker`, `scope: header from /run` (the path of the response that carried it), `scope: switcher` (your pick) or `scope: none`. `scope: none` covers both the fallback and a scope read from a panel token's claims (rung 4b). An explicit or URL public id with no run in Studio reads "Studio has no runs for pub_… yet — check the id (scope: explicit)", or `(scope: url)`: it may be a wrong id.

What the panel does with each field of the scope:

- **The public id** selects the conversation.
- **`run`** pins the selected turn, and its live tail, to that run once; your clicks own the selection after that. A run that is not the conversation's reads `run r_… not in this conversation`.
- **`session`** narrows the turn list to that session's runs. Passed to `scope()`, a scope with a session and no public id (`;session=s_…`) is resolved through `GET /api/sessions/{id}/public_id`, which only setup A and the dev token may ask; under a panel token the panel says `session s_…: the session lookup needs the dev token`. While no public id is known, the list is the newest 10 runs, unpaged, and the session narrows within those 10 only ([The turn list](https://weftgo.dev/docs/observe/devtools/reading-runs/#the-turn-list)). Two more lines say when the session could not narrow anything:
  - `session s_…: these runs carry no session id — not narrowed`: none of the listed turns carries `weft.session.id` (plain `Generate` runs, not thread turns), so the list is shown whole;
  - `session s_…: Studio did not answer the lookup`: the `public_id` lookup failed for another reason than a 401, 403 or 404, such as a network error or a 5xx.
- **`flow`** narrows every read to the runs stamped with it: a flow is run metadata, `weft.flow`, which `scope.Header` stamps on the runs its handler starts ([Flows](#narrow-by-a-flow)). It shows as a `flow <id>` chip in the header and in the switcher's labels, and two scopes that differ only by `flow` count as two conversations there.

When more than one conversation is known (an explicit scope, the markers on the page, the scopes headers named), the header shows a switcher. It is a `<select aria-label="conversation">` listing up to 20 by public id and source (`explicit`, `url`, `marker`, `header`), with `●` (the live stream open) or `○` marking the one followed. Choosing one follows it and pins its run until focus next goes into a marker, the explicit scope changes, or, with no explicit scope, a new page-URL scope arrives (`?weft_scope=`, a `hashchange`).

The switcher also shows when only one conversation is known but the panel follows another that is no longer on the page. That one heads the list as a disabled entry that cannot be chosen again: its full scope string, `● pub_…;session=… · not on the page` (`latest (dev)` when none is followed), its dot `○` while the live stream is closed.

![A page with two conversations marked, order 4411 and ops watch, and the devtools panel docked beside them: its header's conversation switcher reads ● pub_acme_4411 · marker](https://weftgo.dev/docs/_astro/panel-scope-switcher.light.Bd61gMGO.webp)

*Two conversations marked on one page, order 4411 and ops watch: the panel header's switcher follows pub_acme_4411, found by its marker.*

When nothing names a scope (rung 5), "how to scope" opens one-line fixes, each with a copy button. The zero-code one comes first, `add ?weft_scope=pub_… to this page's URL (no code)`, then `data-scope` on the panel's tag (or `<weft-devtools>`), `scope()` from `@weftgo/devtools`, a `data-weft-scope` marker on the chat's element, and `scope.Header` on the app's handler. The fallback selects no run, sums no cost and groups its rows by agent. The panel lists the newest 10 runs meanwhile, with no paging: past them it says `the newest 10 runs — older ones are in Studio (⤢)`. That list follows `/api/live?agent=<agent of the newest run>`, so the agent your dev page runs streams live, and the list is still read every 30 s for other agents' runs. With no stream (no run listed yet, the stream gone, or a grant refused), a 10 s poll takes over while the dock is open and the page visible. In the fallback only the streamed agent's runs light the collapsed pill.

### Rung 1: explicit

Name the scope in its string form on the panel's `<script>` tag, on a `<weft-devtools>` element, or in a meta tag:

```html
<meta name="weft:scope" content="pub_demo;session=s_1">
```

A single-page app that switches conversations sets `window.__WEFT__` instead. The panel watches the global with a setter: reassigning it, or setting `scope` or `publicId` on the object, rescopes every connected panel. Script order does not matter; a value set before the panel loads is read the same way.

```js
window.__WEFT__ = { scope: "pub_demo;run=s_01M576FH50XX1CZQ3NMD59ZP57-t1" }
window.__WEFT__ = { publicId: "pub_other" }
```

Keep `data-weft` on the tag when it carries nothing else: it is how the panel finds its tag. From npm, [`scope(s)`](https://weftgo.dev/docs/observe/devtools/host-api/) and `mount({scope})` are rung 1 too; `scope(null)` undoes `scope()`: the panel goes back to the scope `mount()` named, else to the ladder.

At each source the panel reads `data-scope` first, then `data-public-id`. `data-public-id="pub_…"` (and `weft:public-id`) is still read, as the scope with only that public id, but it is deprecated: `data-scope` is the form, and wins when both are on one tag. `window.__WEFT__` is read only when no tag, element, meta tag or `mount()` names a scope.

### Rung 2: response headers

Your chat handler sets `Weft-Scope: pub_demo;run=…` on its responses ([The scope header](#the-scope-header)), and the panel reads it by wrapping `window.fetch`. This is a patch of a global of your page, so it is held to these rules:

- It reads the response's URL and its `Weft-Scope` header only: never a body, never a clone, and it sends nothing of its own.
- It reads same-origin responses, and a cross-origin one only when the page and the response are both on loopback (a dev server on `:5173` calling your app on `:8080`). Any other cross-origin response is ignored even when it exposes the header.
- It never reads the panel's own Studio requests.
- It is installed only once Studio has answered, so a panel whose Studio never answers never touches `fetch`.
- It chains to the `fetch` it found (the browser's own or another library's patch) and returns the same response or rejection; the footer adds `(chained)` when that `fetch` was not the browser's.
- It is put back exactly as found when the panel disconnects or the rung is turned off. If another library wrapped `fetch` after the panel, that stack is left alone, the wrapper goes inert, and the footer says `fetch not restored`.
- Nothing it does reaches the console.

It is fetch-only. A page cannot read an `EventSource`'s response headers, and WebSocket is never wrapped, so an SSE or WebSocket chat names its scope with rung 1 or rung 3.

A header naming the conversation the panel already follows (the next turn's response) narrows it to the new run; it never restarts the panel. A header naming another conversation is followed only when it comes from the request path that set the current one, so two widgets polling for different conversations do not thrash. A run the header names that is not listed yet (a streaming handler's header lands before its run row) is looked for again a second later before the panel says it is not in the conversation.

### Rung 3: DOM markers

Put the scope on the element that shows the conversation:

```html
<div id="chat" data-weft-scope="pub_demo">…</div>
```

This is the production rung: it touches no global of your page. It reads attributes only, through one `MutationObserver` on `document.documentElement` (rescans debounced about 100 ms, none while the page is hidden), one passive `focusin` listener and one `visibilitychange` listener, all removed when the panel disconnects. It never writes your DOM and never reads the panel's own tree. An empty value, or one without a public id, is ignored.

With several markers on the page, the one nearest focus wins: the marker around the focused element, else the one focus was last in, else the one followed now, else the first in document order. A followed marker that leaves the page stays followed, except on a route change: when every old marker is gone and exactly one new one appeared in the same scan, the new one is followed.

A marker must be in the light DOM. One inside a widget's own shadow root is invisible to the scan; put it on the host element at or above the widget.

Markers trust your page's DOM, and an HTML sanitizer (DOMPurify among them) keeps `data-*` attributes by default. A page that renders user or model HTML marks the container `data-weft-untrusted`: a marker on or inside it is ignored, and setting or lifting the attribute later rescans.

```html
<div data-weft-untrusted><!-- rendered model output --></div>
```

A host that cannot mark it sets `data-detect="off"` and names the scope explicitly.

An explicit scope wins over a marker, unless the marker carries the same conversation: the [framework helpers](#framework-helpers) call `scope()` and set the marker, so focus moves the panel between the helpers' chats.

### Rung 4: the page URL

A link can scope the panel on the page it opens: `?weft_scope=…` in the query, else `#weft_scope=…` in the fragment, the scope's string form URL-encoded once.

```text
http://127.0.0.1:8080/?weft_scope=pub_demo
http://127.0.0.1:8080/#weft_scope=pub_demo%3Bflow%3Df_1
http://127.0.0.1:8080/#/chat?weft_scope=pub_demo
```

A hash router's own query works; a value ends at the next `&` or `?`. A tag, agent or flow scope works too (`?weft_scope=tag.arena.batch%3Db1`). A value naming neither a public id nor a tag, agent or flow, or one encoded twice (its public id still holding `;` or `=`), is ignored.

The rung reads `location` and listens to `hashchange` and `popstate`; it never writes the URL. A navigation your page makes with `pushState` or `replaceState` is not seen until the next `hashchange` or `popstate`. A new URL scope pins its run; an explicit scope set later wins over it, and removing that hands the panel back to the URL. Focus in a marked chat does not move the panel off the URL's scope; the switcher does.

### Detection switches

`data-detect` (also `weft:detect`, or `mount({detect})`) switches rungs 2 and 3:

| `data-detect` | Rung 2 (headers) | Rung 3 (markers) |
|---|---|---|
| unset | page and endpoint on loopback, no panel token (`weft_pt.`) | on, except a read-scoped panel token off loopback |
| `headers` | on anywhere | as unset |
| `markers` | as unset | on anywhere |
| `headers,markers` | on anywhere | on anywhere |
| `off` (named anywhere: `off,headers` is `off`) | off | off |

Rungs 1 and 4 stay on whatever the value. Empty words are skipped (`markers,` is `markers`); a value naming anything else (`bogus`, `headers,bogus`) counts as unset, so the defaults apply.

## Name a batch of runs by tags, agent or flow

A page of unrelated runs, such as a test harness or a CI or eval batch, has no conversation. Name it by the run metadata your app stamped with `weft.WithMetadata` or `weft.Metadata`:

```html
<script type="module" src="/studio/panel.js" data-weft data-scope="tag.arena.batch=cli-20261012-115753"></script>
```

| Scope | Write it as | Lists |
|---|---|---|
| one conversation | `data-scope="pub_…"`, or `?weft_scope=pub_…` on the page's URL | its turns |
| one session of it | `pub_…;session=s_…` | that session's turns |
| one flow | `;flow=f_checkout` (or `pub_…;flow=…`) | the runs stamped `weft.flow=f_checkout` |
| a batch of runs | `tag.arena.batch=…`, repeatable, ANDed | the runs whose metadata carries every pair |
| one agent's runs | `;agent=director` (with tags: that agent's runs of the batch) | those runs |

A tag, agent or flow scope stands without a public id: its string form then starts with `;`, and a first segment that is one of these keys is read as one. The panel lists that page's runs, through `/api/runs?tag.<k>=<v>` (and `agent=`, `flow=`) with the live lane on `/api/live` under the same filter. The header's title reads `batch <id> · N runs`, such as `batch cli-20261012-115753 · 196 runs`: the first tag's key by its last dotted segment and the match's whole count, every other tag a chip. Without a tag it reads `agent <name> · N runs` or `flow <id> · N runs`. The count is in the title, not the stats line, which says the tokens; in a narrow dock the id is cut before the count. The header's figures, the tokens, the cost and the unpriced count, are one group that takes only the room the title leaves: each figure shows whole or not at all, never cut mid-figure. Rows read "turn" only for a public id with no tag, agent or flow; otherwise every row is a "run" and names its agent. `agent=` beside a public id, session or run narrows to the agent's runs.

What a tag scope reads depends on the token. Under a public id's panel token it reads what the token allows anyway: the runs of its public id that also carry the tags. Under a tag-scoped panel token ([Tokens](https://weftgo.dev/docs/observe/devtools/security/#tokens)) it reads the whole batch across public ids, live lane included, and without a `data-scope` the token's claims seed it (rung 4b). A tag scope is only as tight as your app's own tagging: metadata is caller-written.

![The devtools panel scoped to one arena batch (data-scope=";tag.arena.batch=…"): the header names the batch and counts its runs (batch cli-… · N runs), with the batch's tokens and cost, and the list names each run's agent](https://weftgo.dev/docs/_astro/panel-batch-scope.light.Bp8-bWtR.webp)

*data-scope=&quot;;tag.arena.batch=…&quot;: the panel lists that batch's runs, its header reading batch &lt;id&gt; · N runs.*

### Narrow by a flow

A scope's flow is run metadata, [`scope.FlowKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#FlowKey) (`weft.flow`). `scope.Header` stamps it on every run its handler starts, from the scope your function returns, else from the request's own `Weft-Scope` header; [`scope.WithFlow(ctx, flow)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#WithFlow) does the same for any context, and a run's own `weft.Metadata` wins over both. Studio's runs, sessions, search, stats, traces and live reads filter on it (`flow=`). The request's header is the client's to set, as any tag is, so a flow narrows a view and never grants one. [`ExampleWithFlow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#example-WithFlow) and [`ExampleScope (tags)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#example-Scope-Tags) show both forms.

## The scope header

[`scope.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Header) wraps your chat handler. It sets the `Weft-Scope` response header ([`scope.HeaderName`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#HeaderName)) to the scope your function returns for the request, unless that scope is zero, before your handler runs, so a streaming handler's first flush carries it. It also appends `Weft-Scope` to `Access-Control-Expose-Headers`. It is the Go side of rung 2; `thread` has no HTTP layer, so your handler sets it. The package sits beside the root package rather than in it, because the root package is a generated facade over `core`, which never imports `net/http`.

The `scope-header` snippet at the top of this page is the whole wiring: one line around the handler you already have.

A handler that learns the run id only once its turn starts narrows the scope with [`scope.Set`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Set) before its first write. The docs example sends one turn of the conversation's session and sets the run before it answers:

```go title="devtools/main.go"
// The page the request came from, which scope.Header put on the context.
if page, ok := scope.PageURLFromContext(r.Context()); ok {
	log.Printf("chat from %s", page)
}
turn, err := s.Send(ctx, weft.User(question(r)))
if err != nil {
	http.Error(w, err.Error(), http.StatusInternalServerError)
	return
}
// The run id is known: narrow the scope to it before the first write.
scope.Set(w, scope.Scope{PublicID: publicIDOf(r), RunID: turn.RunID()})
res, err := turn.Wait()
if err != nil {
	http.Error(w, err.Error(), http.StatusInternalServerError)
	return
}
_, _ = io.WriteString(w, res.Text())
```

[devtools/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/devtools/main.go)

`Set` replaces any earlier value; a zero scope removes the header. Like any header it must come before the first `Write` or `WriteHeader`; after that it changes nothing sent. The response then reads:

```sh
curl -si -X POST 'http://127.0.0.1:8080/chat?c=pub_demo' \
  -H 'Referer: http://127.0.0.1:8080/support?draft=1#top' -d 'Where is order 1234?'
```

```text
HTTP/1.1 200 OK
Access-Control-Expose-Headers: Weft-Scope
Weft-Scope: pub_demo;run=s_01M576FH50XX1CZQ3NMD59ZP57-t3
Date: Sun, 18 Oct 2026 09:53:28 GMT
Content-Length: 23
Content-Type: text/plain; charset=utf-8

Order 1234 has shipped.
```

The run id is illustrative: it is the session's id plus the turn number, so a fresh app's first turn ends in `-t1`.

The header never carries a token: a [`scope.Scope`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Scope) has nowhere to put one. Its fields are `PublicID`, `SessionID`, `FlowID`, `RunID`, `Agent` and `Tags`. [`Scope.String`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Scope.String) writes the string form: the public id first and bare, then `session=`, `flow=`, `run=` and `agent=` for each field set and `tag.<k>=<v>` for each tag in key order, joined by `;`, every key and value percent-encoded with `encodeURIComponent`'s rules; a scope without a public id starts with `;`. The zero `Scope` is `""`, and [`Scope.IsZero`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Scope.IsZero) reports it. [`scope.Parse`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Parse) reads the form back and never fails. A first segment that is a known `key=value` (`session=…`, `tag.<k>=<v>`) is read as that key, not as a public id. An unknown key, a segment without `=`, an empty value and a repeated key are ignored, and a value that does not decode is kept raw. Since `Tags` is a map, a `Scope` is no longer comparable with `==`: use [`Scope.Equal`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Scope.Equal), which treats a nil and an empty `Tags` alike.

```go title="devtools/main.go"
s := scope.Parse("pub_demo;flow=f_3;tenant=acme;run=r_9")
// s.PublicID "pub_demo", s.FlowID "f_3", s.RunID "r_9"; tenant= is ignored
form := s.String() // "pub_demo;flow=f_3;run=r_9"
```

[devtools/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/devtools/main.go)

The package's godoc has a runnable example for each of these: [`Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#example-Header), [`Parse`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#example-Parse), [`Scope.String`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#example-Scope.String) and [`PageURLFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#example-PageURLFromContext). weft's own `examples/studio-local` uses the same pair: its `/run` answers `Weft-Scope: pub_demo;run=<id>`.

The form is the panel's `data-weft-scope` marker and `serializeScope`/`parseScope`, byte for byte: weft's `studio/testdata/scope.golden.json` pins the Go and web sides to the same cases, and the docs example's `TestParseGolden` runs them against `scope.Parse` and `Scope.String`.

### Cross-origin pages

`scope.Header` and `scope.Set` expose the header, but a page on another origin also needs your CORS policy to allow that origin. A CORS layer inside `scope.Header` that sets its own expose list replaces the entry: put `scope.Header` inside your CORS middleware, or list `Weft-Scope` in its exposed headers. The panel reads a cross-origin response only when the page and the response are both on loopback; a cross-origin production app names its scope with `data-scope` or a marker.

### The page URL stamp

`scope.Header` also records the page a request came from, and stamps it as `weft.page_url` ([`scope.PageURLKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#PageURLKey)) on every run the handler starts. It puts the pair on the request's context with [`weft.WithMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WithMetadata), so `Generate` and thread's `Send` under `r.Context()` carry it with no option passed. A run's own `weft.Metadata` wins over it.

[`scope.PageURL(r)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#PageURL) is the rule: the request's `Referer`, else its `Origin` plus `/`. Only an absolute http or https URL with a host counts. Userinfo, the query and the fragment are dropped, and a URL over 1024 bytes is dropped whole, never cut. [`scope.PageURLFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#PageURLFromContext) reads it back in the handler; the `scope-set` region above logs it. With the `Referer` in the request above, the run row Studio serves carries it in `meta`:

```text
{'weft.page_url': 'http://127.0.0.1:8080/support'}
```

Studio's run meta serves it for "open in app", the way back to that page with `#weft_scope=`. The browser's default `Referrer-Policy` sends a cross-origin request only the origin, so a page on another origin is often its origin's root.

## Framework helpers

The npm package's helpers set the `data-weft-scope` marker on the element you give them and call `scope()`. They are not components, and they import no framework.

```tsx
// React 18/19: a callback ref.

<div ref={useWeftDevtools({ scope: { publicId }, endpoint: "/studio/", enabled: import.meta.env.DEV })}>…</div>
```

```vue
<!-- Vue 3: a function ref; pass a getter to follow reactive state -->
<script setup>

const weft = useWeftDevtools(() => ({ scope: { publicId: id.value } }))
</script>
<template><div :ref="weft">…</div></template>
```

```svelte
<!-- Svelte 3/4/5: an action -->
<script>import { weftDevtools } from "@weftgo/devtools/svelte"</script>
<div use:weftDevtools={{ scope: { publicId } }}>…</div>
```

Every helper takes the same options (`HelperOptions`):

| Option | Effect |
|---|---|
| `scope` | The scope to follow and mark: a `Scope` object, or a string, which is read as a public id alone |
| `endpoint`, `token` | When either is given and the page has no panel of its own, the helper first mounts one with `mount({ endpoint, token })`, replacing the bundle's self-mounted dock. With neither it mounts nothing: the page's own configuration decides |
| `enabled` | `false`: no marker, nothing loaded, nothing mounted (default `true`) |

On detach the helper removes the marker it set. Re-rendering with the same options does nothing. The Svelte action is also exported as `useWeftDevtools`, and rebinds on `update` with another scope. The helpers load the panel only when an element is bound, so they are safe to import in server-rendered components.

To write the marker yourself, in server code or a template, use the string form from `@weftgo/devtools/scope`, which touches no DOM:

```ts

serializeScope({ publicId: "pub_demo", run: "r_1" }) // "pub_demo;run=r_1"
parseScope("pub_demo;flow=f_3;run=r_9")              // { publicId: "pub_demo", flow: "f_3", run: "r_9" }
```

## Complete example

`docs-site/examples/devtools/main.go` (shown whole on [Install the devtools panel](https://weftgo.dev/docs/observe/devtools/install/#complete-example)) wraps its chat handler with `scope.Header`, sets the run with `scope.Set`, and runs offline. Its tests check the header and its expose entry, the `weft.page_url` stamp from a `Referer` and from an `Origin`, and `scope.Parse` against the golden cases:

```sh
go test ./devtools
```

```text
ok  	weftgo.dev/docs/examples/devtools	0.033s
```

Run it with `go run ./devtools` and open `http://127.0.0.1:8080/`. The dock reads `no conversation detected on this page`; ask a question and it follows `pub_demo`, with `detect: headers+markers` in its footer. Open `http://127.0.0.1:8080/?weft_scope=pub_demo` and the footer reads `detect: url+headers+markers`.

## Best practices & gotchas

- **Use markers or `data-scope` in production.** The header rung is off by default anywhere but loopback; the marker rung reads attributes only and patches nothing. (Source: `studio/README.md:1004-1006`; `studio/web/src/panel/config.ts:537-568`)
- **Mark rendered model or user HTML `data-weft-untrusted`.** Sanitizers keep `data-*`, so injected HTML could otherwise carry a marker that names another conversation. (Source: `studio/README.md:960-970`)
- **Set the run before the first write.** `scope.Set` after `Write` or `WriteHeader` changes nothing sent. (Source: `scope.Set` godoc)
- **Wrap inside your CORS layer.** A CORS middleware inside `scope.Header` that sets its own expose list hides the header from cross-origin pages. (Source: `scope.Header` godoc)
- **Keep secrets out of page paths behind `scope.Header`.** It stamps the `Referer`'s path as `weft.page_url` on every destination; strip a secret path in your own middleware before it, or leave that route unwrapped. (Source: `CHANGELOG.md:1201`)
- **Pass helpers a `Scope` object for more than a public id.** A string given to a helper is a public id alone, while `scope("pub_…;run=…")` parses the string form. (Source: `studio/web/src/npm/marker.ts:16-17, 27`)

## See also

- [Drive the panel from your page](https://weftgo.dev/docs/observe/devtools/host-api/)
- [Install the devtools panel](https://weftgo.dev/docs/observe/devtools/install/)
- [Secure the devtools panel](https://weftgo.dev/docs/observe/devtools/security/)
- [What is the devtools panel?](https://weftgo.dev/docs/observe/devtools/overview/)
- [Send turns and wait for them](https://weftgo.dev/docs/sessions/turns/)

Symbols used: [`scope.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Header) · [`scope.Set`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Set) · [`scope.Scope`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Scope) · [`scope.Parse`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Parse) · [`scope.HeaderName`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#HeaderName) · [`scope.PageURL`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#PageURL) · [`scope.PageURLFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#PageURLFromContext) · [`scope.PageURLKey`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#PageURLKey) · [`weft.WithMetadata`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WithMetadata) · [`thread.PublicID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#PublicID) · [`thread.Session.Send`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Session.Send) · [`thread.Turn.RunID`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/thread#Turn.RunID) · [Example (`Header`)](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#example-Header)
