Install the devtools panel
Add the panel to a page with one <script type="module"> tag that loads panel.js from your Studio. When the page and Studio share an origin (a Go app that embeds Studio), the tag needs no attributes beyond data-weft. Elsewhere it takes the Studio URL and a token as data-* attributes or weft:* meta tags. Apps that bundle their JavaScript can use the npm package @weftgo/devtools instead, which you build from weft’s repository: it is not on the npm registry.
Pick the line that fits how your page reaches Studio:
| Setup | The install |
|---|---|
A · your Go app serves Studio (studio.Handler at /studio/) | <script type="module" src="/studio/panel.js" data-weft data-scope="pub_…"></script>: same origin, no token |
B · a separate weft studio or weft dev | <script type="module" src="http://127.0.0.1:7331/panel.js" data-weft data-endpoint="http://127.0.0.1:7331/" data-token="…" data-scope="pub_…"></script> |
A bundled app with no <script> tag | import "@weftgo/devtools", or mount({endpoint, scope}), or useWeftDevtools(…) in React (npm) |
In setup B the token is the dev token in development; weft open --with-token prints it in a link. On a page you ship it is a panel token your backend mints. data-scope is optional: without it the panel detects the conversation (the detection ladder). The panel’s ⤢ links open the same run, step or session in Studio.
Setup A in Go: mount Studio beside your routes, and serve a page that loads the panel from it, in docs-site/examples/devtools/main.go:
stop := otel.Install(otel.Local("")) // ./.weft/weft.db (or $WEFT_DB), content on
mux := http.NewServeMux()// Studio, and with it /studio/panel.js and /studio/panel-config.json.mux.Handle("/studio/", http.StripPrefix("/studio", studio.Handler(studio.DB(otel.LocalDB()))))// The app's own page, which loads /studio/panel.js with one script tag.mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = io.WriteString(w, page)})The page’s tag is:
<script type="module" src="/studio/panel.js" data-weft></script>Open the page. The dock mounts in its corner, reads no conversation detected on this page, and follows the first conversation your page names. Scope the panel to a conversation shows how a page names one.


The script tag
Section titled “The script tag”studio.Handler serves the panel at <base>/panel.js: static, unauthenticated, embedded in the studio package, so the panel is always the version of the Studio that serves it. weft studio (setup B) serves it at its root, /panel.js. The file is one ES module: load it with type="module". It is built apart from Studio’s UI, as a separate Vite library-mode bundle with no React in it; a Studio build without the bundle answers /panel.js with a 500.
data-weft marks the tag as the panel’s. The panel finds its own tag by that attribute, whatever the file is called, so a bundle served from a proxy or renamed /assets/devtools.abc123.js still reads its configuration. Without data-weft, a module tag counts only when its src resolves to the panel’s own URL. A tag is never taken for the panel’s because it carries a data-endpoint or data-token: a third-party widget’s attributes are not the panel’s configuration.
Setup A, the page on Studio’s origin, needs nothing more. In setups B and C the page is on another origin, so the tag also names the Studio and a token:
<script type="module" src="http://127.0.0.1:7331/panel.js" data-weft data-endpoint="http://127.0.0.1:7331/" data-token="…"></script>A dev page against weft studio must be on localhost or 127.0.0.1: When the panel does not connect says why.
On your own machine the token is weft studio’s dev token. In a page you ship it is a per-page panel token your backend mints through POST /api/panel-tokens, never the dev or server token: Secure the devtools panel.
What the tag does when it loads:
- A
<weft-devtools>in your markup upgrades in place and is configured by its own attributes. The panel mounts no second dock. - No markup: the panel appends a dock to
<body>, unlessdata-auto="false". That dock is the panel’s own. If no Studio answers its/api/metarequest, it removes itself, unless you named a loopback endpoint (When the panel does not connect). A Studio that answers 401 or 403 never removes it. - A mount you made (your
<weft-devtools>, ormount()from npm) stays when no Studio answers, and shows one line,Studio not reachable at <endpoint> · retry. While a retry asks again,retryreadschecking…. - Attribute changes apply live. The element watches every field in the table below except
data-modeanddata-open, which are read once as the initial mode and state. A framework that rewrites them, or remounts the element, reconfigures the panel without removing it. ?weft=debugin the page URL, ordebug: trueunderlocalStorage["weft.devtools"], mounts the dock even withdata-auto="false": a switch for a staging page. The olderlocalStorage.weft_debug=1is migrated into that key.
When the panel does not connect
Section titled “When the panel does not connect”The panel asks /api/meta once at start. Since 0.20.0 it tells two cases apart:
- Studio refused the token (a 401 or 403). Studio is there and wants a token, so the panel is never removed, however it was installed. Its line reads
Studio needs a token at <endpoint> — add data-token (the dev token) or a panel token (POST /api/panel-tokens) · retry. - No Studio answered: no answer, any other non-2xx answer, a request the browser blocks, or a 200 that is not Studio’s meta (an app’s catch-all route). The self-mounted dock removes itself, silently. Two exceptions show
Studio not reachable at <endpoint> · retryinstead: a loopback endpoint you named (your own Studio, not started yet) and a mount you made.
A bare tag, with no endpoint and no data-weft, whose guessed endpoint is on loopback also logs one console line, once per page: weft devtools: Studio did not answer at <endpoint>; add data-weft or data-endpoint on the panel's <script> tag. Off loopback the removal stays silent, so a production page with a vendored tag shows nothing. The npm package never logs it.
A Studio that stops answering after the panel started, a turn-list read with no answer or a 401 or 403, gets the same line under the dock’s header. The turns stay, dimmed. The live lane reads the list again with a bounded backoff, and a read that lands clears the line; retry starts the backoff over. Past those retries the panel reads /api/meta once a minute while the dock is open and the page is visible. It comes back by itself.
| Case | What /api/meta gets |
|---|---|
| No Studio at the endpoint | no answer (connection refused) |
| A panel token that expired before the page loaded or reloaded (the 1 h default) | 401 bad or expired token |
A token from before weft studio --rotate-token (the old dev token) or a studio.Token change (the old server token), or a panel token either one signed | 401 bad or expired token |
No data-token against a Studio with a token (setups B and C) | 401 the API requires a token: Authorization: Bearer <token> |
Setup A reached on a Host that is not loopback and not in AllowOrigins | 403 no studio.Token is configured, so the API answers only a loopback Host … |
A page origin weft studio’s CORS does not allow (*.localhost, [::1], a LAN IP, a custom hostname) | blocked by the browser: a CORS error. Loaded from that Studio, /panel.js itself is blocked, so not even the not-reachable line appears |
weft studio answers cross-origin requests only from http or https pages on localhost or 127.0.0.1, any port, and has no AllowOrigins flag or environment variable to add an origin. The ways out:
- Serve the page and Studio from one origin through your dev server’s proxy, as the Vite example does.
- Embed Studio in a Go program with
studio.AllowOriginslisting the page’s origin. The list replaces the default: withAllowOrigins("http://192.168.1.5:5173")alone, a page onhttp://localhost:5173loses CORS, so list it too.
A phone on your LAN also needs to reach Studio: weft studio listens on 127.0.0.1 (port 7331 by default) unless --addr names an interface the phone can reach.
Panel config JSON
Section titled “Panel config JSON”Studio’s handler (embedded in setup A, and under weft studio) also serves GET <base>/panel-config.json, the panel’s endpoint as the request reached Studio, the weft version and Studio’s capabilities. With the program above running:
curl -s http://127.0.0.1:8080/studio/panel-config.json{"endpoint":"http://127.0.0.1:8080/studio/","version":"v0.20.2","capabilities":["requests","steps","export","logs","diff","traces","search","stats","manifests","spans_tree","timeline","pricing","delete","proposals","live","scope_tags","ingest","panel-config"]}It answers a loopback Host (or an studio.AllowOrigins host), and a request whose Origin, when it has one, is the same origin, a loopback origin or an AllowOrigins entry. Anything else gets a 404, as if there were no Studio. It never carries a token. /api/meta lists its capability, panel-config.
The panel asks for it only when no rung above named an endpoint: it fetches panel-config.json from its script’s own directory (/studio/panel.js → /studio/panel-config.json), with no credentials, and takes the endpoint only when it is on that same origin. It reads endpoint alone: version and capabilities are for other readers. The request is aborted after 3 s, so a proxy that holds it does not hold the panel, and the panel falls through to the script’s own directory, as it does on a 404, a non-JSON answer or an endpoint on another origin. Name the endpoint and the request is never made.
The release asset
Section titled “The release asset”Each weft release on GitHub attaches the panel as panel-v<version>.js, with panel-v<version>.js.sha256 beside it: for v0.20.2, panel-v0.20.2.js and panel-v0.20.2.js.sha256 on the v0.20.2 release. It is the file Studio serves as /panel.js and the npm package ships as panel.js, byte for byte. Use it for a backend that is not Go, which serves the file itself, and to check a built npm package against the release. Download and check it:
gh release download v0.20.2 -R weftgo/weft -p 'panel-v0.20.2.js*'sha256sum -c panel-v0.20.2.js.sha256panel-v0.20.2.js: OKServe it from your app’s static files, and name the Studio and a token on the tag as in setups B and C, keeping data-weft on it:
<script type="module" src="/static/panel-v0.20.2.js" data-weft data-endpoint="https://studio.example/" data-token="…"></script>Take the asset of the release your Studio runs: a panel older than Studio says Studio is newer than this panel; update panel.js. The npm package’s panel.js.sha256 carries the same hash as the asset’s .sha256. In weft’s repository make studio-panel-asset stages the two files.
Where configuration comes from
Section titled “Where configuration comes from”Each field resolves on its own: the first source that sets it wins, so a meta tag can carry the token while the script tag carries the endpoint. The sources, highest first:
| # | Source | Example |
|---|---|---|
| 1 | mount(opts) from @weftgo/devtools (not in the script-tag bundle) | mount({ endpoint: "/studio/" }) |
| 2 | the <weft-devtools> element’s attributes | <weft-devtools data-endpoint="…" data-token="…"> |
| 3 | meta tags | <meta name="weft:endpoint" content="…"> |
| 4 | the panel’s <script> tag: the running classic script, else the module script whose src is the bundle’s own URL when it carries data-weft (two marked tags on a page each read their own), else the first tag with data-weft, else the module’s own bare tag | <script type="module" src="…" data-weft data-endpoint="…"> |
| 5 | panel-config.json beside the script, for the endpoint only, asked only when rungs 1–4 named none | — |
| 6 | the script’s own origin and directory | /studio/panel.js → /studio/ |
Imported through @weftgo/devtools, the panel is part of your app’s bundle, so rung 4 is only a tag carrying data-weft. With no such tag, panel-config.json is not asked and the endpoint defaults to the page’s own directory. The panel never reads its own file name.
The fields, as an attribute (data-<field> on the element or the tag), a meta tag (weft:<field>) and a mount() option:
| Attribute | Meta tag | mount() option | Default | Effect |
|---|---|---|---|---|
data-endpoint | weft:endpoint | endpoint | rungs 5–6 | Studio’s base URL; an empty value counts as unset, a non-http(s) one stops the panel |
data-scope | weft:scope | scope | none | The conversation to follow (Scope the panel) |
data-public-id | weft:public-id | publicId | none | Deprecated: the scope with a public id only; data-scope wins at the same rung |
data-token | weft:token | token | none | The API bearer for setups B and C |
data-detect | weft:detect | detect | unset | Scope detection switches (Detection switches) |
data-position | weft:position | position | bottom-right | Where the dock starts (Lay out the panel) |
data-open | weft:open | open | collapsed | "true" (or an empty attribute) starts expanded |
data-auto | weft:auto | auto | on | "false" stops the bundle mounting a dock by itself |
data-global | weft:global | — | on | "off" or "false" keeps window.weft.devtools off (host API) |
data-mode | weft:mode | mode | unset | float, dock, pill or hidden |
data-push | weft:push | push | off | "true": a docked, open panel pads <html> |
data-z-index | weft:z-index | zIndex | --weft-z, else 2147483000 | The dock’s z-index, an integer |
data-theme | weft:theme | theme | auto | light or dark; auto follows the stored choice and the page |
mount() writes mode, push and zIndex onto the element as data-mode, data-push and data-z-index, so those three resolve from rung 2.
The same configuration as meta tags, with the tag carrying only data-weft:
<meta name="weft:endpoint" content="http://127.0.0.1:7331/"><meta name="weft:token" content="…"><meta name="weft:scope" content="pub_demo"><script type="module" src="http://127.0.0.1:7331/panel.js" data-weft></script>A weft:token meta tag is a token in your page’s source, exactly like data-token.
@weftgo/devtools is the same panel.js, byte for byte, packaged with a small typed module and three framework helpers, for apps that bundle everything and ship no <script> tag (Vite, Next, SvelteKit, Nuxt). It is a second delivery of the panel, not a replacement: the script tag is the canonical install.
The package is ready to publish (publishConfig.access is public, and prepublishOnly reruns the package check), but publishing is done by hand at release time and v0.20.2 was not published. The <weft-devtools> custom element in its shadow DOM is the whole panel here too; the package’s helpers only set a DOM marker.
Build the package
Section titled “Build the package”From a clone of weft at v0.20.2, with Bun and npm on the PATH:
git clone --branch v0.20.2 https://github.com/weftgo/weftcd weftmake devtools-npmcd studio/web/npm && npm packmake devtools-npm runs make studio-build (bun install, then the web, panel and npm builds), assembles the package in studio/web/npm, checks that its panel.js is the served studio/dist/panel/panel.js, runs the package’s test suite and type checks, and lists the tarball. npm pack then writes it:
weftgo-devtools-0.20.2.tgzInstall it in your app
Section titled “Install it in your app”npm install --save-dev /path/to/weft/studio/web/npm/weftgo-devtools-0.20.2.tgznpm records the tarball as a file: spec in your package.json. The package version is the weft version (package 0.20.2 is weft v0.20.2); rebuild it when you upgrade Studio, since the panel compares its version with Studio’s and says Studio is newer than this panel; update panel.js when Studio is newer. It has zero runtime dependencies and needs Node 18 or later. React (18+), Vue (3+) and Svelte (3+) are optional peer dependencies; the helpers do not import them.
Import it
Section titled “Import it”In client code, one import does what the script tag does: it defines <weft-devtools> and mounts the dock, configured from meta tags and markup:
import "@weftgo/devtools"Or mount it yourself, which takes configuration rung 1:
import { mount } from "@weftgo/devtools"
mount({ endpoint: "/studio/" })mount() appends a <weft-devtools> to target (default <body>) and returns it. It replaces the dock the bundle mounted by itself and leaves markup of your own alone. It is idempotent: a second call, from a React StrictMode effect or a hot reload, returns the same element with the new options. Called before <body> exists, it returns the element and appends it on DOMContentLoaded. It returns null with enabled: false, and on a server.
Its options are endpoint, scope, publicId, token, detect, position, open, auto, theme, mode, push, zIndex, target and enabled. position (type Position) takes six values: bottom-right, bottom-left, right-dock, left-dock, top-dock and bottom-dock. mode (type Mode) is float, dock, pill or hidden.
enabled: false is not a production gate for mount(). It makes mount() return null, but a static import of the package has already loaded panel.js, and that bundle mounts its own dock as it evaluates (unless a weft:auto meta tag says "false"). The dock then asks the page’s own directory for api/meta before it removes itself. Only the framework helpers load nothing with enabled: false, since they import the panel lazily. weft’s own studio/web/npm/README.md claims more for mount() than the code does.
To keep the panel out of production, import it dynamically behind your build’s flag:
if (import.meta.env.DEV) { import("@weftgo/devtools").then(({ mount }) => mount({ endpoint: "/studio/" }))}Under vite build, import.meta.env.DEV is false and the branch is dropped: the built app is a 0.67 kB chunk with no panel in it. A static import { mount } with mount({ enabled: false }) builds a 276 kB chunk that includes panel.js. Under vite dev, the guarded import mounts one panel. The bundle’s own dock still asks api/meta in the page’s directory first, which shows as a 404 in the console when the app serves nothing there, and then mount() replaces that dock.
The imported panel finds its scope by the same ladder as the script tag. Highest first:
mount({scope}),scope("pub_…")or a meta tag (rung 1);- the page URL’s
?weft_scope=(rung 4); - a
data-weft-scopemarker thatuseWeftDevtoolsorweftDevtoolssets (rung 3); - a
Weft-Scoperesponse header (rung 2); - a panel token’s claims (rung 4b);
- the fallback.
A page of unrelated runs names a batch by its tags, tag.arena.batch=… (Scope the panel to a conversation).
What it exports
Section titled “What it exports”import { … } from "@weftgo/devtools":
| Export | What it does |
|---|---|
mount(opts?) | Mounts a configured panel and returns it (above) |
scope(s) | Points every panel on the page at a scope, or null to hand it back to the ladder (Scope the panel) |
open(), close(), toggle() | Expand, collapse or flip every panel; a panel mounted after open() or close() starts that way |
isOpen() | Whether a panel on the page is expanded |
select(runId, step?) | Selects that turn, and the step by its ordinal |
studioLink(runId, step?) | The Studio page of that run, never with a token; "" before a panel knows its endpoint |
on(event, cb) | Follows run, parked or error; returns the unsubscribe |
serializeScope(s), parseScope(str) | The scope’s string form, pub_…;session=…;flow=…;run=… |
types Scope, MountOptions, PanelOptions, Position, Mode, WeftDevtoolsElement, DevtoolsEvents |
Drive the panel from your page covers select, studioLink, on and the events. The package adds no global. In the npm API isOpen() is a function; on the element and on the script tag’s window.weft.devtools it is a property, isOpen.
The package’s subpaths:
| Import | What it is |
|---|---|
@weftgo/devtools | The typed module above; importing it loads panel.js |
@weftgo/devtools/react | useWeftDevtools, a callback ref |
@weftgo/devtools/vue | useWeftDevtools, a function ref |
@weftgo/devtools/svelte | weftDevtools, an action (also exported as useWeftDevtools) |
@weftgo/devtools/scope | serializeScope, parseScope and the Scope type alone; touches no DOM |
@weftgo/devtools/panel.js | The side-effect bundle itself, the same file as /studio/panel.js, with panel.js.sha256 beside it; minified, with no sourcemap |
@weftgo/devtools/package.json | The package manifest |
The helpers set the data-weft-scope marker on your chat’s element: Framework helpers.
Server-rendered frameworks
Section titled “Server-rendered frameworks”The root entry is import-safe on a server (Node, a worker, an edge runtime). Nothing is registered there and every export is a no-op: mount() returns null, on() returns a no-op unsubscribe, isOpen() is false and studioLink() is "". The helpers load the panel only when an element is bound, which never happens on a server. In server code, @weftgo/devtools/scope writes the marker’s value into your markup.
Example: Vite app
Section titled “Example: Vite app”weft’s examples/devtools-vite is a Vite + TypeScript app with no framework: a form that POSTs to /run, inside <div id="chat" data-weft-scope="pub_demo">. The panel comes from the package and no <script> tag for it appears anywhere. Its src/main.ts is the whole integration:
import { mount } from "@weftgo/devtools"
mount({ endpoint: import.meta.env.VITE_WEFT_STUDIO ?? "/studio/" })/studio/ is examples/studio-local’s embedded Studio, which vite.config.ts proxies in development with /run: same origin, so no token and no CORS. VITE_WEFT_STUDIO points the panel at another Studio; WEFT_BACKEND moves the proxy (default http://127.0.0.1:8080).
The example installs the packed tarball, never a registry copy. From weft’s repository root, after make studio-build:
make devtools-vite-checkIt packs studio/web/npm into vendor/weftgo-devtools.tgz inside the example, runs npm ci (vite 8.3.4 and jsdom 30.1.2, pinned by the committed lockfile), installs the tarball with npm install --offline --no-save, and runs check.ts. The check builds with vite build, fails if dist/index.html has a <script src=…panel.js> tag, loads the page into jsdom with a fake /api/meta, asserts one <weft-devtools> asked /studio/api/meta, and compares the installed panel.js with the served one by sha256:
ok: <weft-devtools> defined, one on the page, /api/meta asked (1x)ok: page /app/ with the entry tag kept: the self-mounted dock's endpoint is http://127.0.0.1:5173/app/, nothing asked under /assets/ok: panel.js sha256 346ef1dad2ecc5a1a73dbbf6d2a638469591f0a4161858fd51f5eeae37c9196a = studio/dist/panel/panel.jsDEVTOOLS VITE CHECK PASSFor the live demo, once the check has installed the package, run in two terminals:
weft dev -- go run ./examples/studio-local # repository rootcd examples/devtools-vite && npm run dev # http://localhost:5173/weft dev runs Studio on 127.0.0.1:7331 and studio-local beside it on 127.0.0.1:8080; without the weft command installed, use go run ./cmd/weft dev -- go run ./examples/studio-local. Ask a question in the chat: /run answers with a Weft-Scope header, which scopes the panel to the turn.
The example’s install is npm’s, not bun’s: bun keeps serving a cached copy of a file: tarball after it changes, while npm reinstalls an explicit tarball spec. Its lockfile holds vite and jsdom only; the tarball is installed unsaved, since its integrity changes with every panel build. The other form, described in its src/main.ts, is a bare import "@weftgo/devtools" with the endpoint in a weft:endpoint meta tag: that dock removes itself when its /api/meta fails, where mount() shows Studio not reachable.
Complete example
Section titled “Complete example”The page’s program, a Go app that serves Studio, the page with the script tag, and a chat endpoint that sets the scope header:
// Command devtools is the devtools panel pages' program: an app that// serves Studio (setup A) beside its own page and chat endpoint, so the// page's <script src="/studio/panel.js" data-weft> and// /studio/panel-config.json resolve on the app's own origin, and whose// chat handler tells the panel which conversation and run a response// belongs to, with package weft/scope.//// main serves it on http://127.0.0.1:8080/. main_test.go runs every// part offline: the page, the panel's two files, the Weft-Scope header,// the weft.page_url stamp and scope.Parse against weft's golden file.package main
import ( "context" "errors" "fmt" "io" "log" "net/http" "strings" "sync"
"github.com/weftgo/weft" "github.com/weftgo/weft/otel" "github.com/weftgo/weft/scope" "github.com/weftgo/weft/studio" "github.com/weftgo/weft/thread" "github.com/weftgo/weft/wefttest")
// page is the app's own page. Its only weft-ness is the panel's script// tag: same origin as Studio (setup A), so no endpoint and no token. The// tag names no scope; the first /chat response's Weft-Scope header does.const page = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Order help</title></head><body><h1>Order help</h1><form id="ask"><input name="text" value="Where is order 1234?" size="40"> <button>Ask</button></form><ol id="answers"></ol><script>document.getElementById("ask").addEventListener("submit", async (e) => { e.preventDefault() const res = await fetch("/chat?c=pub_demo", { method: "POST", body: new FormData(e.target).get("text") }) const li = document.createElement("li") li.textContent = await res.text() document.getElementById("answers").append(li)})</script><script type="module" src="/studio/panel.js" data-weft></script></body></html>`
// newAgent is the chat's agent. The model is scripted so the program// runs offline: it answers the same line for the first thousand turns.func newAgent(opts ...weft.Option) *weft.Agent { turns := make([]wefttest.Turn, 1000) for i := range turns { turns[i] = wefttest.Say("Order 1234 has shipped.") } return weft.New(wefttest.Script(turns...), append([]weft.Option{weft.Name("support-bot")}, opts...)...)}
// publicIDOf is the conversation a request belongs to: the public id// the app hands out. This page sends it as ?c=.func publicIDOf(r *http.Request) string { if c := r.URL.Query().Get("c"); c != "" { return c } return "pub_demo"}
// question is the request body: the user's words.func question(r *http.Request) string { raw, _ := io.ReadAll(io.LimitReader(r.Body, 64<<10)) if q := strings.TrimSpace(string(raw)); q != "" { return q } return "hello"}
// chats holds one thread session per public id: the conversation the// panel follows is the session created with thread.PublicID.type chats struct { agt *weft.Agent st thread.Storage mu sync.Mutex sessions map[string]*thread.Session}
func newChats(agt *weft.Agent) *chats { return &chats{agt: agt, st: thread.Memory(), sessions: map[string]*thread.Session{}}}
// session returns the conversation's one Session, created on first use.func (c *chats) session(ctx context.Context, publicID string) (*thread.Session, error) { c.mu.Lock() defer c.mu.Unlock() if s, ok := c.sessions[publicID]; ok { return s, nil } s, err := thread.Create(ctx, c.st, c.agt, thread.PublicID(publicID)) if err != nil { return nil, err } c.sessions[publicID] = s return s, nil}
// close closes every Session (thread's T2: close what you opened to write).func (c *chats) close() { c.mu.Lock() defer c.mu.Unlock() for _, s := range c.sessions { _ = s.Close(context.Background()) }}
// chat answers one question: one turn of the conversation's session.func (c *chats) chat(w http.ResponseWriter, r *http.Request) { // The turn outlives the request: keep r.Context()'s values (the // page URL scope.Header put there), drop its cancellation. ctx := context.WithoutCancel(r.Context()) s, err := c.session(ctx, publicIDOf(r)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // 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())}
// routes is the app: Studio under /studio/, the page at /, the chat at// POST /chat. It records every run into the local sink Studio serves;// the returned func closes the sessions and the pipeline.func routes(agt *weft.Agent) (http.Handler, func()) { c := newChats(agt) stop := otel.Install(otel.Local("")) // ./.weft/weft.db (or $WEFT_DB), content on
mux := http.NewServeMux() // Studio, and with it /studio/panel.js and /studio/panel-config.json. mux.Handle("/studio/", http.StripPrefix("/studio", studio.Handler(studio.DB(otel.LocalDB())))) // The app's own page, which loads /studio/panel.js with one script tag. mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = io.WriteString(w, page) })
mux.Handle("POST /chat", scope.Header(http.HandlerFunc(c.chat), func(r *http.Request) scope.Scope { return scope.Scope{PublicID: publicIDOf(r)} })) return mux, func() { c.close(); stop() }}
// parsed reads a scope's string form back, as the panel's parseScope// does: an unknown key is ignored, the fields come back in their order.func parsed() (scope.Scope, string) { 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" return s, form}
func main() { h, stop := routes(newAgent()) defer stop() fmt.Println("app: http://127.0.0.1:8080/ · studio: http://127.0.0.1:8080/studio/") srv := &http.Server{Addr: "127.0.0.1:8080", Handler: h} if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Print(err) }}View on GitHub · from docs-site/examples:
go run ./devtoolsgo test ./devtoolsapp: http://127.0.0.1:8080/ · studio: http://127.0.0.1:8080/studio/TestPanelFilesResolve fetches the page, /studio/panel.js and /studio/panel-config.json, and checks that a non-loopback Host gets a 404 for the config.
Best practices & gotchas
Section titled “Best practices & gotchas”- Keep
data-wefton the tag. It is how the panel finds its own tag, and with it the endpoint, whatever the file is called. Setup A also finds an unmarked module tag by its URL, but a renamed or proxied file needs the attribute, and so does a tag configured only bywindow.__WEFT__. (Source:studio/README.md:870-874;studio/web/src/panel/config.ts:273-298) - Load the panel from the Studio it talks to.
/panel.jsis embedded in the Studio of the same version; a copied or npm-installed panel older than Studio saysStudio is newer than this panel; update panel.js. (Source:studio/web/npm/README.md:22-27) - Never put a dev or server token in a page you ship.
data-tokenandweft:tokenare in the page’s source; mint a per-page panel token instead. (Source:studio/README.md:1297-1299) - Gate the npm import in production with a dynamic
import(). A static import loadspanel.jsand its self-mounted dock whatevermount()’senabledsays; only the helpers’enabled: falseloads nothing. (Source:studio/web/src/npm/index.ts:20,index.ts:262;studio/web/src/panel/main.ts:66-67;studio/web/src/npm/marker.ts:32-34; observed withvite build) - A panel that vanishes found no Studio; one that asks for a token was refused. A 401 or 403 keeps the panel with its
Studio needs a tokenline: a 401 is a missing, expired or rotated token, a 403 setup A on aHostit does not answer. A vanished dock is a failed connection, a CORS error (a page origin Studio does not allow) or a non-Studio answer; the browser’s network tab tells them apart. (Source:studio/web/src/panel/state.ts:2055-2068;studio/web/src/panel/client.ts:66-86;studio/auth.go:166-215; observed in Chromium) - Use
localhostor127.0.0.1for a dev page againstweft studio. Any other page origin gets no panel; When the panel does not connect has the ways out, a phone included. (Source:studio/auth.go:774-792;cmd/weft/main.go:875-907; observed with curl) - Build the package from the tag you run. The package is not on the registry;
make devtools-npmat a different tag gives a panel of a different version. (Source:studio/README.md:1446-1450;AGENTS.md:400)
See also
Section titled “See also”- Scope the panel to a conversation
- Lay out and theme the panel
- Drive the panel from your page
- Secure the devtools panel
- Run Studio: embedded, local binary or hosted
Symbols used: studio.Handler · studio.DB · studio.AllowOrigins · otel.Install · otel.Local · otel.LocalDB · scope.Header