Skip to content

Scope the panel to a conversation

View as Markdown

The panel follows one scope: a conversation’s 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 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.

Name it on the tag:

<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:

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

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 panel takes the first scope it finds, in this order:

OrderRungWhere the scope comes fromWhen it is on
1st1 · explicitdata-scope, window.__WEFT__, scope() / mount({scope})always
2nd4 · the page URL?weft_scope=…, else #weft_scope=…always
3rd3 · DOM markersdata-weft-scope="…" on an element of the pageby default everywhere, except a page off loopback under a read-scoped panel token
4th2 · response headersthe Weft-Scope header of the page’s own fetch responsesby default only with the page and Studio on loopback, and no token or a dev token
5th4b · a panel token’s claimsa 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 fallbacknothing names a scope: no conversation detected on this page · how to scope, over the newest runswhen 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); 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). 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). 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 · markerA 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
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.

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

<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.

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) 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.

Your chat handler sets Weft-Scope: pub_demo;run=… on its responses (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.

Put the scope on the element that shows the conversation:

<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.

<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 call scope() and set the marker, so focus moves the panel between the helpers’ chats.

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.

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.

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

data-detectRung 2 (headers)Rung 3 (markers)
unsetpage and endpoint on loopback, no panel token (weft_pt.)on, except a read-scoped panel token off loopback
headerson anywhereas unset
markersas unseton anywhere
headers,markerson anywhereon anywhere
off (named anywhere: off,headers is off)offoff

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

Section titled “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:

<script type="module" src="/studio/panel.js" data-weft data-scope="tag.arena.batch=cli-20261012-115753"></script>
ScopeWrite it asLists
one conversationdata-scope="pub_…", or ?weft_scope=pub_… on the page’s URLits turns
one session of itpub_…;session=s_…that session’s turns
one flow;flow=f_checkout (or pub_…;flow=…)the runs stamped weft.flow=f_checkout
a batch of runstag.arena.batch=…, repeatable, ANDedthe 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) 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 agentThe 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
data-scope=";tag.arena.batch=…": the panel lists that batch's runs, its header reading batch <id> · N runs.

A scope’s flow is run metadata, 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) 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 and ExampleScope (tags) show both forms.

scope.Header wraps your chat handler. It sets the Weft-Scope response header (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 before its first write. The docs example sends one turn of the conversation’s session and sets the run before it answers:

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

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:

Terminal window
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?'
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 has nowhere to put one. Its fields are PublicID, SessionID, FlowID, RunID, Agent and Tags. 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 reports it. 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, which treats a nil and an empty Tags alike.

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

The package’s godoc has a runnable example for each of these: Header, Parse, Scope.String and 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.

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.

scope.Header also records the page a request came from, and stamps it as weft.page_url (scope.PageURLKey) on every run the handler starts. It puts the pair on the request’s context with weft.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) 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 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:

{'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.

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.

// React 18/19: a callback ref.
import { useWeftDevtools } from "@weftgo/devtools/react"
<div ref={useWeftDevtools({ scope: { publicId }, endpoint: "/studio/", enabled: import.meta.env.DEV })}>…</div>
<!-- Vue 3: a function ref; pass a getter to follow reactive state -->
<script setup>
import { useWeftDevtools } from "@weftgo/devtools/vue"
const weft = useWeftDevtools(() => ({ scope: { publicId: id.value } }))
</script>
<template><div :ref="weft">…</div></template>
<!-- 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):

OptionEffect
scopeThe scope to follow and mark: a Scope object, or a string, which is read as a public id alone
endpoint, tokenWhen 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
enabledfalse: 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:

import { serializeScope, parseScope, type Scope } from "@weftgo/devtools/scope"
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" }

docs-site/examples/devtools/main.go (shown whole on Install the devtools panel) 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:

Terminal window
go test ./devtools
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.

  • 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)

Symbols used: scope.Header · scope.Set · scope.Scope · scope.Parse · scope.HeaderName · scope.PageURL · scope.PageURLFromContext · scope.PageURLKey · weft.WithMetadata · thread.PublicID · thread.Session.Send · thread.Turn.RunID · Example (Header)