Support remote hosts for WS transport and Vite dev server

- resolve WebSocket URL with explicit/bridge/env/page fallback and token propagation
- add wsTransport tests for URL precedence and token handling
- add remote-access guide and README section for cross-device usage
- add `T3CODE_PUBLIC_HOST` wiring in dev runner plus Vite host/HMR overrides
This commit is contained in:
Julius Marminge committed 2026-02-20 08:52:38 -08:00
1 parent 05aa27a0d9
commit 2880ef8276
6 files changed
+325 -11

No files matched your search

+13
View File
@@ -63,6 +63,19 @@ bun run dist:desktop:dmg
npx t3
```
## Remote usage (phone/tablet/laptop)
To run the server on one device and control it from another (for example over Tailscale), use:
- `docs/remote-access.md`
This includes:
- architecture and security model
- production setup for remote control
- remote dev setup with hot reload
- troubleshooting for cross-device connectivity
## Scripts
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
+85
View File
@@ -0,0 +1,85 @@
import { describe, expect, it } from "vitest";
import { appendTokenFromPageUrl, resolveWsUrl } from "./wsTransport";
describe("resolveWsUrl", () => {
it("prefers explicit url when provided", () => {
const resolved = resolveWsUrl({
explicitUrl: "ws://explicit.example:3773/socket",
bridgeUrl: "ws://bridge.example:3773",
envUrl: "ws://env.example:3773",
pageUrl: "http://device.local:3773/?token=abc",
pageProtocol: "http:",
pageHostname: "device.local",
pagePort: "3773",
});
expect(resolved).toBe("ws://explicit.example:3773/socket");
});
it("prefers desktop bridge url over env url", () => {
const resolved = resolveWsUrl({
bridgeUrl: "ws://bridge.example:3773",
envUrl: "ws://env.example:3773",
pageUrl: "http://device.local:3773/",
pageProtocol: "http:",
pageHostname: "device.local",
pagePort: "3773",
});
expect(resolved).toBe("ws://bridge.example:3773");
});
it("falls back to env url when bridge url is missing", () => {
const resolved = resolveWsUrl({
envUrl: "ws://env.example:3773/path",
pageUrl: "http://device.local:3773/",
pageProtocol: "http:",
pageHostname: "device.local",
pagePort: "3773",
});
expect(resolved).toBe("ws://env.example:3773/path");
});
it("derives wss url from https page when no explicit, bridge, or env url exists", () => {
const resolved = resolveWsUrl({
pageUrl: "https://tailnet-host.ts.net/",
pageProtocol: "https:",
pageHostname: "tailnet-host.ts.net",
pagePort: "",
});
expect(resolved).toBe("wss://tailnet-host.ts.net");
});
it("adds token from page url when missing on websocket url", () => {
const resolved = resolveWsUrl({
envUrl: "ws://tailnet-host.ts.net:3773",
pageUrl: "http://tailnet-host.ts.net:3773/?token=super-secret",
pageProtocol: "http:",
pageHostname: "tailnet-host.ts.net",
pagePort: "3773",
});
expect(resolved).toBe("ws://tailnet-host.ts.net:3773/?token=super-secret");
});
it("does not overwrite existing websocket token", () => {
const resolved = resolveWsUrl({
envUrl: "ws://tailnet-host.ts.net:3773/?token=already-set",
pageUrl: "http://tailnet-host.ts.net:3773/?token=super-secret",
pageProtocol: "http:",
pageHostname: "tailnet-host.ts.net",
pagePort: "3773",
});
expect(resolved).toBe("ws://tailnet-host.ts.net:3773/?token=already-set");
});
});
describe("appendTokenFromPageUrl", () => {
it("returns original url for invalid page urls", () => {
expect(appendTokenFromPageUrl("ws://localhost:3773", "not-a-url")).toBe("ws://localhost:3773");
});
});
+59 -7
View File
@@ -11,6 +11,56 @@ interface PendingRequest {
const REQUEST_TIMEOUT_MS = 60_000;
const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
interface WsUrlResolutionInput {
explicitUrl?: string;
bridgeUrl?: string | null;
envUrl?: string;
pageUrl: string;
pageProtocol: string;
pageHostname: string;
pagePort: string;
}
function normalizeUrl(value: string | null | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function defaultWsUrlForPage(protocol: string, hostname: string, port: string): string {
const wsProtocol = protocol === "https:" ? "wss" : "ws";
const authority = port.length > 0 ? `${hostname}:${port}` : hostname;
return `${wsProtocol}://${authority}`;
}
export function appendTokenFromPageUrl(wsUrl: string, pageUrl: string): string {
try {
const page = new URL(pageUrl);
const token = page.searchParams.get("token")?.trim();
if (!token) return wsUrl;
const resolvedWsUrl = new URL(wsUrl, page.origin);
if (!resolvedWsUrl.searchParams.has("token")) {
resolvedWsUrl.searchParams.set("token", token);
}
return resolvedWsUrl.toString();
} catch {
return wsUrl;
}
}
export function resolveWsUrl(input: WsUrlResolutionInput): string {
const explicitUrl = normalizeUrl(input.explicitUrl);
if (explicitUrl) return explicitUrl;
const baseUrl =
normalizeUrl(input.bridgeUrl) ??
normalizeUrl(input.envUrl) ??
defaultWsUrlForPage(input.pageProtocol, input.pageHostname, input.pagePort);
return appendTokenFromPageUrl(baseUrl, input.pageUrl);
}
export class WsTransport {
private ws: WebSocket | null = null;
private nextId = 1;
@@ -26,13 +76,15 @@ export class WsTransport {
// In dev mode, VITE_WS_URL points to the server's WebSocket endpoint.
// In production, the page is served by the WS server on the same host:port.
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
this.url =
url ??
(bridgeUrl && bridgeUrl.length > 0
? bridgeUrl
: envUrl && envUrl.length > 0
? envUrl
: `ws://${window.location.hostname}:${window.location.port}`);
this.url = resolveWsUrl({
explicitUrl: url,
bridgeUrl,
envUrl,
pageUrl: window.location.href,
pageProtocol: window.location.protocol,
pageHostname: window.location.hostname,
pagePort: window.location.port,
});
this.connect();
}
+4 -1
View File
@@ -4,6 +4,8 @@ import { tanstackRouter } from "@tanstack/router-plugin/vite";
import { defineConfig } from "vite";
const port = Number(process.env.PORT ?? 5173);
const devServerHost = process.env.VITE_DEV_SERVER_HOST ?? "localhost";
const hmrHost = process.env.VITE_HMR_HOST ?? "localhost";
export default defineConfig({
plugins: [
@@ -29,6 +31,7 @@ export default defineConfig({
tsconfigPaths: true,
},
server: {
host: devServerHost,
port,
strictPort: true,
hmr: {
@@ -36,7 +39,7 @@ export default defineConfig({
// inside Electron's BrowserWindow. Vite 8 uses console.debug for
// connection logs — enable "Verbose" in DevTools to see them.
protocol: "ws",
host: "localhost",
host: hmrHost,
},
},
build: {
+138
View File
@@ -0,0 +1,138 @@
# Remote Access Guide (Server on Computer, Client on Phone)
This guide explains how to run T3 Code on one machine and control it from another device (for example, your phone) over a private network like Tailscale.
## Goal
- Run the `apps/server` process on your computer.
- Open the web client from another device.
- Keep Codex running on the computer while controlling it remotely.
## Architecture
T3 Code is already split into backend and frontend roles:
- Backend (`apps/server`):
- Runs on your computer.
- Hosts HTTP pages + static assets.
- Hosts the WebSocket API.
- Spawns and manages Codex app-server sessions.
- Reads/writes local state and your local workspace files.
- Frontend (`apps/web`):
- Runs in the browser on any device.
- Connects to backend over WebSocket.
- Renders thread state and sends commands.
Data path:
1. Phone browser opens `http://<computer-tailnet-host>:<port>`.
2. Browser loads the T3 web app from that server.
3. Web app opens a WebSocket to the same server.
4. Server executes provider/terminal/git/file actions on the computer.
5. Server streams updates back to the phone.
Important: your phone never runs Codex itself. The agent process stays on the computer.
## Security Model
- Recommended network boundary: Tailscale tailnet ACLs.
- Optional app-layer auth: set `T3CODE_AUTH_TOKEN` on server start.
- When `T3CODE_AUTH_TOKEN` is enabled, open the UI with `?token=<token>` in the URL so the browser can authenticate WebSocket requests.
Example:
`http://my-macbook.tailnet-name.ts.net:3773/?token=<your-token>`
## Recommended Setup (Production Build)
Use this for reliable "control from phone while away from home".
### 1. Prepare computer
- Ensure Codex CLI is installed and authenticated on the computer.
- Ensure Tailscale is connected on the computer.
- Build the app:
```bash
bun run build
```
### 2. Start server
- Choose a port (default is `3773`).
- Create an auth token (recommended).
```bash
export T3CODE_PORT=3773
export T3CODE_NO_BROWSER=1
export T3CODE_AUTH_TOKEN="$(openssl rand -hex 24)"
bun run start
```
Notes:
- `T3CODE_NO_BROWSER=1` avoids auto-opening a local browser tab.
- Without `T3CODE_AUTH_TOKEN`, anyone with network reachability to your server can open a session.
### 3. Find Tailscale address of computer
```bash
tailscale ip -4
```
Or use MagicDNS hostname (for example `my-macbook.tailnet-name.ts.net`).
### 4. Open from phone
- Ensure your phone is connected to the same Tailscale tailnet.
- In phone browser, open:
```text
http://<tailscale-host-or-ip>:3773/?token=<T3CODE_AUTH_TOKEN>
```
You should now control the agent running on your computer.
## Remote Dev Setup (Hot Reload)
This repo now supports remote dev host wiring directly.
### 1. Pick the public host
Use the computer's Tailscale hostname or IP as `T3CODE_PUBLIC_HOST`.
### 2. Run dev mode
```bash
T3CODE_PUBLIC_HOST=my-macbook.tailnet-name.ts.net bun run dev
```
What this config does:
- Vite dev server is reachable off-machine (`0.0.0.0` bind).
- Server redirects to the public dev URL instead of localhost.
- WebSocket target uses the same public host instead of localhost.
- HMR uses the public host for browser reconnects.
If you also use auth token in dev:
1. set `T3CODE_AUTH_TOKEN=...` before running `bun run dev`
2. open `http://<host>:<web-port>/?token=<token>`
## Operational Tips
- Keep the server process running in `tmux`, `screen`, or a service manager.
- Use a long, random auth token.
- Restrict tailnet access using Tailscale ACLs to only your user/devices.
- Prefer production build for lower moving parts when remote.
## Troubleshooting
- Page loads but no data:
- Most likely missing/incorrect `?token=` when `T3CODE_AUTH_TOKEN` is set.
- Phone cannot reach host:
- Verify both devices are connected to Tailscale and can ping each other.
- Dev mode opens localhost URL:
- Ensure `T3CODE_PUBLIC_HOST` is set before `bun run dev`.
- Live reload not working in remote dev:
- Ensure `T3CODE_PUBLIC_HOST` resolves on the phone and no conflicting port overrides are set.
+26 -3
View File
@@ -58,6 +58,19 @@ function resolveOffset() {
return { offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` };
}
function resolvePublicHost() {
const rawHost = process.env.T3CODE_PUBLIC_HOST?.trim();
if (!rawHost) return undefined;
if (rawHost.includes("://") || rawHost.includes("/")) {
throw new Error(
`Invalid T3CODE_PUBLIC_HOST: ${rawHost}. Use only a host or IP (no protocol/path).`,
);
}
return rawHost;
}
function main() {
const mode = process.argv[2];
const isDryRun = process.argv.includes("--dry-run");
@@ -69,6 +82,9 @@ function main() {
const { offset, source } = resolveOffset();
const serverPort = BASE_SERVER_PORT + offset;
const webPort = BASE_WEB_PORT + offset;
const publicHost = resolvePublicHost();
const wsHost = publicHost ?? "localhost";
const webHost = publicHost ?? "localhost";
if (serverPort > 65535 || webPort > 65535) {
throw new Error(
@@ -81,15 +97,22 @@ function main() {
T3CODE_PORT: String(serverPort),
PORT: String(webPort),
ELECTRON_RENDERER_PORT: String(webPort),
VITE_WS_URL: `ws://localhost:${serverPort}`,
VITE_DEV_SERVER_URL: `http://localhost:${webPort}`,
VITE_WS_URL: `ws://${wsHost}:${serverPort}`,
VITE_DEV_SERVER_URL: `http://${webHost}:${webPort}`,
};
if (publicHost) {
env.VITE_DEV_SERVER_HOST = "0.0.0.0";
env.VITE_HMR_HOST = publicHost;
}
if (mode === "dev" && !env.T3CODE_LOG_WS_EVENTS) {
env.T3CODE_LOG_WS_EVENTS = "1";
}
console.info(
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort}`,
`[dev-runner] mode=${mode} source=${source} serverPort=${serverPort} webPort=${webPort}` +
`${publicHost ? ` publicHost=${publicHost}` : ""}`,
);
if (isDryRun) {