Make dev servers shareable from other devices

Browser dev is now single-origin: Vite proxies /api, /ws, /oauth, and
/.well-known to the backend, and dev/dev:web no longer bake
VITE_HTTP_URL/VITE_WS_URL into the bundle. Absolute localhost URLs in the
bundle sent any remote browser to its own machine, which no amount of
external path mapping could fix.

- `dev --share` publishes the web port on the tailnet and logs a pairing
  URL already built against that origin
- `dev:pair` mints a pairing URL for a running server, resolving port and
  state dir from server-runtime.json
- Ports derive from the worktree path, so each worktree is stable across
  restarts; the availability probe is loopback-only so `tailscale serve`
  can't push the port
- Web session cookies are port-scoped like desktop's, ending the
  cross-instance "Invalid session token signature" loop
- Dev startup pairing tokens last 24h instead of 5m; user-issued links
  keep the 5m default

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5 committed 2026-07-24 16:55:50 -07:00
1 parent 38cfc25e54
commit 9b1a64e4a9
18 files changed
+636 -66

No files matched your search

+57 -12
View File
@@ -13,9 +13,16 @@ Use this skill for the web client. For iOS Simulator, Android Emulator, or physi
2. Choose a base directory that belongs only to the current worktree or test:
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
3. Start the full web stack with `vp run dev --home-dir <base-dir>`. Add `--share`
to also publish it on the tailnet so the user can open it from another device
(see "Share a dev server with the user" below).
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
Ports are derived from the worktree path, so each worktree gets its own stable
pair that survives restarts. Read them from the dev-runner line rather than
assuming `5733`/`13773`; `node scripts/dev-runner.ts dev --dry-run` prints them
without starting anything.
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
@@ -42,20 +49,56 @@ Treat pairing URLs as secrets. Do not copy them into final responses, screenshot
## Recover a consumed or expired pairing token
Create another token against the same database and web URL as the running dev server:
Ask the running server for a fresh pairing URL:
```bash
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
--base-dir <base-dir> \
--dev-url <web-url> \
--base-url <web-url> \
--ttl 15m \
--label agent-ui-test
bun run dev:pair # implicit ~/.t3 home
bun run dev:pair -- --base-dir <base-dir> # explicit --home-dir environment
```
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
It reads the running server's own `server-runtime.json`, so it needs no port and
builds the URL against the web origin already in use — including a `--share`
tailnet URL. Pass `--base-dir` only when the dev server was started with
`--home-dir`, and pass exactly the same path: `--base-dir` switches the state
directory from `<base>/dev` to `<base>/userdata`, and a mismatch writes the token
to a database the server isn't reading. Add `--ttl 1h` for a longer window or
`--json` for machine-readable output.
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
Use the printed `Pair URL` once. If the command reports no running server, the
dev process has exited — restart it and use the URL from its own startup log.
Use `auth pairing list` to inspect active token metadata; it intentionally cannot
reveal token secrets. `auth pairing create` remains available for scripted cases
that need explicit control over every flag.
## Share a dev server with the user
When the user wants to try the change themselves — from their laptop, their
phone, or anything else on their tailnet — start the stack with `--share`:
```bash
bun run dev:share # or: vp run dev --share --home-dir <base-dir>
```
This publishes the web port over HTTPS on the machine's tailnet and prints
`[dev-runner] shared on tailnet: https://<host>:<port>/`. The pairing URL logged
right after is already built against that origin, so give the user that URL
verbatim — it is the deliverable, and it works unchanged on any of their devices.
Dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to
the backend, so one shared port covers the whole app. Do not map backend paths by
hand, and do not set `VITE_HTTP_URL`/`VITE_WS_URL` for a shared server — absolute
localhost URLs get compiled into the bundle and send the remote browser to its
own machine.
The mapping is removed when the dev server exits, and re-running `--share`
replaces any mapping left behind by a run that was killed. If the tailnet is
unavailable the dev server still starts and serves locally; the warning explains
what to fix.
Expect one failed `ws://localhost:<port>` HMR attempt in the remote console
before Vite falls back to the page origin. That is Vite's own hot-reload socket,
not the app's connection — ignore it.
## Inspect or seed SQLite state
@@ -83,7 +126,9 @@ If completion is uncertain, keep the environment alive and mention that it is re
## Troubleshoot predictably
- If the browser shows an unauthenticated pairing screen, issue a new token instead of retrying the consumed URL.
- If the pairing URL is no longer visible, create a replacement token with both `--dev-url` and `--base-url`.
- If the replacement token is rejected, verify that the CLI and server use the identical absolute base directory and web URL.
- If the pairing URL is no longer visible, run `bun run dev:pair`.
- If the replacement token is rejected, verify that the CLI and server resolve the same state directory — pass `--base-dir` only when the server was started with `--home-dir`, and use the same path.
- If the UI shows unexpected data, verify that every command uses the identical explicit base directory before editing anything.
- If ports move because another instance is running, trust the current dev-runner output rather than assuming ports `13773` and `5733`.
- If a remote browser reaches the page but the app cannot connect, check that the served bundle has no absolute `localhost` backend URL baked in: `VITE_HTTP_URL` and `VITE_WS_URL` must be unset for `dev`/`dev:web`.
- If a shared URL returns 403 with "host is not allowed", the hostname is outside `*.ts.net`; add it to `T3CODE_DEV_ALLOWED_HOSTS` (comma-separated).
+8
View File
@@ -13,6 +13,14 @@
- Subagents must not independently launch dev servers or repeat integrated client verification unless their delegated task explicitly requires it.
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
## Dev Servers
- Start the web stack with `bun run dev` (equivalently `vp run dev`). Never run `vp dev` from the repo root — that starts a bare Vite with no backend.
- Ports are derived from the worktree path, so each worktree has its own stable pair. Read them from the `[dev-runner] …` line; `--dry-run` prints them without starting anything.
- To let the user try a change on their own device, use `bun run dev:share`. It publishes the web port on the tailnet and logs a pairing URL already built against that origin — hand them that URL as-is. Details and troubleshooting live in the `test-t3-app` skill.
- Dev is single-origin: Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the backend. Do not set `VITE_HTTP_URL`/`VITE_WS_URL` for `dev`/`dev:web` — they compile absolute localhost URLs into the bundle and break every non-localhost origin.
- Need a pairing URL for a server that is already running? `bun run dev:pair`. It finds the server itself; no ports or flags to get wrong.
## Package Roles
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
+8 -1
View File
@@ -8,9 +8,13 @@ import * as ServerConfig from "../config.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import * as PairingGrantStore from "./PairingGrantStore.ts";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import { resolveSessionCookieName } from "./utils.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
/** Pinned so the session cookie name (which is port-scoped) is predictable. */
const TEST_SERVER_PORT = 13_773;
const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Service"]>) =>
Layer.effect(
ServerConfig.ServerConfig,
@@ -18,6 +22,7 @@ const makeServerConfigLayer = (overrides?: Partial<ServerConfig.ServerConfig["Se
const config = yield* ServerConfig.ServerConfig;
return {
...config,
port: TEST_SERVER_PORT,
...overrides,
} satisfies ServerConfig.ServerConfig["Service"];
}),
@@ -35,7 +40,9 @@ const makeCookieRequest = (
): Parameters<EnvironmentAuth.EnvironmentAuth["Service"]["authenticateHttpRequest"]>[0] =>
({
cookies: {
t3_session: sessionToken,
// Derived, not hardcoded: the name is port-scoped so concurrent servers
// on one hostname don't share a cookie.
[resolveSessionCookieName({ port: TEST_SERVER_PORT })]: sessionToken,
},
headers: {},
}) as unknown as Parameters<
+3 -1
View File
@@ -36,7 +36,9 @@ import { verifyRequestDpopProof } from "./dpop.ts";
import { layerConfig as SqlitePersistenceLayer } from "../persistence/Layers/Sqlite.ts";
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";
// Re-exported from PairingGrantStore, which keys the dev startup-token TTL off it.
export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT =
PairingGrantStore.INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT;
export interface IssuedPairingLink {
readonly id: string;
@@ -69,12 +69,15 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
expect(descriptor.policy).toBe("loopback-browser");
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
expect(descriptor.sessionCookieName).toBe("t3_session");
// Port-scoped in web mode too: cookies ignore ports, so two dev servers
// on one hostname would otherwise clobber each other's session.
expect(descriptor.sessionCookieName).toBe("t3_session_13773");
}).pipe(
Effect.provide(
makeEnvironmentAuthPolicyLayer({
mode: "web",
host: "127.0.0.1",
port: 13773,
}),
),
),
@@ -38,10 +38,7 @@ export const make = Effect.gen(function* () {
policy,
bootstrapMethods,
sessionMethods: ["browser-session-cookie", "bearer-access-token", "dpop-access-token"],
sessionCookieName: resolveSessionCookieName({
mode: config.mode,
port: config.port,
}),
sessionCookieName: resolveSessionCookieName({ port: config.port }),
};
return EnvironmentAuthPolicy.of({
+15 -1
View File
@@ -243,6 +243,16 @@ const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
// window can still recover by re-bootstrapping rather than locking
// the user out of the backend.
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
// A dev server's startup token is read off a log by whoever (or whatever) is
// driving the session, often minutes later — after a `node --watch` restart, a
// detour into another task, or a hand-off to the person actually doing the
// testing. Five minutes turns that into a restart-the-server loop for no
// security benefit: the token only unlocks a local dev backend, and its holder
// could read the log anyway. Same reasoning (and duration) as the desktop
// bootstrap grant above. Only applies when a dev URL is configured; user-issued
// pairing links and real servers keep the 5-minute default.
const DEV_STARTUP_TTL_HOURS = Duration.hours(24);
export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
const PAIRING_TOKEN_LENGTH = 12;
const PAIRING_TOKEN_REJECTION_LIMIT =
@@ -371,7 +381,11 @@ export const make = Effect.gen(function* () {
),
);
const credential = yield* generatePairingToken;
const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
const isDevStartupToken =
config.devUrl !== undefined && input?.subject === INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT;
const ttl =
input?.ttl ??
(isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
const issued: IssuedBootstrapCredential = {
+1 -4
View File
@@ -467,10 +467,7 @@ export const make = Effect.gen(function* () {
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
const cookieName = resolveSessionCookieName({
mode: serverConfig.mode,
port: serverConfig.port,
});
const cookieName = resolveSessionCookieName({ port: serverConfig.port });
const emitUpsert = (clientSession: AuthClientSession) =>
PubSub.publish(changesPubSub, {
+9 -8
View File
@@ -10,14 +10,15 @@ import * as Result from "effect/Result";
const SESSION_COOKIE_NAME = "t3_session";
export function resolveSessionCookieName(input: {
readonly mode: "web" | "desktop";
readonly port: number;
}): string {
if (input.mode !== "desktop") {
return SESSION_COOKIE_NAME;
}
/**
* Cookies are scoped by host but *not* by port, so every server reachable at a
* given hostname shares one cookie jar. Suffixing the port keeps concurrent
* instances from overwriting each other's session — otherwise two dev servers
* (different worktrees, or several ports behind one tailnet name) fight over
* `t3_session`, and whichever wrote last makes every other one reject the
* cookie with "Invalid session token signature" until it's cleared by hand.
*/
export function resolveSessionCookieName(input: { readonly port: number }): string {
return `${SESSION_COOKIE_NAME}_${input.port}`;
}
+73 -1
View File
@@ -8,6 +8,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
@@ -19,6 +20,7 @@ import {
formatSessionList,
} from "../cliAuthFormat.ts";
import * as ServerConfig from "../config.ts";
import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
import {
authLocationFlags,
type CliAuthLocationFlags,
@@ -26,6 +28,19 @@ import {
resolveCliAuthConfig,
} from "./config.ts";
class NoRunningServerError extends Schema.TaggedErrorClass<NoRunningServerError>()(
"NoRunningServerError",
{ statePath: Schema.String },
) {
override get message(): string {
return [
"No running T3 Code server was found for this data directory.",
`Looked for: ${this.statePath}`,
"Start one with `bun run dev`, or point at another directory with --base-dir.",
].join("\n");
}
}
const runWithEnvironmentAuth = <A, E>(
flags: CliAuthLocationFlags,
run: (environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,
@@ -113,6 +128,58 @@ const pairingCreateCommand = Command.make("create", {
),
);
/**
* `t3 auth pairing url` — print a ready-to-open pairing link for a dev server
* that is already running, without having to know its port, its state
* directory, or which of those two the `--base-dir`/`--dev-url` combination
* happens to select. The running server records all of it in
* `server-runtime.json`; this reads that back.
*
* The startup link printed in the server's own log is usually enough. This is
* for when it has been consumed, scrolled away, or the log isn't at hand.
*/
const pairingUrlCommand = Command.make("url", {
...authLocationFlags,
ttl: ttlFlag,
json: jsonFlag,
}).pipe(
Command.withDescription(
"Print a pairing URL for the dev server running against this data directory.",
),
Command.withHandler((flags) =>
Effect.gen(function* () {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveCliAuthConfig(flags, logLevel);
const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
if (Option.isNone(runtimeState)) {
return yield* new NoRunningServerError({ statePath: config.serverRuntimeStatePath });
}
// Prefer the web origin the user actually opens; a server with no dev URL
// serves the app itself, so its own origin is the right target.
const baseUrl = runtimeState.value.devUrl ?? runtimeState.value.origin;
return yield* runWithEnvironmentAuth(
flags,
(environmentAuth) =>
Effect.gen(function* () {
const issued = yield* environmentAuth.createPairingLink({
scopes: AuthStandardClientScopes,
subject: "one-time-token",
...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
label: "cli-issued pairing url",
});
yield* Console.log(
formatIssuedPairingCredential(issued, { json: flags.json, baseUrl }),
);
}),
{ quietLogs: flags.json },
);
}),
),
);
const pairingListCommand = Command.make("list", {
...authLocationFlags,
json: jsonFlag,
@@ -156,7 +223,12 @@ const pairingRevokeCommand = Command.make("revoke", {
const pairingCommand = Command.make("pairing").pipe(
Command.withDescription("Manage one-time client pairing tokens."),
Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
Command.withSubcommands([
pairingCreateCommand,
pairingUrlCommand,
pairingListCommand,
pairingRevokeCommand,
]),
);
const sessionIssueCommand = Command.make("issue", {
+27 -1
View File
@@ -41,6 +41,16 @@ import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./ht
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
const DESKTOP_RENDERER_ORIGINS = ["t3code://app", "t3code-dev://app"];
// Paths the web dev server proxies to us. Bouncing an unmatched one back to
// Vite would loop forever (Vite proxies it straight back), and it would answer
// an API call with index.html — so these 404 instead.
const DEV_PROXIED_PATH_PREFIXES = ["/api/", "/oauth/", "/.well-known/", "/ws"] as const;
function isDevProxiedPath(pathname: string): boolean {
return DEV_PROXIED_PATH_PREFIXES.some(
(prefix) => pathname === prefix.replace(/\/$/, "") || pathname.startsWith(prefix),
);
}
export const browserApiCorsLayer = Layer.unwrap(
Effect.gen(function* () {
@@ -48,9 +58,21 @@ export const browserApiCorsLayer = Layer.unwrap(
const devOrigin = config.devUrl?.origin;
// Dev uses credentialed requests from Vite or the Electron custom origin, so both must be
// explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.
//
// T3CODE_DEV_ALLOWED_ORIGINS covers dev servers reached from a second
// origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies
// through Vite and is same-origin (no preflight at all), so this is a
// safety net for the desktop renderer and any direct-to-backend caller.
const extraDevOrigins = (process.env.T3CODE_DEV_ALLOWED_ORIGINS ?? "")
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
return HttpRouter.cors({
...(devOrigin
? { allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS], credentials: true }
? {
allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...extraDevOrigins],
credentials: true,
}
: {}),
allowedMethods: browserApiCorsAllowedMethods,
allowedHeaders: browserApiCorsAllowedHeaders,
@@ -216,6 +238,10 @@ export const staticAndDevRouteLayer = HttpRouter.add(
}
const config = yield* ServerConfig.ServerConfig;
if (config.devUrl && isDevProxiedPath(url.value.pathname)) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
if (config.devUrl && isLoopbackHostname(url.value.hostname)) {
return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {
status: 302,
+8 -1
View File
@@ -14,6 +14,12 @@ export const PersistedServerRuntimeState = Schema.Struct({
host: Schema.optional(Schema.String),
port: Schema.Int,
origin: Schema.String,
/**
* The web origin users actually open in dev — the Vite server, or the shared
* tailnet URL when the dev runner published one. Recorded so tooling can mint
* a pairing URL for a running server without being told where it lives.
*/
devUrl: Schema.optional(Schema.String),
startedAt: Schema.String,
});
export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
@@ -45,7 +51,7 @@ const runtimeOriginForConfig = (
};
export const makePersistedServerRuntimeState = (input: {
readonly config: Pick<ServerConfig.ServerConfig["Service"], "host">;
readonly config: Pick<ServerConfig.ServerConfig["Service"], "host" | "devUrl">;
readonly port: number;
}): Effect.Effect<PersistedServerRuntimeState> =>
Effect.map(DateTime.now, (now) => ({
@@ -54,6 +60,7 @@ export const makePersistedServerRuntimeState = (input: {
...(input.config.host ? { host: input.config.host } : {}),
port: input.port,
origin: runtimeOriginForConfig(input.config, input.port),
...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),
startedAt: DateTime.formatIso(now),
}));
+50 -11
View File
@@ -65,7 +65,20 @@ const unitTestProject = {
},
} satisfies TestProjectInlineConfiguration;
function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
function resolveDevProxyTarget(
backendPort: string | undefined,
wsUrl: string | undefined,
): string | undefined {
// Browser dev is single-origin: the backend port is proxied through this
// server so the app works from any origin (localhost, tailnet, LAN, phone).
// T3CODE_PORT is set by scripts/dev-runner.ts for every non-desktop mode.
const port = Number(backendPort?.trim());
if (Number.isInteger(port) && port > 0) {
return `http://localhost:${port}/`;
}
// dev:desktop still points the renderer straight at the backend, so fall
// back to deriving the target from the explicit websocket URL.
if (!wsUrl) {
return undefined;
}
@@ -86,7 +99,17 @@ function resolveDevProxyTarget(wsUrl: string | undefined): string | undefined {
}
}
const devProxyTarget = resolveDevProxyTarget(configuredWsUrl);
const devProxyTarget = resolveDevProxyTarget(process.env.T3CODE_PORT, configuredWsUrl);
// Vite rejects requests whose Host header isn't localhost, which blocks sharing
// a dev server over Tailscale/LAN. Tailnet names are safe to allow wholesale:
// the DNS is controlled by tailscale, so they can't be rebound by an attacker.
// Anything else (ngrok, a LAN IP alias) goes through the env var.
const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "")
.split(",")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
const allowedHosts = [".ts.net", ...configuredAllowedHosts];
export default defineConfig(() => {
return {
@@ -145,6 +168,7 @@ export default defineConfig(() => {
host,
port,
strictPort: true,
allowedHosts,
...(devProxyTarget
? {
proxy: {
@@ -156,21 +180,36 @@ export default defineConfig(() => {
target: devProxyTarget,
changeOrigin: true,
},
"/attachments": {
"/oauth": {
target: devProxyTarget,
changeOrigin: true,
},
// The app's own socket. Vite's HMR socket is matched separately
// and exactly (path "/" plus a vite-hmr subprotocol), so the two
// upgrade handlers don't collide.
"/ws": {
target: devProxyTarget,
changeOrigin: true,
ws: true,
},
},
}
: {}),
// Electron's BrowserWindow needs the HMR socket pinned to an explicit
// host to connect reliably; dev:desktop is the only mode that sets HOST.
// Everywhere else, leaving this unset lets the client derive it from the
// page origin, which is what makes HMR work over Tailscale/LAN instead of
// failing an attempt against the wrong machine's localhost first.
// (Vite 8 logs connection state via console.debug — enable "Verbose".)
...(process.env.HOST?.trim()
? {
hmr: {
protocol: "ws",
host,
clientPort: port,
},
}
: {}),
hmr: {
// Explicit config so Vite's HMR WebSocket connects reliably
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
// connection logs — enable "Verbose" in DevTools to see them.
protocol: "ws",
host,
clientPort: port,
},
},
build: {
outDir: "dist",
+24 -5
View File
@@ -1,6 +1,8 @@
# Scripts
- `vp run dev` — Starts contracts, server, and web in watch mode.
- `vp run dev --share` (or `vp run dev:share`) — Same, plus publishes the web port on this machine's tailnet over HTTPS via `tailscale serve`. Prints the shareable URL, and the pairing URL is built against it so it can be opened from a phone or another laptop as-is. The mapping is removed on exit; if the tailnet is unavailable, the dev server still starts locally and logs a warning.
- `vp run dev:pair` — Prints a fresh pairing URL for the dev server already running against this data directory, resolving its port and web origin from `server-runtime.json`. Add `--base-dir <path>` only when the server was started with `--home-dir`.
- `vp run dev:server` — Starts just the WebSocket server. The server process runs on Bun (`@effect/platform-bun` + `BunPtyAdapter`), but task running uses `vp run`.
- `vp run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
@@ -38,10 +40,27 @@
## Running multiple dev instances
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
Ports resolve in this order, first match winning:
- Default ports: server `13773`, web `5733`
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
- Example: `T3CODE_DEV_INSTANCE=branch-a vp run dev:desktop`
1. `T3CODE_PORT_OFFSET=<n>` — exact numeric offset, full control.
2. `T3CODE_DEV_INSTANCE=<value>` — numeric offset, or a hashed one for non-numeric values. Example: `T3CODE_DEV_INSTANCE=branch-a vp run dev:desktop`
3. **Git worktree** — the offset is hashed from the worktree path, so every worktree gets its own stable pair that survives restarts and doesn't collide with its siblings.
4. Otherwise the defaults: server `13773`, web `5733`.
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
Whatever the source, both ports are then checked on loopback and shifted together if either is taken. The resolved values are printed on the `[dev-runner] …` line; `--dry-run` prints them without starting anything. Read them from there rather than assuming the defaults.
## Browser dev is single-origin
`dev` and `dev:web` deliberately leave `VITE_HTTP_URL` and `VITE_WS_URL` unset so
the client resolves its backend from `window.location.origin`, with Vite proxying
`/api`, `/ws`, `/oauth`, and `/.well-known` to the server. That is what lets a dev
server work unchanged from a tailnet name, a LAN IP, or a phone.
Setting those variables for web dev compiles absolute `localhost` URLs into the
bundle, and any browser that isn't on this machine will then try to reach its own
localhost. `dev:desktop` still sets them, because the Electron renderer talks to
the backend directly.
Non-`.ts.net` hostnames need `T3CODE_DEV_ALLOWED_HOSTS` (comma-separated) to pass
Vite's host check; `T3CODE_DEV_ALLOWED_ORIGINS` does the same for the server's
CORS allowlist.
+2
View File
@@ -5,8 +5,10 @@
"scripts": {
"prepare": "effect-tsgo patch && vp config --no-agent",
"dev": "node scripts/dev-runner.ts dev",
"dev:share": "node scripts/dev-runner.ts dev --share",
"dev:server": "node scripts/dev-runner.ts dev:server",
"dev:web": "node scripts/dev-runner.ts dev:web",
"dev:pair": "node apps/server/src/bin.ts auth pairing url",
"dev:marketing": "vp run --filter @t3tools/marketing dev",
"dev:desktop": "node scripts/dev-runner.ts dev:desktop",
"start": "vp run --filter t3 start",
+53 -2
View File
@@ -58,6 +58,7 @@ const devServerInput = {
port: 13_773,
devUrl: undefined,
dryRun: false,
share: false,
runArgs: ["--inspect", "secret-token-value"],
} as const;
@@ -336,8 +337,58 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
});
assert.equal(env.T3CODE_PORT, "13773");
assert.equal(env.VITE_HTTP_URL, "http://localhost:13773");
assert.equal(env.VITE_WS_URL, "ws://localhost:13773");
assert.equal(env.PORT, "5733");
}),
);
// Browser dev is single-origin: Vite proxies the backend, and the client
// resolves it from window.location.origin. Baking a localhost URL here is
// what breaks sharing a dev server to another device.
for (const mode of ["dev", "dev:web"] as const) {
it.effect(`leaves the client backend URLs unset in ${mode} mode`, () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode,
baseEnv: {
VITE_HTTP_URL: "http://localhost:1234",
VITE_WS_URL: "ws://localhost:1234",
},
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
});
assert.equal(env.VITE_HTTP_URL, undefined);
assert.equal(env.VITE_WS_URL, undefined);
assert.equal(env.T3CODE_PORT, "13773");
}),
);
}
it.effect("keeps explicit backend URLs for the desktop renderer", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev:desktop",
baseEnv: {},
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
});
assert.equal(env.VITE_HTTP_URL, "http://127.0.0.1:13773");
assert.equal(env.VITE_WS_URL, "ws://127.0.0.1:13773");
}),
);
});
+120 -13
View File
@@ -9,6 +9,7 @@ import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import * as Config from "effect/Config";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Hash from "effect/Hash";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
@@ -18,6 +19,7 @@ import * as Schema from "effect/Schema";
import { Argument, Command, Flag } from "effect/unstable/cli";
import { ChildProcess } from "effect/unstable/process";
import { DevShareError, shareDevServer, unshareDevServer } from "./lib/dev-share.ts";
import { loadRepoEnv } from "./lib/public-config.ts";
Object.assign(process.env, loadRepoEnv());
@@ -27,7 +29,12 @@ const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
const MAX_PORT = 65535;
const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::1", "::"] as const;
// Dev servers bind loopback, so loopback is the only interface whose
// availability decides whether we can use a port. Probing wildcards too made
// the runner walk away from a perfectly free port whenever something else held
// the same number on another interface — `tailscale serve` does exactly that,
// which silently moved the ports out from under a URL that had just been shared.
const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const;
export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
path.join(NodeOS.homedir(), ".t3"),
@@ -166,6 +173,7 @@ const OffsetConfig = Config.all({
export function resolveOffset(config: {
readonly portOffset: number | undefined;
readonly devInstance: string | undefined;
readonly worktreePath?: string | undefined;
}): Effect.Effect<
{ readonly offset: number; readonly source: string },
DevRunnerInvalidPortOffsetError
@@ -187,19 +195,46 @@ export function resolveOffset(config: {
}
const seed = config.devInstance?.trim();
if (!seed) {
return Effect.succeed({ offset: 0, source: "default ports" });
if (seed) {
if (/^\d+$/.test(seed)) {
return Effect.succeed({
offset: Number(seed),
source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
});
}
const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
}
if (/^\d+$/.test(seed)) {
return Effect.succeed({
offset: Number(seed),
source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
});
// Worktrees get ports derived from their path so each one is stable across
// restarts and distinct from its siblings. Without this every worktree starts
// at offset 0 and scan-collides onto whatever happens to be free that minute,
// so ports move under you between runs — which breaks any URL you already
// shared. The main checkout keeps the documented 5733/13773.
const worktreePath = config.worktreePath?.trim();
if (worktreePath) {
const offset = ((Hash.string(worktreePath) >>> 0) % MAX_HASH_OFFSET) + 1;
return Effect.succeed({ offset, source: `worktree ${worktreePath}` });
}
const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
return Effect.succeed({ offset: 0, source: "default ports" });
}
/**
* The path of the linked git worktree we're running in, or undefined for the
* main checkout. Git marks a linked worktree by making `.git` a file
* (`gitdir: …`) rather than a directory.
*/
export function resolveWorktreePath(
cwd: string,
): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const info = yield* fs.stat(path.join(cwd, ".git")).pipe(Effect.option);
return Option.isSome(info) && info.value.type === "File" ? cwd : undefined;
});
}
function resolveBaseDir(baseDir: string | undefined): Effect.Effect<string, never, Path.Path> {
@@ -265,8 +300,20 @@ export function createDevRunnerEnv({
if (!isDesktopMode) {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
if (mode === "dev" || mode === "dev:web") {
// Browser dev is single-origin: everything (including /ws) is proxied
// through Vite, so the client must resolve its backend from
// window.location.origin rather than a baked-in localhost URL. See
// resolveConfiguredPrimaryTarget in apps/web/src/environments/primary/target.ts
// — it only defers to the origin when both of these are absent. Baking
// localhost here is what breaks any non-localhost origin (tailnet, LAN,
// phone): the remote browser dials its own machine.
delete output.VITE_HTTP_URL;
delete output.VITE_WS_URL;
} else {
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
}
} else {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
@@ -480,6 +527,7 @@ interface DevRunnerCliInput {
readonly port: number | undefined;
readonly devUrl: URL | undefined;
readonly dryRun: boolean;
readonly share: boolean;
readonly runArgs: ReadonlyArray<string>;
}
@@ -495,7 +543,11 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
),
);
const { offset, source } = yield* resolveOffset({ portOffset, devInstance });
const { offset, source } = yield* resolveOffset({
portOffset,
devInstance,
worktreePath: yield* resolveWorktreePath(process.cwd()),
});
const { serverOffset, webOffset } = yield* resolveModePortOffsets({
mode: input.mode,
@@ -529,6 +581,55 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
`[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
);
const sharedWebPort = BASE_WEB_PORT + webOffset;
if (input.share) {
if (input.mode === "dev:server") {
yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
} else {
// acquireRelease, not share-then-addFinalizer: the mapping outlives this
// process (and reboots), so the cleanup has to be registered atomically
// with creating it. An interrupt landing in between would otherwise
// leave a mapping pointing at a port nothing is listening on.
//
// A tailnet that isn't up shouldn't stop the dev server from starting —
// warn, and carry on serving locally.
const shared = yield* Effect.acquireRelease(
shareDevServer({ webPort: sharedWebPort }),
() => unshareDevServer(sharedWebPort),
).pipe(
Effect.tapError((error: DevShareError) =>
Effect.logWarning(
`[dev-runner] could not share on the tailnet: ${error.message}${
error.hint ? ` — ${error.hint}` : ""
}`,
),
),
Effect.option,
Effect.map(Option.getOrUndefined),
);
if (shared) {
// The app is reached from the tailnet origin. Vite already allows
// *.ts.net hosts; the backend needs the origin for credentialed
// requests that bypass the proxy (desktop renderer, direct calls).
env.T3CODE_DEV_ALLOWED_ORIGINS = [
env.T3CODE_DEV_ALLOWED_ORIGINS,
new URL(shared.url).origin,
]
.filter((entry) => entry && entry.length > 0)
.join(",");
env.T3CODE_DEV_SHARE_URL = shared.url;
// The server builds its pairing URL from this, so the URL printed at
// startup is already the shareable one — no rewriting by hand. An
// explicit --dev-url still wins.
if (input.devUrl === undefined) {
env.VITE_DEV_SERVER_URL = shared.url;
}
yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
}
}
}
if (input.dryRun) {
return;
}
@@ -631,6 +732,12 @@ const devRunnerCli = Command.make("dev-runner", {
Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
Flag.withDefault(false),
),
share: Flag.boolean("share").pipe(
Flag.withDescription(
"Publish the web dev server on this machine's tailnet over HTTPS (via `tailscale serve`) and print the pairing URL for it. Removed again on exit.",
),
Flag.withDefault(false),
),
runArgs: Argument.string("run-arg").pipe(
Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
Argument.variadic(),
+173
View File
@@ -0,0 +1,173 @@
/**
* Shares a running dev server on the local tailnet via `tailscale serve`, so it
* can be opened from a phone, another laptop, or by whoever is reviewing the
* work.
*
* Because browser dev is single-origin (Vite proxies the backend — see
* `resolveDevProxyTarget` in apps/web/vite.config.ts), one proxy rule covering
* the web port is enough; the backend needs no mapping of its own.
*/
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
export class DevShareError extends Schema.TaggedErrorClass<DevShareError>()("DevShareError", {
reason: Schema.Literals([
"tailscale-missing",
"status-failed",
"status-unreadable",
"no-tailnet-name",
"serve-failed",
]),
detail: Schema.optional(Schema.String),
}) {
override get message(): string {
const base = {
"tailscale-missing": "tailscale is not installed or not on PATH",
"status-failed": "could not read tailscale status",
"status-unreadable": "could not parse tailscale status output",
"no-tailnet-name": "this machine has no tailnet DNS name",
"serve-failed": "tailscale serve failed",
}[this.reason];
return this.detail ? `${base}: ${this.detail}` : base;
}
/** What the user can actually do about it. */
get hint(): string | undefined {
switch (this.reason) {
case "tailscale-missing":
return "Install Tailscale, or drop --share and open the printed localhost URL.";
case "status-failed":
return "Is tailscaled running? Try `tailscale status`.";
case "no-tailnet-name":
return "Run `tailscale up` and make sure MagicDNS is enabled.";
default:
return undefined;
}
}
}
/** The one field we need out of `tailscale status --json`. */
const TailscaleStatus = Schema.fromJsonString(
Schema.Struct({
Self: Schema.Struct({
DNSName: Schema.String,
}),
}),
);
const decodeTailscaleStatus = Schema.decodeUnknownEffect(TailscaleStatus);
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(accumulated, chunk) => accumulated + chunk,
),
);
interface TailscaleResult {
readonly exitCode: number;
readonly stdout: string;
readonly stderr: string;
}
const runTailscale = Effect.fn("devShare.runTailscale")(function* (
args: ReadonlyArray<string>,
spawnFailureReason: DevShareError["reason"],
) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner
.spawn(ChildProcess.make("tailscale", args))
.pipe(Effect.mapError(() => new DevShareError({ reason: "tailscale-missing" })));
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
).pipe(
Effect.mapError(
(cause) => new DevShareError({ reason: spawnFailureReason, detail: String(cause) }),
),
);
return { exitCode, stdout, stderr } satisfies TailscaleResult;
});
/** The tailnet DNS name of this machine, e.g. `bb-1.example.ts.net`. */
export const resolveTailnetHost = Effect.fn("devShare.resolveTailnetHost")(function* () {
const status = yield* runTailscale(["status", "--json"], "status-failed");
if (status.exitCode !== 0) {
return yield* new DevShareError({
reason: "status-failed",
...(status.stderr.trim() ? { detail: status.stderr.trim() } : {}),
});
}
const decoded = yield* decodeTailscaleStatus(status.stdout).pipe(
Effect.mapError(() => new DevShareError({ reason: "status-unreadable" })),
);
// MagicDNS names come back fully qualified, with the trailing dot.
const host = decoded.Self.DNSName.replace(/\.$/, "");
if (!host) {
return yield* new DevShareError({ reason: "no-tailnet-name" });
}
return host;
});
export interface DevShareResult {
readonly url: string;
readonly host: string;
}
/**
* Removes a mapping created by {@link shareDevServer}. Best-effort.
*
* Runs uninterruptibly with its own scope: this is called from a finalizer on
* the way out of an interrupted program, and spawning the cleanup subprocess
* under the dying scope would cancel it before `tailscale` ever ran — leaving
* exactly the stale mapping it exists to remove.
*/
export const unshareDevServer = (webPort: number) =>
runTailscale(["serve", `--https=${String(webPort)}`, "off"], "serve-failed").pipe(
Effect.scoped,
Effect.ignore,
Effect.uninterruptible,
);
/**
* Publishes `webPort` on the tailnet at the same port number and returns the
* resulting HTTPS URL. Idempotent: re-running replaces any existing mapping.
*/
export const shareDevServer = Effect.fn("devShare.shareDevServer")(function* (input: {
readonly webPort: number;
}) {
const host = yield* resolveTailnetHost();
const port = String(input.webPort);
// Clear any mapping left behind by a run that was killed before its finalizer
// could fire. Serve config survives both the process and a reboot, and a
// stale entry may carry path routes we no longer want (older versions mapped
// /ws, /api and friends to a separate backend port).
yield* unshareDevServer(input.webPort);
const serve = yield* runTailscale(
["serve", "--bg", `--https=${port}`, `http://127.0.0.1:${port}`],
"serve-failed",
);
if (serve.exitCode !== 0) {
return yield* new DevShareError({
reason: "serve-failed",
detail: serve.stderr.trim() || `exit code ${String(serve.exitCode)} for port ${port}`,
});
}
return { url: `https://${host}:${port}/`, host } satisfies DevShareResult;
});