---
title: Develop with weft dev
description: 'Run Studio and your app with one command: weft dev sets the four variables your app needs, restarts it on every .go save, and finds or reuses Studio through the dev token, the discovery file and the port policy.'
url: https://weftgo.dev/docs/observe/weft-dev/
type: how-to
sources:
  - 'W11-auditB2-fix, v0.20.2: weft/cmd/weft/discovery.go:100-110 (reuseNotes: wrote no discovery file); weft/cmd/weft/dev.go:264-270; weft/internal/discovery/discovery.go:310-319'
  - 'weft/otel/pipeline.go:224-236 (Start: a Studio or a Local named in code, NoDiscovery and WEFT_STUDIO_URL switch the discovery read off), 276-279 (joined the running Studio, its hint names otel.NoDiscovery()), 342-360 (Install: the default Local added only when nothing else is found)'
  - weft/otel/options.go:127-139 (NoDiscovery), 214-227 (Local switches the discovery file off)
  - 'weft/runtime/options.go:300-312 (beside an installed Local-only pipeline: no link, one WARN)'
  - 'weft/CHANGELOG.md:125 (0.19.0: otel.NoDiscovery), 154 (0.19.0 breaking: an explicit otel.Local switches the discovery file off; runtime.Install follows; NoGlobal is not installed), 43 (0.20.0: one resolver for weft runs, open, export, doctor and mcp)'
  - 'W11-auditB1-fix, v0.20.2: weft/cmd/weft/dev.go:95-98 (Usage: run a package or a module build, never go run main.go); weft/core/manifest.go:254-306 (sourceRel, mainPath: command-line-arguments has no path, so main/f.go)'
  - 'weft/cmd/weft/dev.go:25-33 (four variables), 35-42 (5 s stop grace, 300 ms debounce), 48-49 (5 s runtime wait), 64-68 (skipped directories), 71-143 (the flags; the banner''s notes are dropped), 108-111 (default command go run .), 119-125 (--watch must be a directory), 145-151 (signals armed first), 197-233 (devEnv), 252-384 (devStudio: reuse, rotate line, discovery file), 386-397 (0.0.0.0 handed over as 127.0.0.1), 415-475 (the loop: restart, exit lines, --no-watch exit code, 127), 522-571 (the start line), 573-599 (newRuntime: a runtime not listed before the start)'
  - 'weft/cmd/weft/devproc.go:20-41 (startChild: own group; stdin not the terminal), 43-56 (stop: signal, 5 s, SIGKILL)'
  - weft/cmd/weft/devproc_unix.go:12-18 (Setpgid), 62-74 (devSignals; SIGHUP sent as SIGTERM)
  - weft/cmd/weft/devproc_linux.go:6-11 (Pdeathsig SIGTERM for go run only)
  - weft/cmd/weft/devproc_windows.go:14 (no process group), 33 (no SIGHUP)
  - 'weft/cmd/weft/devwatch.go:14-25 (watchGo: debounce, new directories, lock files, watch errors), 105-110 (isGoSource)'
  - weft/cmd/weft/token.go:17-30 (the dev token), 47-52 (printable), 56-82 (resolveToken), 84-114 (stableProbe, probeToken)
  - weft/cmd/weft/discovery.go:18-31 (written once bound, removed on a clean exit; a reuse writes nothing), 46-60 (announce), 100-112 (reuseNotes), 113-115 (refreshed hourly)
  - weft/cmd/weft/main.go:54-67 (the discovery file and its readers), 80-102 (the port policy), 163-203 (weft dev), 504-514 (--addr, then WEFT_STUDIO_ADDR, both pin), 842-859 (the banner's token lines)
  - 'weft/internal/discovery/discovery.go:1-42 (the file, its locations, trust and readers), 65-69 (24 h, 64 KiB), 99-114 (DefaultDirs), 121-140 (Stale), 162-210 (Write: stale files removed; a displaced live file remembered), 212-233 (Remove restores it), 236-260 (Refresh), 264-276 (GuardDir), 353-377 (Lookup: WEFT_STUDIO_URL, WEFT_DISCOVERY=off)'
  - weft/internal/discovery/trust_unix.go:17-30 (mode 0600, this user)
  - 'weft/internal/discovery/discovery.go:118-138 (Stale: every reason, the one-minute future slack, pid <= 0), 364-372 (the two Debug lines)'
  - 'weft/cmd/weft/discovery.go:48-60 (announce: studio: no discovery file (…); apps need WEFT_STUDIO_URL=<url>)'
  - 'weft/internal/listen/listen.go:168-192 (the skipped lines, every port busy), 221-277 (probe: each reason)'
  - 'weft/internal/listen/listen.go:1-34 (the policy), 56-67 (7331, span 10, 2 s probe), 144-192 (Choose), 221-284 (probe: the reasons)'
  - weft/runtime/options.go:285-332 (WEFT_ENV=dev; otel.StudioEndpoint, then the discovery file; else no link and a WARN)
  - weft/otel/pipeline.go:218-236 (the discovery file read once, in Start); weft/cmd/weft/dev.go:156-183 (Studio bound before the app starts)
  - weft/README.md:412-461 (the dev token and the discovery file), 497-560 (weft dev)
  - weft/AGENTS.md:202-208 (block 6, the discovery file), 419-422, 449-463 (block 7, weft dev and the port policy)
  - weft/CHANGELOG.md:2447-2470 (0.11.0, weft dev), 2471-2484 (the port policy, WEFT_STUDIO_ADDR), 2520-2537 (the discovery file)
  - docs-site/factcheck/studio-2.md (several Studios stopped at once can leave a studio.json; WEFT_DISCOVERY=off affects readers only)
  - docs-site/factcheck/playground.md (under weft dev without otel.Install, runtime.Install opens no link)
  - docs-site/examples/cli/main.go, main_test.go:TestServeRecordsTwoRuns
  - 'observed: weft v0.17.0 dev on a scratch module requiring weft v0.17.0 (the example''s main.go), with XDG_RUNTIME_DIR and XDG_CACHE_HOME in a scratch directory; a restart on save, a build failure, Ctrl-C, --no-watch, reuse and the next port captured'
  - 'weft v0.20.2: cmd/weft/dblock.go:15-22 (one Studio per database file, the lock before the port policy, weft dev reuses), 24-38 (lockPath: symlinks resolved), 64-89 (dbHolder: the lock file''s holder under ReadHolder''s rules, else a trusted discovery file), 91-110 (heldError, alreadyRunning: the refusal''s words); cmd/weft/main.go:640-668 (weft studio: lock, then Choose with Known; a lockless Studio on the file is refused too); cmd/weft/dev.go:264-308 (weft dev reuses the holder, else probes, else refuses), 155-167, 370-384 (tokenLine: the three token lines), 556-566 (the start line''s embedded-Studio clause); internal/listen/listen.go:95-102, 149-151 (Request.Known probed first), 130-136 (ReuseLine); weft/AGENTS.md:456-462 (block 7: the lock and the port policy); weft/CHANGELOG.md:54 (0.20.0: the token line, the embedded-Studio clause), 83 (0.20.0 Breaking: one Studio per SQLite file)'
  - 'weft/examples/studio-local/main.go:40-69 (under weft dev, 8080, the export and runtime link to WEFT_STUDIO_URL''s Studio, the panel tag from that Studio with data-endpoint and a minted playground panel token, runtime.Sessions, the embedded /studio/ without the playground), 292 (Playground only without WEFT_STUDIO_URL); weft/CHANGELOG.md:106 (0.19.0: examples/studio-local under weft dev)'
---

# Develop with weft dev

`weft dev` runs Studio and your app with one command. It starts Studio in-process exactly as [`weft studio`](https://weftgo.dev/docs/reference/cli/#weft-studio) does, runs your app beside it with the four variables the app needs to find that Studio, and restarts the app on every `.go` save. Run it from your app's module; the app's command goes after the flags (after `--` when it has flags of its own) and defaults to `go run .`:

```sh
weft dev
```

```text
studio http://127.0.0.1:7331/ · app pid 2825860 · runtime rt_921efe69d315c004 registered
```

That is the one line each start prints: Studio's link, the app's pid, and the [playground](https://weftgo.dev/docs/reference/glossary/#playground) runtime the app registered. The app's own output passes through around it. For that line the app calls [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) and [`runtime.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Install), with no Studio URL or token in its code:

```go title="cli/main.go"
defer otel.Install()() // under weft dev: exports to WEFT_STUDIO_URL with WEFT_STUDIO_TOKEN

agt := newAgent()
defer runtime.Install(runtime.Agents(agt))() // WEFT_ENV=dev: registers with that Studio
```

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

<span id="weft-dev"></span>

## Run your app beside Studio

`weft dev` takes all of `weft studio`'s flags (`--addr`, `--db`, `--token`, `--rotate-token`, `--manifest`, `--open`, `--no-playground`, `--retain`, `--pricing`, `--log-level`, `--log-format`) and follows the same [port policy](#the-port-policy), with the playground on. It adds two of its own, which shape the dev loop and have no environment mirror:

- `--watch dir` names a directory to watch for `.go` changes. It is repeatable, and the list replaces the default, the working directory.
- `--no-watch` turns watching off. `weft dev` then exits with the app's exit code, or 127 when the command cannot start.

Run a package (`go run .`, `go run ./cmd/app`) or a module build, never `go run main.go`. A file list has no build info, so the manifest names its tool sources `main/…` and its runs read stale against `weft.json` ([`source`](https://weftgo.dev/docs/guides/manifest/#what-the-file-holds)). `weft dev -h` prints the same warning.

Pass a command after the flags to run something other than `go run .`. Flag parsing stops at the first word that is not a flag, so `--` is needed only when the command has flags of its own; it is always safe:

```sh
weft dev -- go run ./cmd/app
```

```text
answered: Order 42 has shipped.
failed: weft: run failed at step 1: weft: run exceeded the maximum number of steps
studio http://127.0.0.1:7331/ · app pid 2825860 · runtime rt_921efe69d315c004 registered
studio: shutting down (interrupt)
```

The first two lines are the app's; the last follows Ctrl-C. `weft studio`'s banner is not printed: the start line replaces it, so the manifest, retention and pricing notes do not appear. Only a rotated token is said, as `studio: token rotated: a new one in <path>`, and a discovery file that could not be written, as `studio: no discovery file (…); the app gets WEFT_STUDIO_URL regardless`.

Everything `weft dev` does is something you can do by hand: `weft studio` in one terminal, and the app started with the variables below in another, is the same setup without the command.

## The environment weft dev sets

The app's environment is yours plus four variables:

| Variable | Value | What reads it |
|---|---|---|
| `WEFT_ENV` | `dev`, unless your shell set `WEFT_ENV` to something non-empty | `runtime.Install`, which opens the playground link only under `dev` (or [`runtime.Enabled(true)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Enabled)) |
| `WEFT_STUDIO_URL` | the Studio's URL | `otel`'s Studio destination; `runtime.Install` dials that destination |
| `WEFT_STUDIO_TOKEN` | the token the Studio serves: the stable one, a fixed one or a generated one | the same two |
| `WEFT_DB` | the Studio's SQLite file, absolute; not set for a database with no file or ClickHouse | `otel.Local("")`'s path, so a local sink and Studio share one file |

The last three replace whatever your shell had, so the app and Studio always agree. A run with `env` as the command shows them (the token and the path shortened):

```sh
weft dev --no-watch -- sh -c 'env | grep ^WEFT_ | sort'
```

```text
WEFT_DB=~/support/.weft/weft.db
WEFT_ENV=dev
WEFT_STUDIO_TOKEN=<token>
WEFT_STUDIO_URL=http://127.0.0.1:7331
studio http://127.0.0.1:7331/ · app pid 2822350 · no runtime registered (the app stopped first)
weft dev: app pid 2822350 exited (exit code 0)
studio: shutting down (terminated)
```

A `WEFT_ENV` you set yourself is kept:

```sh
WEFT_ENV=staging weft dev --no-watch -- sh -c 'echo $WEFT_ENV'
```

```text
staging
studio http://127.0.0.1:7331/ · app pid 2822367 · no runtime registered (the app stopped first)
weft dev: app pid 2822367 exited (exit code 0)
studio: shutting down (terminated)
```

`otel.Install()` with no options reads `WEFT_STUDIO_URL` and `WEFT_STUDIO_TOKEN` and exports every run to that Studio; with a destination from the environment it writes no local sink of its own. `runtime.Install` dials the pipeline's Studio destination, `otel.StudioEndpoint()`. Without `otel.Install` there is no such destination, and the discovery file is not read because `WEFT_STUDIO_URL` is set, so `runtime.Install` logs `weft/runtime: no Studio to dial: no link opened` and the start line waits in vain. A Studio bound to every interface (`--addr 0.0.0.0:7331`) is handed to the app, and printed, as `127.0.0.1`.

## Read the start line

Each start prints one line once its runtime registers, or after five seconds:

| Line ends with | Meaning |
|---|---|
| `runtime rt_… registered` | A runtime this Studio did not list before the app started registered within five seconds |
| `no runtime registered yet (the app needs runtime.Install; WEFT_ENV=dev is set), or the app links its own embedded Studio` | None yet: the app installs no runtime, or links its own Studio in-process (`runtime.Local`) rather than this one (the clause after the comma since 0.20.0). When one registers later, a second line says `weft dev: runtime rt_… registered (app pid n)` |
| `no runtime registered (the app stopped first)` | The app exited, or was stopped, before one registered |
| `playground off (--no-playground): no runtime link` | `--no-playground`: there is nothing to register with |
| `the Studio's playground is off: no runtime link` | `weft dev` reused a running Studio that was started with `--no-playground` |

The link is bare: the stable token and a fixed `--token` stay out of the log. Only a token generated for a database with no file is added as `#token=`, since nobody holds it otherwise. The pid is the command's (for `go run .`, the `go` process), not the binary `go run` builds and starts.

## Restart on save

A `.go` change under a watched directory restarts the app after 300 ms of quiet, so an editor's write-and-rename or a `gofmt` pass is one restart. The restart sends SIGTERM to the app's process group, waits up to five seconds, sends SIGKILL to what is left, and runs the command again:

```text
weft dev: main.go changed; restarting the app
answered: Order 42 has shipped.
failed: weft: run failed at step 1: weft: run exceeded the maximum number of steps
studio http://127.0.0.1:7331/ · app pid 2817781 · no runtime registered yet (the app needs runtime.Install; WEFT_ENV=dev is set), or the app links its own embedded Studio
```

That restart's line reads `no runtime registered yet …` although the app did register: a runtime id is stable per service, working directory and agents, so the restarted app re-registered with the id Studio already listed. The playground's runtime list shows it connected. The same holds for a second `weft dev` over the same database: Studio restores the runtimes it knew, the id is already listed, and the line reads `no runtime registered yet` with no later `registered` line.

A build failure is printed, and the next save retries:

```text
weft dev: broken.go changed; restarting the app
# example.com/support
./broken.go:2:14: syntax error: unexpected {, expected )
studio http://127.0.0.1:7331/ · app pid 2818789 · no runtime registered (the app stopped first)
weft dev: app pid 2818789 exited (exit code 1); a .go save restarts it
```

The watcher skips `.git`, `node_modules`, `vendor`, `testdata`, `.weft` and `dist`. A directory that arrives with `.go` files in it (a checkout, a `mv`, a `git stash pop`) is a change too; an editor's lock file (`.#name.go`) and a permission change (`touch`) are not. A directory below a watched root that cannot be watched (inotify's `max_user_watches` spent) is one line, never a stop; a root that cannot be watched stops the start.

## Stop weft dev

Ctrl-C, SIGTERM and SIGHUP (the terminal closing) stop the app first, with the same signal (SIGHUP is sent as SIGTERM, which many servers do not take as "reload"), then Studio, and `weft dev` exits 0. With `--no-watch` the app's own exit ends `weft dev` with the app's code:

```sh
weft dev --no-watch -- sh -c 'exit 3'
```

```text
studio http://127.0.0.1:7331/ · app pid 2822388 · no runtime registered (the app stopped first)
weft dev: app pid 2822388 exited (exit code 3)
studio: shutting down (terminated)
```

The exit code is 3. With `--no-watch`, a command that cannot start is exit 127 (without it, `weft dev` waits for the next save): `weft dev: could not start "no-such-command": exec: "no-such-command": executable file not found in $PATH`.

The app runs in a process group of its own, so the stop reaches `go run`'s child, the app binary, too, and the terminal's Ctrl-C reaches `weft dev` only. Its stdin is not the terminal. A SIGKILL of `weft dev` cannot be caught: on Linux `go run` still gets SIGTERM, but the binary it started can be orphaned. On Windows there is no process group and no SIGHUP.

## The dev token

`weft dev` and `weft studio` serve one token, resolved once at start:

1. `--token`, else `WEFT_STUDIO_TOKEN`: a fixed token. The token file is left alone.
2. Else the database's token file, `<db>.token` beside the SQLite file (`./.weft/weft.db.token` by default): 32 random bytes, base64url, mode 0600. The first start creates it; every later start serves the same token. `--rotate-token` writes a new one.
3. Else, for a database with no file (`sqlite://:memory:`, ClickHouse), a token generated for this process.

The stable token is the panel tokens' signing key, like a fixed one, so it is never printed: `weft studio`'s banner names its file (`studio: token from ~/work/.weft/weft.db.token (stable for this database; --rotate-token renews it)`), and `weft dev`'s start line leaves it out. Only the generated token is printed. Because it is stable, a restart keeps the browser tab, the app's `WEFT_STUDIO_TOKEN` and the discovery file valid. A client reads it from the file:

```sh
export WEFT_STUDIO_TOKEN=$(cat .weft/weft.db.token)
```

Since 0.20.0, when `weft dev` opens no browser it prints where the token is, before the start line: `studio: token: .weft/weft.db.token (weft open --with-token)`, or `studio: token: the one --token / WEFT_STUDIO_TOKEN set` for a fixed one. When it reused a running Studio whose token is not the one in the file, the line reads `studio: token: the running Studio's, not .weft/weft.db.token (weft open --with-token)`, so it never points at a file that would not sign in. A generated token needs no such line: it is in the start line's link.

`--rotate-token` on a start that reuses a running Studio is not applied: `studio: --rotate-token not applied: the running Studio keeps its token (stop it, then start with --rotate-token)`. When no fresh [discovery file](#the-discovery-file) names the reused Studio, as when it was started with `WEFT_DISCOVERY=off` or by an app embedding `studio.New`, the start adds `studio: the running Studio wrote no discovery file; apps need WEFT_STUDIO_URL=http://<addr>`: an app started by hand will not find it, so set that variable. An app `weft dev` starts gets it already.

## The discovery file

Once its listener is bound, a Studio that `weft studio` or `weft dev` started writes `studio.json`, naming itself, and removes it on a clean exit. An app's `otel.Install()` and `runtime.Install()` read it when `WEFT_STUDIO_URL` is unset and the code names no Studio or Local store, so an app started by hand in the same directory joins the running Studio with no configuration, one INFO line naming it. `runtime.Install` reads it only when its link is on (`WEFT_ENV=dev`, or `runtime.Enabled(true)`), no `runtime.Studio` or `runtime.Local` option names a Studio, and the installed pipeline is not a Local store without a Studio ([below](#the-discovery-file)). They read it once, at `Install`: an app started before `weft studio` never joins it, so start Studio first or restart the app. An app under `weft dev` is not affected, because Studio is bound before the app starts. `weft mcp` reads it too.

```text
{
  "url": "http://127.0.0.1:7331",
  "token": "<token>",
  "db": "~/support/.weft/weft.db",
  "pid": 2812038,
  "started": "2026-10-18T10:29:05Z",
  "version": "v0.20.2"
}
```

That is the file of the first `weft dev` above, with the token and the `db` path shortened; on disk `db` is absolute. It goes to the first of:

1. `./.weft/`, when that directory exists. After a default start it always does, so the file lands there: run the app from the directory you ran Studio in, or set `WEFT_STUDIO_URL`.
2. `$XDG_RUNTIME_DIR/weft/`, when `XDG_RUNTIME_DIR` is set to an absolute path (Linux).
3. The user cache directory's `weft/` (macOS, Windows, bare containers).

A reader takes the first file it trusts in the same order. It trusts a file only when it is a regular file of at most 64 KiB, its URL is loopback (`127.0.0.0/8`, `::1`, `localhost`), it is fresh (its pid alive, started under 24 hours ago) and, on unix, it is mode 0600 and owned by the reader. A `studio.json` committed to git (0644) or naming another host is never used. Anything untrusted is skipped with a Debug line, `weft: discovery file ignored` with the file's error or `weft: discovery file ignored (stale)` with one of these reasons, and the next writer removes it:

| `why` | The file |
|---|---|
| `names no url` | has an empty `url` |
| `its url "…" is not a loopback http(s) address` | names another host, a scheme other than `http` or `https`, or a URL with a user part |
| `carries no started time` | has a zero `started` |
| `started 25h0m0s ago (more than 24h0m0s)` | is 24 hours old or more |
| `started in the future` | has a `started` more than one minute ahead of the reader's clock |
| `pid N is not running` | names a pid of 0 or less, or a dead process |

On unix the file's error reads `mode 0644, not 0600` or `owned by uid N, not this user (M)`. A running Studio re-stamps its file every hour, so it stays fresh past 24 hours.

The writer also drops a `.gitignore` (`*`) into `./.weft` when there is none, so the database, its token and the file stay out of commits. Two live Studios never erase each other's file: the second one's exit puts the first's back. A start that reuses a running Studio writes nothing. When `weft studio` cannot write the file it serves anyway and says so in its banner: `studio: no discovery file (<error>); apps need WEFT_STUDIO_URL=<url>`.

The file is a convenience, never a requirement:

- `WEFT_STUDIO_URL` always wins: when it is set the file is not read. That is why an app under `weft dev` never reads it.
- `WEFT_DISCOVERY=off` turns the read off for apps and `weft mcp`. Since 0.18.0 it also stops `weft studio` and `weft dev` from writing the file, and the start says so in one line: `studio: no discovery file written (WEFT_DISCOVERY=off)`.
- **A store named in code switches the read off.** [`otel.Studio`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Studio)`(url, tok)` or, since 0.19.0, [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local)`(path)`: the pipeline writes only to the stores it names and the environment's (`WEFT_STUDIO_URL`, `OTEL_*`), never into a Studio it found on disk. `otel.Install()` with no destination still reads the file; its default Local store is added only when nothing else is found. An `otel.OTLP`, `Datadog`, `Langfuse` or `Exporters` destination does not switch the read off.
- [`otel.NoDiscovery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoDiscovery)`()` skips the file and nothing else: `WEFT_STUDIO_URL`, the `OTEL_*` destinations and the `WEFT_ENV` development gate are read as usual. It is the per-pipeline form of `WEFT_DISCOVERY=off`, for a test or harness that keeps the operator's destinations but must not write into a Studio found on disk. The package example [`ExampleNoDiscovery`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#example-NoDiscovery) shows it. [`otel.NoEnv`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoEnv)`()` ignores the file with the rest of the environment.
- **The runtime link follows the installed pipeline.** Beside an installed pipeline that records into a Local store and names no Studio, `runtime.Install` opens no link and logs one WARN: `weft/runtime: the pipeline records only into a Local store (otel.Local, or otel.Install's default) and names no Studio: no link opened`. Dial setup A's embedded Studio with [`runtime.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Local)`(srv)`, or a running one with [`runtime.Studio`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Studio)`(url, tok)` beside `otel.Studio(url, tok)`. A pipeline started with `otel.NoGlobal()` is not installed, so the rule does not see it: there `runtime.Install` without `runtime.Studio` or `runtime.Local` still joins a discovered Studio.

To record into your own store and a running Studio at once, name both: `otel.Install(otel.Local(path), otel.Studio(url, tok))`, or set `WEFT_STUDIO_URL`.

`weft runs`, `weft open`, `weft export`, `weft doctor` and `weft mcp` find the Studio in one order: `--url`, else `WEFT_STUDIO_URL`, else the discovery file (`WEFT_DISCOVERY=off` skips it), else `http://127.0.0.1:7331` ([Use the weft command](https://weftgo.dev/docs/observe/cli/)).

## The port policy

**One Studio per database file.** Since 0.20.0 `weft studio` and `weft dev` take an exclusive lock on `<db>.lock` beside a SQLite file (`flock`, `LockFileEx` on Windows) before anything else, and hold it while they serve; the kernel releases it when the process ends, a crash included. The lock stands for the file a symlink resolves to. A second `weft studio` on a file that is held, from any directory and on any port, is refused, exit 1:

```text
weft: studio already running at http://127.0.0.1:7331 (pid 1683241) on ~/work/other.db: one Studio per database file — sign in to it with `weft open --with-token`, or stop it first
```

`weft dev` reuses the holder instead: it runs the app against that Studio, with its URL and the database's token, and stops only the app on exit. The holder is named only from this user's own lock file (mode 0600, a loopback address and a live pid), else from a trusted discovery file naming the same database. With neither, `weft dev` probes the ports below for it, and a `weft studio` refusal names the lock file instead of a Studio. ClickHouse takes no lock: it is a shared server by design. Before 0.20.0 a second `weft studio` on the same file said `…, reusing` and exited 0.

With the lock taken, the start looks for an address. `127.0.0.1:7331` is the one default, and the Studio your trusted discovery file names is probed first, whatever its port. When the wanted address is busy, the start asks `GET /api/meta` there and decides in one line:

- **A Studio already serving the same database file without its lock** (a weft before 0.20.0, or an app's embedded Studio): `weft dev` reuses it; `weft studio` is refused with the same `studio already running …` line.
- **Anything else moves Studio to the next free port in 7331–7340**: another program, a Studio on another database, or a Studio whose meta this token cannot read. One line names the skipped address and why, and the banner prints the real address.
- **All ten busy** is exit 1: `every port in 127.0.0.1:7331–7340 is busy (7331: <why>; 7332: <why>; …): free one or pin another with --addr`.

The `why` in those lines is one of:

| Reason | What answered on the busy port |
|---|---|
| `not a weft Studio` | No answer, a redirect, or a `GET /api/meta` that is not a Studio's |
| `a Studio that requires a token: set WEFT_STUDIO_TOKEN to its token to reuse it` | A 401 or 403, and this start had no token to send |
| `a Studio that requires a token, which goes to loopback only` | A 401 or 403; this start holds a token but did not send it, since the address is not loopback |
| `a Studio with another token` | A 401 or 403 to the token this start sent |
| `a Studio that serves no database path` | A Studio whose meta gives no `db.path` (a fileless database, or one that withholds the path from this caller) |
| `a Studio on another database, <path>` | A Studio on another file, or any Studio when this start has no database file |
| `a Studio on <path> (could not compare: <error>)` | A Studio whose file could not be compared with this start's |

```sh
weft dev --no-watch -- sh -c 'echo $WEFT_STUDIO_URL'
```

```text
studio already running at http://127.0.0.1:7331 (pid 2822868), reusing
http://127.0.0.1:7331
studio http://127.0.0.1:7331/ · app pid 2822888 · no runtime registered (the app stopped first)
weft dev: app pid 2822888 exited (exit code 0)
```

That was `weft dev` in the directory of a running `weft studio`. From a directory with its own `./.weft/weft.db`, the same start takes the next port:

```sh
weft dev --no-watch -- true
```

```text
studio: 127.0.0.1:7331 is busy (a Studio that requires a token: set WEFT_STUDIO_TOKEN to its token to reuse it); listening on 127.0.0.1:7332 instead (--addr pins one)
studio http://127.0.0.1:7332/ · app pid 2822900 · no runtime registered (the app stopped first)
weft dev: app pid 2822900 exited (exit code 0)
studio: shutting down (terminated)
```

The probe carries the fixed token (`--token`, `WEFT_STUDIO_TOKEN`) when there is one. Otherwise it carries the database's stable token, but only to an address your own trusted discovery file names; anything else holding a port is probed with no token, and a token goes to loopback only. A second start on the same file never gets that far: the lock decides it first, wherever it was started from.

`--addr` (or `WEFT_STUDIO_ADDR`) pins the address: busy is exit 1, never a probe or another port:

```sh
weft studio --addr 127.0.0.1:7331
```

```text
weft: listen on 127.0.0.1:7331 (pinned by --addr / WEFT_STUDIO_ADDR, no fallback): listen tcp 127.0.0.1:7331: bind: address already in use
```

## Approve from the page's panel

weft's own [`examples/studio-local`](https://github.com/weftgo/weft/tree/v0.20.2/examples/studio-local) shows the whole loop under `weft dev` (since 0.19.0): setup B for a page with the devtools panel.

```sh
weft dev -- go run ./examples/studio-local      # repository root; open http://127.0.0.1:8080/
```

With `WEFT_STUDIO_URL` set, the demo listens on `127.0.0.1:8080`, since `weft dev`'s Studio holds 7331. Its pipeline exports to that Studio besides its local sink, and its runtime link registers there with `runtime.Sessions`. The page's script tag loads `panel.js` from that Studio and names it in `data-endpoint`, scoped to the page's public id, `pub_demo`, with a panel token the app mints per page view through `POST /api/panel-tokens` (`"playground": true`, with `WEFT_STUDIO_TOKEN`). The server token never reaches the page, and no token rides a URL. So the panel, the runtime and `weft dev`'s Studio are one Studio: a refund the chat parks is approved from the page's panel, and Studio's `/runtimes` lists the app. The demo's embedded `/studio/` stays as the app's own read-only view, without the playground, since `weft dev`'s Studio owns the command store in the shared `WEFT_DB`. [Approve and steer your app's own turns](https://weftgo.dev/docs/observe/devtools/app-turns/) explains the approval path.

## Complete example

The app behind every output on this page records one run that answers and one that stops at its step budget, registers its agent with the playground, and waits until it is stopped:

```go title="cli/main.go"
// Command cli is the app the weft command's pages run under `weft dev`.
//
// It records two runs of a scripted support agent, one that answers and
// one that stops at its step budget, registers the agent with Studio's
// playground, and waits until it is stopped. Under `weft dev` it needs no
// configuration: otel.Install reads WEFT_STUDIO_URL and WEFT_STUDIO_TOKEN,
// and runtime.Install opens its link because WEFT_ENV=dev. main_test.go
// runs it offline.
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/otel"
	"github.com/weftgo/weft/runtime"
	"github.com/weftgo/weft/wefttest"
)

// LookupInput is lookup_order's input.
type LookupInput struct {
	OrderID string `json:"order_id" jsonschema:"the order to look up"`
}

// newAgent is a support agent with one tool, on a scripted model so the
// program runs offline. The script answers the first run in two steps and
// starts the second with a tool call.
func newAgent() *weft.Agent {
	lookup := weft.Tool("lookup_order", "Look up an order by ID.",
		func(ctx context.Context, in LookupInput) (string, error) {
			return "order " + in.OrderID + ": shipped", nil
		})
	model := wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{ID: "c1", Name: "lookup_order", Args: `{"order_id":"42"}`}),
		wefttest.Say("Order 42 has shipped."),
		wefttest.ToolCalls(wefttest.Call{ID: "c2", Name: "lookup_order", Args: `{"order_id":"43"}`}),
	)
	return weft.New(model, weft.Name("support-bot"), lookup)
}

// serve records the two runs, then waits for ctx. The runs use their own
// context, so a cancelled ctx still records them.
func serve(ctx context.Context, out io.Writer) error {
	defer otel.Install()() // under weft dev: exports to WEFT_STUDIO_URL with WEFT_STUDIO_TOKEN

	agt := newAgent()
	defer runtime.Install(runtime.Agents(agt))() // WEFT_ENV=dev: registers with that Studio

	res, err := agt.Generate(context.Background(), weft.Prompt("Where is order 42?"))
	if err != nil {
		return err
	}
	_, _ = fmt.Fprintln(out, "answered:", res.Text())

	// MaxSteps(1) lowers the budget for this run: the tool call needs a second step.
	if _, err := agt.Generate(context.Background(), weft.Prompt("Where is order 43?"), weft.MaxSteps(1)); err != nil {
		_, _ = fmt.Fprintln(out, "failed:", err)
	}
	<-ctx.Done()
	return nil
}

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	if err := serve(ctx, os.Stdout); err != nil {
		log.Fatal(err)
	}
}
```

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

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/cli). Its test runs it offline from `docs-site/examples`, with no Studio and no runtime link:

```sh
go test ./cli
```

```text
ok  	weftgo.dev/docs/examples/cli	0.023s
```

To run it under `weft dev`, copy `main.go` into a module that requires `github.com/weftgo/weft v0.20.2` and run `weft dev` there. Its first start compiles it, which can take longer than the five seconds the start line waits:

```text
studio http://127.0.0.1:7331/ · app pid 2812053 · no runtime registered yet (the app needs runtime.Install; WEFT_ENV=dev is set), or the app links its own embedded Studio
answered: Order 42 has shipped.
failed: weft: run failed at step 1: weft: run exceeded the maximum number of steps
weft dev: runtime rt_05aa67b84b44a147 registered (app pid 2812053)
```

## Best practices & gotchas

- **Call `otel.Install` in an app you run under `weft dev`.** `runtime.Install` dials the pipeline's Studio destination; without one, and with `WEFT_STUDIO_URL` set so the discovery file is skipped, it opens no link. (Source: `runtime/options.go:295-328`)
- **Run a hand-started app from Studio's directory, or set `WEFT_STUDIO_URL`.** `./.weft/studio.json` is found relative to the working directory only. (Source: `internal/discovery/discovery.go:9-16, 93-114`)
- **Start a scratch Studio under `WEFT_DISCOVERY=off`.** Since 0.18.0 it then writes no discovery file, so no app or `weft mcp` finds it by accident; before 0.18.0 the variable stopped readers only. (Source: `cmd/weft/discovery.go:24-29`; `internal/discovery/discovery.go:353-356`)
- **Stopping several Studios at the same moment can leave a `studio.json` naming a stopped one.** Readers ignore it, since its pid is dead, and the next Studio's start removes it. (Source: `internal/discovery/discovery.go:121-140, 162-233`)
- **Never run `go run main.go` under `weft dev`.** A file list has no build info, so its manifest sources read `main/…`. Studio's manifest check then counts the agent's runs stale. Run `go run .` or `go run ./cmd/app`. (Source: `cmd/weft/dev.go:95-98`; `core/manifest.go:254-306`)
- **Do not read stdin in an app under `weft dev`.** It runs in its own process group with stdin not attached to the terminal. (Source: `cmd/weft/devproc.go:20-23`)
- **Pin `--addr` only when you mean it.** A pinned busy address is exit 1, and turns off the reuse of a running Studio on the same database. (Source: `internal/listen/listen.go:154-160`)

## See also

- [Connect your app to Studio's playground](https://weftgo.dev/docs/observe/playground/connect/)
- [Use the weft command](https://weftgo.dev/docs/observe/cli/)
- [weft CLI reference](https://weftgo.dev/docs/reference/cli/#weft-dev)
- [Run Studio](https://weftgo.dev/docs/observe/studio/setup/)
- [Environment variables](https://weftgo.dev/docs/reference/env/#weft-discovery)

Symbols used: [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.Studio`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Studio) · [`otel.NoEnv`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#NoEnv) · [`otel.StudioEndpoint`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#StudioEndpoint) · [`otel.Local`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Local) · [`runtime.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Install) · [`runtime.Agents`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Agents) · [`runtime.Enabled`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Enabled) · [`runtime.Studio`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/runtime#Studio) · [`weft.New`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#New) · [`weft.Tool`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Tool) · [`weft.MaxSteps`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxSteps) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
