Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(dev): serve local stacks through a single frontend origin (#6705)
Eric Hayes5da774bab794
diff --git a/apps/web/scripts/local-dev-server.integration.test.ts b/apps/web/scripts/local-dev-server.integration.test.tsnew file mode 100644index 0000000000..008d438adf--- /dev/null+++ b/apps/web/scripts/local-dev-server.integration.test.ts@@ -0,0 +1,119 @@+import { createHash } from 'node:crypto';+import { createServer as createHttpServer } from 'node:http';+import type { AddressInfo, Socket } from 'node:net';+import { createServer } from 'vite';+import { expect, it } from 'vitest';+import { localDevServer } from './local-dev-server';++it('proxies real HTTP and WebSocket requests through Vite without rewriting paths', async () => {+ const sockets = new Set<Socket>();+ const backend = createHttpServer((req, res) => {+ res.setHeader('Content-Type', 'application/json');+ res.setHeader('Set-Cookie', 'proxy-test=ok; Path=/; SameSite=Lax');+ res.end(+ JSON.stringify({+ url: req.url,+ method: req.method,+ cookie: req.headers.cookie,+ })+ );+ });+ // Minimal server-to-client WebSocket frame: no additional test dependency.+ backend.on('connection', (socket) => {+ sockets.add(socket);+ socket.on('close', () => sockets.delete(socket));+ });+ backend.on('upgrade', (req, socket) => {+ const accept = createHash('sha1')+ .update(+ `${req.headers['sec-websocket-key']}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`+ )+ .digest('base64');+ socket.write(+ `HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`+ );+ const payload = Buffer.from(req.url ?? '');+ socket.write(Buffer.concat([Buffer.from([0x81, payload.length]), payload]));+ });+ await new Promise<void>((resolve) => backend.listen(0, '127.0.0.1', resolve));+ const target = `http://127.0.0.1:${(backend.address() as AddressInfo).port}`;+ const vite = await createServer({+ configFile: false,+ appType: 'custom',+ optimizeDeps: { noDiscovery: true, include: [] },+ server: {+ host: '127.0.0.1',+ port: 0,+ ...localDevServer({+ MACRO_LOCAL_BACKEND_PROXY: target,+ MACRO_LOCAL_BACKEND_ROUTES: '/auth,/connection-gateway,/i',+ }),+ },+ });+ try {+ vite.middlewares.use((_req, res) => res.end('frontend'));+ await vite.listen();+ const address = vite.httpServer?.address();+ if (!address || typeof address === 'string')+ throw new Error('Vite has no TCP listener');+ const origin = `http://127.0.0.1:${address.port}`;+ const response = await fetch(`${origin}/auth/health?check=1`, {+ headers: { cookie: 'session=test' },+ });+ expect(await response.json()).toEqual({+ url: '/auth/health?check=1',+ method: 'GET',+ cookie: 'session=test',+ });+ expect(response.headers.get('set-cookie')).toContain('proxy-test=ok');+ const telemetry = await fetch(`${origin}/i/otlp/v1/traces`, {+ method: 'POST',+ body: 'fixture',+ });+ expect(await telemetry.json()).toMatchObject({+ url: '/i/otlp/v1/traces',+ method: 'POST',+ });+ expect(await fetch(`${origin}/authentic`).then((res) => res.text())).toBe(+ 'frontend'+ );+ const client = await fetch(`${origin}/@vite/client`).then((res) =>+ res.text()+ );+ expect(client).toContain('import.meta.url');++ const path = '/connection-gateway?check=1';+ const socket = new WebSocket(origin.replace(/^http/, 'ws') + path);+ try {+ const message = await new Promise<string>((resolve, reject) => {+ const timer = setTimeout(+ () => reject(new Error('WebSocket proxy timeout')),+ 3000+ );+ socket.addEventListener(+ 'message',+ (event) => {+ clearTimeout(timer);+ resolve(String(event.data));+ },+ { once: true }+ );+ socket.addEventListener(+ 'error',+ () => {+ clearTimeout(timer);+ reject(new Error('WebSocket proxy failed'));+ },+ { once: true }+ );+ });+ expect(message).toBe(path);+ } finally {+ socket.close();+ }+ } finally {+ for (const socket of sockets) socket.destroy();+ await vite.close();+ await new Promise<void>((resolve) => backend.close(() => resolve()));+ }+});diff --git a/apps/web/scripts/local-dev-server.test.ts b/apps/web/scripts/local-dev-server.test.tsnew file mode 100644index 0000000000..5b946ef39d--- /dev/null+++ b/apps/web/scripts/local-dev-server.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest';+import { localDevServer } from './local-dev-server';++describe('localDevServer', () => {+ it('lets browser HMR infer the page origin and leaves hosted dev unproxied', () => {+ expect(localDevServer({})).toEqual({ hmr: undefined });+ });++ it('preserves the explicit Tauri device host', () => {+ expect(localDevServer({ TAURI_DEV_HOST: '192.168.1.20' }).hmr).toEqual({+ host: '192.168.1.20',+ protocol: 'ws',+ });+ });++ it('routes HTTP and bare/query-string WebSockets without swallowing frontend paths', () => {+ const target = 'http://localhost:20109';+ const config = localDevServer({+ MACRO_LOCAL_BACKEND_PROXY: target,+ MACRO_LOCAL_BACKEND_ROUTES:+ '/auth,/connection-gateway,/websocket,/sync,/ai-editing,/i,/static-file',+ });+ const rules = Object.keys(config.proxy ?? {}).map((key) => new RegExp(key));+ for (const path of [+ '/auth/health',+ '/connection-gateway?token=test',+ '/websocket',+ '/sync/document',+ '/ai-editing/edit',+ '/i/otlp/v1/traces',+ '/static-file/file.pdf',+ ]) {+ expect(+ rules.some((rule) => rule.test(path)),+ path+ ).toBe(true);+ }+ for (const path of [+ '/app/',+ '/@vite/client',+ '/src/main.tsx',+ '/?token=hmr',+ '/authentic',+ '/sync-other',+ ]) {+ expect(+ rules.some((rule) => rule.test(path)),+ path+ ).toBe(false);+ }+ for (const options of Object.values(config.proxy ?? {})) {+ expect(options).toEqual({ target, ws: true, xfwd: true });+ }+ expect(config.hmr).toBeUndefined();+ });++ it('rejects missing or malformed routing metadata instead of proxying everything', () => {+ for (const routes of [undefined, '', '/', '/auth,', '/auth|/app']) {+ expect(() =>+ localDevServer({+ MACRO_LOCAL_BACKEND_PROXY: 'http://localhost:20109',+ MACRO_LOCAL_BACKEND_ROUTES: routes,+ })+ ).toThrow(/MACRO_LOCAL_BACKEND_ROUTES/);+ }+ });+});diff --git a/apps/web/scripts/local-dev-server.ts b/apps/web/scripts/local-dev-server.tsnew file mode 100644index 0000000000..0f34ae9542--- /dev/null+++ b/apps/web/scripts/local-dev-server.ts@@ -0,0 +1,35 @@+import type { ServerOptions } from 'vite';++/** The stack's backend address is server-only; browsers use the Vite origin. */+export function localDevServer(+ env: Record<string, string | undefined>+): Pick<ServerOptions, 'hmr' | 'proxy'> {+ // Browser dev follows the page's host, port and ws/wss protocol, including+ // reverse proxies. Native development can still supply its device host.+ const hmr: ServerOptions['hmr'] = env.TAURI_DEV_HOST+ ? { host: env.TAURI_DEV_HOST, protocol: 'ws' }+ : undefined;+ const target = env.MACRO_LOCAL_BACKEND_PROXY;+ if (!target) return { hmr };++ const routes = env.MACRO_LOCAL_BACKEND_ROUTES?.split(',');+ if (+ !routes?.length ||+ routes.some((route) => !/^\/[a-z0-9-]+$/.test(route))+ ) {+ throw new Error(+ 'MACRO_LOCAL_BACKEND_ROUTES must list backend path prefixes'+ );+ }++ return {+ hmr,+ proxy: Object.fromEntries(+ routes.map((route) => [+ // Include bare WebSocket paths, but not /authentic or /sync-other.+ `^${route}(?:/|\\?|$)`,+ { target, ws: true, xfwd: true },+ ])+ ),+ };+}diff --git a/apps/web/src/observability/browser.ts b/apps/web/src/observability/browser.tsindex 6eb7e53be9..c82015808b 100644--- a/apps/web/src/observability/browser.ts+++ b/apps/web/src/observability/browser.ts@@ -44,9 +44,13 @@ async function browserTelemetryEnabled(hasExporter: boolean): Promise<boolean> {/** Initialize browser telemetry and its application-level lifecycle hooks. */export async function initializeBrowserObservability(): Promise<void> {- const tracesUrl =+ const configuredTracesUrl =import.meta.env.VITE_OTEL_EXPORTER_URL ??(import.meta.hot ? 'http://localhost:8098/i/otlp/v1/traces' : undefined);+ // Local stacks use a same-origin path; exporters expect an absolute URL.+ const tracesUrl = configuredTracesUrl+ ? new URL(configuredTracesUrl, window.location.origin).href+ : undefined;const telemetryConfig = {serviceName: 'web-app',environment:diff --git a/apps/web/vite.base.ts b/apps/web/vite.base.tsindex c778e79953..3d8c077e48 100644--- a/apps/web/vite.base.ts+++ b/apps/web/vite.base.ts@@ -11,6 +11,7 @@ import tsconfigpaths from 'vite-tsconfig-paths';// @ts-ignoreimport { version } from './package.json';import { keepImportMetaDev } from './scripts/keep-import-meta-dev';+import { localDevServer } from './scripts/local-dev-server';function readShortSha(): string {try {@@ -199,10 +200,7 @@ export const createAppViteConfig = (): UserConfigFn => {port: Number(process.env.PORT || 3000),host: '0.0.0.0',strictPort: true,- hmr: {- protocol: 'ws',- host: process.env.TAURI_DEV_HOST || 'localhost',- },+ ...localDevServer(process.env),cors: true,watch: {usePolling: true,diff --git a/docs/RUNNING_LOCALLY.md b/docs/RUNNING_LOCALLY.mdindex d635606036..c15638aa9a 100644--- a/docs/RUNNING_LOCALLY.md+++ b/docs/RUNNING_LOCALLY.md@@ -248,6 +248,28 @@ The generated files for an instance live here:infra/local/generated/<instance>```+### Access a remote dev server through one URL++`run_local` and `run_dev` serve API requests and backend WebSockets through Vite,+so the browser needs only the frontend port. For example, forward a remote+instance's frontend with `ssh -N -L 3000:127.0.0.1:20110 your-dev-host`, then open+`http://localhost:3000/app/`. A WebSocket-capable reverse proxy can instead expose+that frontend under a different hostname/port, including HTTPS. Vite HMR follows+the page's origin; no separate HMR or backend port forward is needed.++The launcher sets `VITE_LOCAL_BACKEND_ORIGIN=same-origin` and supplies Vite's+server-only `MACRO_LOCAL_BACKEND_PROXY` and `MACRO_LOCAL_BACKEND_ROUTES` from the+selected instance and backend inventory. The proxy preserves paths, query+strings, cookies, streaming responses and WebSocket upgrades. AI-editing and+enabled browser telemetry also use same-origin paths. Bare `bun run dev` without+these variables still uses hosted services; `TAURI_DEV_HOST` remains an explicit+native HMR override. Keep local dev stacks private: same-origin routing does not+add authentication or make passwordless local login safe to publish.++The stack launches Vite directly with Node (available in the Nix shell), because+Bun's Node HTTP compatibility currently hangs on Vite's proxied WebSocket+upgrades. Bun is still used for dependency installation and builds.+## Port Conflicts (macOS)The default instance binds a fixed set of host ports. macOS reserves some of themdiff --git a/tooling/xtask/crates/xtask_local/src/local/frontend.rs b/tooling/xtask/crates/xtask_local/src/local/frontend.rsindex 41e24ba44e..4ae401fe1a 100644--- a/tooling/xtask/crates/xtask_local/src/local/frontend.rs+++ b/tooling/xtask/crates/xtask_local/src/local/frontend.rs@@ -92,8 +92,8 @@ pub fn build_static(stage: &Stage, instance: &Instance, mode: Mode) -> Result<()}/// The env the dev server runs with. Both local and dev point the whole app at-/// the local proxy origin (single backend origin); the modes differ only in-/// what the *services* behind the proxy talk to (local infra vs dev resources).+/// the Vite origin, which forwards backend routes to the instance proxy. The+/// modes differ in what the services talk to (local infra vs dev resources).////// When a trace collector is up (`--traces`), point the OTel exporter at the/// analytics-proxy through the same proxy origin (`/i/otlp`), so tracing works@@ -115,19 +115,27 @@ fn dev_env(("VITE_LOCAL_SERVERS".to_string(), "ALL".to_string()),("VITE_LOCAL_BACKEND_ORIGIN".to_string(),+ "same-origin".to_string(),+ ),+ (+ "MACRO_LOCAL_BACKEND_PROXY".to_string(),proxy::url(instance),),+ (+ "MACRO_LOCAL_BACKEND_ROUTES".to_string(),+ proxy::frontend_path_prefixes().join(","),+ ),];if mode.spec().runs_local_infra {env.push(("VITE_AI_EDITING_WORKER_URL".to_string(),- format!("{}/ai-editing", proxy::url(instance)),+ "/ai-editing".to_string(),));}if traces_enabled {env.push(("VITE_OTEL_EXPORTER_URL".to_string(),- format!("{}/i/otlp/v1/traces", proxy::url(instance)),+ "/i/otlp/v1/traces".to_string(),));// Tag frontend telemetry with the same env the Datadog agent uses// (DD_ENV, default `local`), so the summary's traces/logs links —@@ -197,10 +205,10 @@ impl Frontend {}impl FrontendProcess {- /// Stop the dev server and all its children. `bun run dev` spawns Vite (and- /// friends), which we put in their own process group at spawn — so signal the+ /// Stop the dev server and all its children. We put Vite and its children+ /// in their own process group at spawn — so signal the/// GROUP (negative pid). SIGKILL is enough: the kernel releases the port the- /// moment the processes die. Then reap `bun` and join the drain threads (their+ /// moment the processes die. Then reap Vite and join the drain threads (their/// pipes close, so they exit).pub fn shutdown(&mut self) {if matches!(self.child.try_wait(), Ok(None)) {@@ -285,7 +293,10 @@ pub fn start(]);stage.run("Preparing frontend dependencies", &mut prepare)?;- let mut cmd = Command::new("bun");+ // Vite's node-http-proxy WebSocket upgrades hang under Bun (including+ // 1.3.13). Use Node for the dev server, while keeping Bun for dependencies+ // and builds: https://github.com/oven-sh/bun/issues/10441.+ let mut cmd = Command::new("node");cmd.current_dir(app_dir()).arg(repo_root().join("node_modules/vite/bin/vite.js")).args(["-c", "vite.config.ts"])@@ -311,11 +322,11 @@ pub fn start(}fn spawn(stage: &Stage, cmd: &mut Command, port: u16) -> Result<FrontendProcess> {- let mut child = cmd.spawn().context("launching `bun run dev`")?;+ let mut child = cmd.spawn().context("launching the Vite dev server")?;// Drain stdout+stderr into a buffer on their own threads (a full pipe would- // otherwise block bun); the output stays hidden unless the server exits.- // stdin is intentionally NOT taken — its write end stays open so bun never+ // otherwise block Vite); the output stays hidden unless the server exits.+ // stdin is intentionally NOT taken — its write end stays open so Vite never// sees stdin EOF.let captured = Arc::new(Mutex::new(Vec::new()));let mut drains = Vec::new();@@ -328,7 +339,7 @@ fn spawn(stage: &Stage, cmd: &mut Command, port: u16) -> Result<FrontendProcess>drains.push(std::thread::spawn(move || drain_into(&mut err, &buf)));}- // Wait until OUR child is serving: poll the port, but fail fast (with bun's+ // Wait until OUR child is serving: poll the port, but fail fast (with Vite's// output) if the child exits first. A bare port poll would mistake a stale// server already on the port for "ready" while our child has died.let addr: std::net::SocketAddr = ([127, 0, 0, 1], port).into();@@ -358,7 +369,7 @@ fn spawn(stage: &Stage, cmd: &mut Command, port: u16) -> Result<FrontendProcess>if let Err(error) = startup {let pgid = child.id() as i32;// SAFETY: the child leads the process group created above. ESRCH is- // harmless when Bun already exited.+ // harmless when Vite already exited.unsafe {libc::kill(-pgid, libc::SIGKILL);}diff --git a/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs b/tooling/xtask/crates/xtask_local/src/local/frontend/test.rsindex fff260daa6..a3fcc72724 100644--- a/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs+++ b/tooling/xtask/crates/xtask_local/src/local/frontend/test.rs@@ -2,6 +2,37 @@ use super::*;use std::io::{Read, Write};use std::net::{TcpListener, TcpStream};+#[test]+fn stack_frontend_uses_same_origin_with_an_instance_specific_server_target() {+ for instance in [+ Instance::derive(None, None).unwrap(),+ Instance::derive(Some("remote-dev"), Some(20100)).unwrap(),+ Instance::derive(Some("other-dev"), Some(20300)).unwrap(),+ ] {+ for mode in [Mode::Local, Mode::Dev] {+ let env: std::collections::HashMap<_, _> =+ dev_env(&instance, mode, true, false).into_iter().collect();+ assert_eq!(env["VITE_LOCAL_BACKEND_ORIGIN"], "same-origin");+ assert_eq!(env["MACRO_LOCAL_BACKEND_PROXY"], proxy::url(&instance));+ assert_eq!(+ env["MACRO_LOCAL_BACKEND_ROUTES"],+ proxy::frontend_path_prefixes().join(",")+ );+ assert_eq!(env["VITE_OTEL_EXPORTER_URL"], "/i/otlp/v1/traces");+ if mode.spec().runs_local_infra {+ assert_eq!(env["VITE_AI_EDITING_WORKER_URL"], "/ai-editing");+ } else {+ assert!(!env.contains_key("VITE_AI_EDITING_WORKER_URL"));+ }+ }+ let env: std::collections::HashMap<_, _> = dev_env(&instance, Mode::Local, false, false)+ .into_iter()+ .collect();+ assert_eq!(env["VITE_ENABLE_BROWSER_OTEL"], "false");+ assert!(!env.contains_key("VITE_OTEL_EXPORTER_URL"));+ }+}+fn test_frontend(stage: &Stage) -> Frontend {let listener = TcpListener::bind("127.0.0.1:0").unwrap();let port = listener.local_addr().unwrap().port();diff --git a/tooling/xtask/crates/xtask_local/src/local/proxy.rs b/tooling/xtask/crates/xtask_local/src/local/proxy.rsindex 1bf8bd6f6e..23e151a2a5 100644--- a/tooling/xtask/crates/xtask_local/src/local/proxy.rs+++ b/tooling/xtask/crates/xtask_local/src/local/proxy.rs@@ -19,6 +19,24 @@ pub fn url(instance: &Instance) -> String {format!("http://localhost:{}", instance.port(Port::Proxy))}+/// Vite forwards only backend routes, leaving assets, SPA navigation and HMR+/// with the frontend. Keep inventoried service paths sourced from the same+/// inventory as Caddy; the remaining paths are this module's special routes.+pub fn frontend_path_prefixes() -> Vec<&'static str> {+ inventory::RUST_SERVICES+ .iter()+ .filter_map(|svc| svc.path_prefix)+ .chain([+ "/websocket",+ "/sync",+ "/i",+ "/lexical",+ "/ai-editing",+ "/static-file",+ ])+ .collect()+}+/// Write the instance Caddyfile and return its path. Both local and dev keep a/// single frontend origin; Local fans every inventory prefix to a local/// container, while Dev fans Local-only prefixes (services that must not rundiff --git a/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs b/tooling/xtask/crates/xtask_local/src/local/proxy/test.rsindex 9e3421f8ad..cf24a8c508 100644--- a/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs+++ b/tooling/xtask/crates/xtask_local/src/local/proxy/test.rs@@ -1,6 +1,30 @@use super::*;use crate::local::{inventory, repo_root};+#[test]+fn vite_routes_cover_every_backend_prefix_and_no_frontend_routes() {+ let prefixes = frontend_path_prefixes();+ for svc in inventory::RUST_SERVICES {+ if let Some(prefix) = svc.path_prefix {+ assert!(prefixes.contains(&prefix));+ }+ }+ for prefix in [+ "/websocket",+ "/sync",+ "/i",+ "/lexical",+ "/ai-editing",+ "/static-file",+ ] {+ assert!(prefixes.contains(&prefix));+ }+ assert!(!prefixes.contains(&"/app"));+ assert!(!prefixes.contains(&"/"));+ let unique: std::collections::HashSet<_> = prefixes.iter().collect();+ assert_eq!(unique.len(), prefixes.len());+}+/// Every inventoried service that declares a path prefix must get a route in the/// generated Caddyfile, targeting its canonical compose service name. This is/// the guarantee that replaces the old hand-maintained route list.