---
title: Install the devtools panel
description: Add the devtools panel to your app's page with one script tag that loads Studio's /panel.js, configure it with data-* attributes or weft:* meta tags, or bundle it from the @weftgo/devtools package built from weft's repository.
url: https://weftgo.dev/docs/observe/devtools/install/
type: how-to
sources:
  - 'weft/studio/web/src/panel/element.ts:851-863 (observedAttributes: no data-mode; data-open adopted once on first connect, 1065-1080), 2116-2140 (attribute changes re-read; only data-position moves the dock), 2452-2468 (the console line: bare loopback tag, once per page, never via the npm package, config.ts:341); weft/studio/web/src/panel/state.ts:1220-1236 (the minute /api/meta probe only while visible and the dock open) — v0.20.2'
  - 'weft/studio/README.md:398-460 (the quickstart: three setups, the hand-off), 1272-1330 (the configuration ladder: rung 4''s own-URL tag with data-weft first, UX-D-28; When Studio does not answer: removal off loopback, the console line, 401/403 never removed, the after-boot line and its backoff); weft/studio/web/npm/README.md:3-72 (not published; the scope ladder; tag scopes); weft/studio/web/src/panel/state.ts:2055-2068 (walled on 401/403); weft/CHANGELOG.md:61 — v0.20.2'
  - weft/studio/README.md:398-403 (one script tag; /panel.js served by the same handler)
  - weft/studio/README.md:867-874 (setups B and C add data-endpoint and data-token; window.__WEFT__; keep data-weft on the tag)
  - 'weft/studio/README.md:1274-1317 (where the configuration comes from: the fields, the six rungs, a tag found by data-weft, the weft:token warning, no Studio answering)'
  - 'weft/studio/README.md:1420-1452 (the same file on npm: a second delivery, the typed module, import-safe on a server, mount idempotent, make devtools-npm, publishing done by hand, examples/devtools-vite)'
  - weft/README.md:488-495 (setup A serves GET <base>/panel-config.json, capability panel-config)
  - weft/AGENTS.md:354 (/panel.js), 384-385 (configured by a data-weft script tag, weft:* meta tags, or <base>/panel-config.json), 395-402 (@weftgo/devtools, mount and its options, the helpers, import-safe, never published by the build; /panel-config.json, capability panel-config)
  - 'weft/studio/web/src/panel/config.ts:1-31 (the ladder), 133-147 (FIELDS), 273-298 (findPanelScript), 376-395 (optionsRung: mode, push, z-index and global are not mount options), 431-551 (readConfig: position, open, auto, global defaults), 557-571 (discoverEndpoint: same origin, no credentials), 218-251 (debugForced: ?weft=debug, localStorage)'
  - 'weft/studio/web/src/panel/main.ts:70-124 (the mount decision: markup upgrades; data-auto or the debug override mounts the dock)'
  - 'weft/studio/panelconfig.go:11-89 (the document and its guard: loopback or AllowOrigins Host, same-origin, loopback or AllowOrigins Origin, else 404)'
  - weft/studio/panel.go:26-58 (GET /panel.js, embedded; 500 when the build lacks it)
  - weft/studio/web/src/panel/element.ts:454-456 (PROBE_TIMEOUT_MS 3 s), 2374-2391 (rung 5 bounded by the probe, falling through to the script directory), 2850-2862 (the not-reachable line, checking… while a retry asks)
  - 'weft/studio/web/src/panel/config.ts:550-572 (discoverEndpoint: endpoint only, same origin, no credentials; empty on a 404, non-JSON or no answer)'
  - weft/studio/panelconfig.go:34-45 (panel-config.json registered on every studio.Handler)
  - weft/studio/web/src/npm/index.ts:20 (panel.js imported statically), 262 (enabled false returns null)
  - weft/studio/web/src/panel/main.ts:66-67 (the bundle mounts its dock when auto is on)
  - weft/studio/web/src/npm/marker.ts:32-34 (a helper with enabled false does nothing; the panel is imported lazily)
  - weft/studio/web/src/panel/config.ts:84 (data-mode, the initial mode)
  - 'observed: vite 8.3.4 over the packed tarball: if (import.meta.env.DEV) import(...).then(mount) builds a 0.67 kB chunk without the panel; a static import with mount({enabled:false}) builds 276.44 kB with it; under vite dev the guarded import mounts one panel after the self-mounted dock asked /api/meta (404)'
  - weft/studio/web/src/panel/element.ts:817-830 (observedAttributes)
  - 'weft/studio/web/npm/README.md:1-164 (the package: install, API table, framework helpers, the file itself)'
  - weft/studio/web/npm/README.md:16-18 (panel.js here equals the served asset and the panel-<version>.js.sha256 release asset)
  - weft/studio/README.md:1373-1374 (make studio-panel-asset stages panel-<version>.js + sha256 for non-Go backends)
  - weft/studio/web/scripts/panel-asset.ts:1-8 (attached to every release for non-Go backends; dist/panel/panel.js copied to <out>/panel-<version>.js with a .sha256); weft/Makefile:180-181 (studio-panel-asset)
  - weft/CHANGELOG.md:3472-3479 (0.8.0's release asset, served from the app with a script tag), 4676-4679 (0.7.0's)
  - 'observed: gh release view v0.17.0 -R weftgo/weft --json assets lists panel-v0.17.0.js and panel-v0.17.0.js.sha256 (v0.16.0, v0.15.0 and v0.10.0 the same names); gh release download v0.17.0 -p ''panel-v0.17.0.js*'' then sha256sum -c printed panel-v0.17.0.js: OK; its hash 346ef1da… equals sha256sum studio/dist/panel/panel.js at v0.17.0'
  - weft/studio/web/npm/package.json:2-3 (name, version 0.20.2), 27-32 (sideEffects), 34-60 (exports), 61-65 (files), 69-71 (engines node >=18), 72-74 (publishConfig), 75-90 (optional peers react >=18, vue >=3, svelte >=3)
  - 'weft/studio/web/src/npm/index.ts:30 (Position: six values), 40 (Mode), 44-80 (MountOptions incl. publicId), 261-339 (mount), 395-397 (isOpen is a function here)'
  - 'weft/Makefile:169-170 (studio-build: bun install, bun run build), 209-213 (devtools-npm), 228-237 (devtools-vite-check)'
  - 'weft/studio/web/package.json:7 (build: the panel build, the npm build, npm-package.ts)'
  - weft/examples/devtools-vite/README.md:1-74, src/main.ts:1-18, index.html:18-25, vite.config.ts:1-16
  - 'weft/CHANGELOG.md:1969 (npm review fixes: publishConfig, prepublishOnly, engines, mount waits for <body>, idempotent, enabled, Position, mode/push/zIndex), 1986 (devtools-vite-check pinned), 2005 (the npm import never takes the app''s script for its tag), 2198 (examples/devtools-vite), 2272 (@weftgo/devtools assembled, unpublished until a release publishes it), 2543 (panel-config.json), 2549 (the configuration ladder), 3446 (attribute changes and remounts), 4575 (the panel element, a separate library-mode build), 4592 (GET /panel.js, static, unauthenticated), 4597 (data-* mounting, the debug override, the version check, fail silent)'
  - docs-site/examples/devtools/main_test.go:TestPanelFilesResolve
  - 'observed: npm view @weftgo/devtools is E404 on 2026-10-18; make devtools-npm in a clean export of v0.17.0 assembles studio/web/npm (panel.js sha256 346ef1da… equal to studio/dist/panel/panel.js) and npm pack writes weftgo-devtools-0.17.0.tgz; npm install --save-dev <tgz> in a fresh app; node imports of every subpath; make devtools-vite-check prints DEVTOOLS VITE CHECK PASS'
  - 'observed: Chromium (Playwright 1.62.0) against docs-site/examples/devtools (setup A) and a scratch weft studio v0.17.0 (setup B, dev token): the script tag, data-endpoint + data-token, weft:* meta tags, a dead endpoint (self-mounted dock removed; <weft-devtools> shows Studio not reachable at … · retry), and examples/devtools-vite under vite dev with mount()'
  - 'weft/studio/web/src/panel/state.ts:2055-2068 (start: a fetchMeta failure, or a 200 that is not Studio''s meta, sets gone; 401/403 walled)'
  - weft/studio/web/src/panel/client.ts:524-544 (panelGet throws on any non-2xx answer)
  - 'weft/studio/web/src/panel/element.ts:2436-2474 (no Studio: the self-mounted dock is removed, a mount the host made goes dormant), 2850-2862 (the not-reachable line)'
  - 'weft/studio/auth.go:259-266 (setup A: 403 for a non-loopback Host), 287-303 (401 the API requires a token; 401 bad or expired token), 741-792 (cors wraps every route, /panel.js included; originAllowed: with a Token and no list, http or https on localhost or 127.0.0.1, any port)'
  - 'weft/studio/studio.go:412-420 (routed: cors over the API, ingest and the default mux)'
  - 'weft/cmd/weft/main.go:475-494 (the extras weft studio passes: Manifest, Playground, Retain, Pricing), 875-907 (newServer: Base, Token, those extras, Open or DB; no AllowOrigins option, no flag or env var for it)'
  - 'weft/studio/auth.go:775-784 (originAllowed: a configured list replaces the localhost default)'
  - 'weft/cmd/weft/main.go:445-446 (--addr default: $WEFT_STUDIO_ADDR, else 127.0.0.1:7331, or the next free port in 7331–7340)'
  - 'observed: a scratch weft studio v0.17.0 (--rotate-token between two starts) and curl: no bearer 401 the API requires a token: Authorization: Bearer <token>; a wrong bearer, an expired 2 s panel token, the old dev token and a panel token minted before --rotate-token all 401 bad or expired token; a preflight from http://localhost:5173, https://localhost:3000, http://localhost and http://127.0.0.1:8080 got Access-Control-Allow-Origin, one from http://app.localhost:5173, http://[::1]:5173, http://127.0.0.2:5173, http://192.168.1.5:5173 and http://myapp.test:5173 got none'
  - 'observed: Chromium 151 (Playwright, local-network-access checks off) against that Studio: a script-tag dock with a bad data-token was removed, a <weft-devtools> with it showed Studio not reachable at http://127.0.0.1:7381/ · retry, the console held only the browser''s Failed to load resource: the server responded with a status of 401 (Unauthorized); from http://app.localhost:7382 Studio''s /panel.js was blocked by CORS (no panel, the element left empty); a same-origin copy of panel.js from http://app.localhost:7382 and http://[::1]:7382 had /api/meta blocked by CORS and showed Studio not reachable on the element'
---

# 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](#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](https://weftgo.dev/docs/observe/devtools/scope/#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`:

```go title="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)
})
```

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

The page's tag is:

```html
<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](https://weftgo.dev/docs/observe/devtools/scope/) shows how a page names one.

![The weft devtools panel docked on the right of an app page, its Story tab showing a step's tool calls and their errors](https://weftgo.dev/docs/_astro/panel-docked-right.light.BuHdPlbl.webp)

## The script tag

[`studio.Handler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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:

```html
<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](#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](https://weftgo.dev/docs/observe/devtools/security/).

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>`, unless `data-auto="false"`. That dock is the panel's own. If no Studio answers its `/api/meta` request, it removes itself, unless you named a loopback endpoint ([When the panel does not connect](#when-the-panel-does-not-connect)). A Studio that answers 401 or 403 never removes it.
- **A mount you made** (your `<weft-devtools>`, or `mount()` from npm) stays when no Studio answers, and shows one line, `Studio not reachable at <endpoint> · retry`. While a retry asks again, `retry` reads `checking…`.
- **Attribute changes apply live.** The element watches every field in the table below except `data-mode` and `data-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=debug`** in the page URL, or `debug: true` under `localStorage["weft.devtools"]`, mounts the dock even with `data-auto="false"`: a switch for a staging page. The older `localStorage.weft_debug=1` is migrated into that key.

### 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> · retry` instead: 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](#example-vite-app) does.
- Embed Studio in a Go program with [`studio.AllowOrigins`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#AllowOrigins) listing the page's origin. The list replaces the default: with `AllowOrigins("http://192.168.1.5:5173")` alone, a page on `http://localhost:5173` loses 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

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:

```sh
curl -s http://127.0.0.1:8080/studio/panel-config.json
```

```text
{"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`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/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

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](https://github.com/weftgo/weft/releases/tag/v0.20.2). 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:

```sh
gh release download v0.20.2 -R weftgo/weft -p 'panel-v0.20.2.js*'
sha256sum -c panel-v0.20.2.js.sha256
```

```text
panel-v0.20.2.js: OK
```

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

```html
<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

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](https://weftgo.dev/docs/observe/devtools/scope/#rung-1-explicit)) |
| `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](https://weftgo.dev/docs/observe/devtools/scope/#detection-switches)) |
| `data-position` | `weft:position` | `position` | `bottom-right` | Where the dock starts ([Lay out the panel](https://weftgo.dev/docs/observe/devtools/layout-and-theme/)) |
| `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](https://weftgo.dev/docs/observe/devtools/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`:

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

## npm

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

> **Not on the npm registry:** At v0.20.2 the package is assembled in weft's repository but not published: `npm install @weftgo/devtools` from the registry fails with E404. Build it from a weft checkout at the same tag as your Studio, then install the tarball.

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

From a clone of weft at `v0.20.2`, with Bun and npm on the `PATH`:

```sh
git clone --branch v0.20.2 https://github.com/weftgo/weft
cd weft
make devtools-npm
cd studio/web/npm && npm pack
```

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

```text
weftgo-devtools-0.20.2.tgz
```

### Install it in your app

```sh
npm install --save-dev /path/to/weft/studio/web/npm/weftgo-devtools-0.20.2.tgz
```

npm 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

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:

```ts
import "@weftgo/devtools"
```

Or mount it yourself, which takes configuration rung 1:

```ts

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](https://weftgo.dev/docs/observe/devtools/scope/#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:

```ts
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-scope` marker that `useWeftDevtools` or `weftDevtools` sets (rung 3);
- a `Weft-Scope` response 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](https://weftgo.dev/docs/observe/devtools/scope/#the-detection-ladder)).

### 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](https://weftgo.dev/docs/observe/devtools/scope/#rung-1-explicit)) |
| `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](https://weftgo.dev/docs/observe/devtools/host-api/) 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](https://weftgo.dev/docs/observe/devtools/scope/#framework-helpers).

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

weft's [`examples/devtools-vite`](https://github.com/weftgo/weft/tree/v0.20.2/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:

```ts

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

```sh
make devtools-vite-check
```

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

```text
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.js
DEVTOOLS VITE CHECK PASS
```

For the live demo, once the check has installed the package, run in two terminals:

```sh
weft dev -- go run ./examples/studio-local        # repository root
cd 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

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:

```go title="devtools/main.go"
// 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)
	}
}
```

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

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/devtools) · from `docs-site/examples`:

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

```text
app: 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

- **Keep `data-weft` on 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 by `window.__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.js` is embedded in the Studio of the same version; a copied or npm-installed panel older than Studio says `Studio 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-token` and `weft:token` are 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 loads `panel.js` and its self-mounted dock whatever `mount()`'s `enabled` says; only the helpers' `enabled: false` loads 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 with `vite 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 token` line: a 401 is a missing, expired or rotated token, a 403 setup A on a `Host` it 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 `localhost` or `127.0.0.1` for a dev page against `weft studio`.** Any other page origin gets no panel; [When the panel does not connect](#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-npm` at a different tag gives a panel of a different version. (Source: `studio/README.md:1446-1450`; `AGENTS.md:400`)

## See also

- [Scope the panel to a conversation](https://weftgo.dev/docs/observe/devtools/scope/)
- [Lay out and theme the panel](https://weftgo.dev/docs/observe/devtools/layout-and-theme/)
- [Drive the panel from your page](https://weftgo.dev/docs/observe/devtools/host-api/)
- [Secure the devtools panel](https://weftgo.dev/docs/observe/devtools/security/)
- [Run Studio: embedded, local binary or hosted](https://weftgo.dev/docs/observe/studio/setup/)

Symbols used: [`studio.Handler`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#Handler) · [`studio.DB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#DB) · [`studio.AllowOrigins`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/studio#AllowOrigins) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) · [`scope.Header`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/scope#Header)
