Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(dev): stop using portless run for apps, register via alias instead
Sidwebworksc3a07f869a46
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.tsindex c1733d8c5a..5f09dfae42 100644--- a/packages/dev/src/commands/up.ts+++ b/packages/dev/src/commands/up.ts@@ -34,7 +34,6 @@ import {} from "../services/migrations.js";import {branchToPrefix,- claimAppHosts,ensurePortlessInstalled,ensureProxyPrivileges,hostsFileInSync,@@ -391,12 +390,18 @@ async function runDatabaseMigrations(]);}-async function setupPortless(ctx: Ctx, selectedApps: AppId[]) {+async function setupPortless(ctx: Ctx, _selectedApps: AppId[]) {await tasks([+ {+ title: "Prune stale portless routes",+ task: async () => {+ await pruneStaleRoutes();+ return "orphans cleaned";+ }+ },{title: "Start portless proxy",task: async (msg) => {- pruneStaleRoutes(ctx.branchPrefix);startProxyDaemon(ctx.root);msg("waiting for proxy on :443");await waitForProxyReady();@@ -413,26 +418,26 @@ async function setupPortless(ctx: Ctx, selectedApps: AppId[]) {);return `${count} aliases registered`;}- },- {- title: "Reserve app hostnames",- task: async () => {- const killed = await claimAppHosts(ctx.branchPrefix, selectedApps);- return killed > 0- ? `killed ${killed} orphan portless process${killed === 1 ? "" : "es"}`- : "no orphans found";- }}]);}-// Skip sudo sync when root daemon already auto-syncs, or hosts unchanged.+// Verify /etc/hosts has all expected entries. Root proxy auto-syncs via+// fs.watch on routes.json, but there's a race between alias registration+// and the watcher firing. Poll briefly, then fall back to sudo sync.async function ensureHostsFile() {if (proxyRunsAsRoot()) {- log.info("/etc/hosts auto-synced by root proxy daemon");- return;- }- if (hostsFileInSync()) {+ // Give the root daemon a moment to pick up new routes.+ const deadline = Date.now() + 3_000;+ while (Date.now() < deadline) {+ if (hostsFileInSync()) {+ log.info("/etc/hosts verified in sync");+ return;+ }+ await new Promise((r) => setTimeout(r, 300));+ }+ log.warn("/etc/hosts not in sync after 3s — falling back to manual sync");+ } else if (hostsFileInSync()) {log.info("/etc/hosts already in sync — skipping sudo");return;}diff --git a/packages/dev/src/env.ts b/packages/dev/src/env.tsindex ba416222c5..4250b02257 100644--- a/packages/dev/src/env.ts+++ b/packages/dev/src/env.ts@@ -84,24 +84,18 @@ export function writeEnv(worktreeRoot: string, content: string) {writeFileSync(join(worktreeRoot, ".env.local"), content);}-// Stamp `apps/<id>/portless.json` so main-checkout gets `<app>.<prefix>.dev`-// too (portless auto-prefixes only in linked worktrees). Linked worktrees-// leave the file absent — stamping would double-prefix.+// Remove leftover portless.json files — apps are no longer spawned via+// `portless run` (which auto-prefixed linked worktrees in the wrong order).+// Instead, apps are spawned directly and registered via `portless alias`.export function syncAppPortlessConfigs(opts: {worktreeRoot: string;branchPrefix: string | null;linked: boolean;}) {- const { worktreeRoot, branchPrefix, linked } = opts;+ const { worktreeRoot } = opts;for (const { value: appId } of APP_CHOICES) {const path = join(worktreeRoot, "apps", appId, "portless.json");- const shouldStamp = !linked && branchPrefix !== null;- if (shouldStamp) {- writeFileSync(- path,- `${JSON.stringify({ name: `${appId}.${branchPrefix}` }, null, 2)}\n`- );- } else if (existsSync(path)) {+ if (existsSync(path)) {unlinkSync(path);}}diff --git a/packages/dev/src/services/apps.ts b/packages/dev/src/services/apps.tsindex 4e011e366c..ea2db5a797 100644--- a/packages/dev/src/services/apps.ts+++ b/packages/dev/src/services/apps.ts@@ -50,38 +50,28 @@ export function spawnApps(opts: {ports: PortMap;portless: boolean;}): Promise<void> {- const { root, apps, ports, portless } = opts;+ const { root, apps, ports } = opts;let shuttingDown = false;const children: ExecaChildProcess[] = apps.map((id) => {const color = APP_COLORS[id] ?? ((s: string) => s);- // detached: own process group so `process.kill(-pid, sig)` reaches the- // whole subtree (portless → react-router → vite → esbuild).- const child = portless- ? execa("portless", ["--script", "dev:app", "run", "--force"], {- cwd: join(root, "apps", id),- env: spawnAppEnv(root, id),- preferLocal: true,- reject: false,- stdin: "ignore",- detached: true- })- : (() => {- const portKey = APP_PORT_KEYS[id];- const port = portKey ? ports[portKey] : undefined;- return execa("pnpm", ["run", "dev:app"], {- cwd: join(root, "apps", id),- env: {- ...spawnAppEnv(root, id),- HOST: "127.0.0.1",- ...(port !== undefined ? { PORT: String(port) } : {})- },- reject: false,- stdin: "ignore",- detached: true- });- })();+ // Spawn apps directly with assigned ports. Hostnames are registered via+ // `portless alias` (in registerAliases) so we control the exact format+ // (`<app>.<prefix>.dev`) without portless auto-prefix mangling.+ const portKey = APP_PORT_KEYS[id];+ const port = portKey ? ports[portKey] : undefined;+ const child = execa("pnpm", ["run", "dev:app"], {+ cwd: join(root, "apps", id),+ env: {+ ...spawnAppEnv(root, id),+ HOST: "127.0.0.1",+ ...(port !== undefined ? { PORT: String(port) } : {})+ },+ reject: false,+ stdin: "ignore",+ detached: true+ });const prefix = color(pc.bold(`${id.padEnd(3)} | `));const pipe = (diff --git a/packages/dev/src/services/portless.ts b/packages/dev/src/services/portless.tsindex 4d5e0ddacd..08be3bbe44 100644--- a/packages/dev/src/services/portless.ts+++ b/packages/dev/src/services/portless.ts@@ -1,14 +1,10 @@-import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { existsSync, readFileSync } from "node:fs";import { homedir } from "node:os";import { setTimeout as sleep } from "node:timers/promises";import { confirm, isCancel, log, spinner } from "@clack/prompts";import { execa, execaSync } from "execa";import pc from "picocolors";-import {- ALIAS_SERVICES,- type AppId,- PORTLESS_MIN_VERSION-} from "../constants.js";+import { PORTLESS_MIN_VERSION } from "../constants.js";import type { PortMap } from "../worktree.js";// Strip npm_* / PNPM_* so portless doesn't refuse with "should not be run via@@ -331,8 +327,10 @@ export async function registerAliases(}export async function unregisterAliases(root: string, branchPrefix: string) {+ // Use a dummy PortMap — only the names matter for removal, not ports.+ const names = aliasMap(branchPrefix, {} as PortMap).map((a) => a.name);await Promise.all(- ALIAS_SERVICES.map((s) => withPrefix(s, branchPrefix)).map((name) =>+ names.map((name) =>execa("portless", ["alias", "--remove", name], {cwd: root,reject: false,@@ -345,97 +343,15 @@ export async function unregisterAliases(root: string, branchPrefix: string) {);}-// Pre-empt `<app>.<prefix>.{dev,localhost}` routes before spawning apps.-// Orphan portless processes from a prior `crbn up` keep entries alive,-// causing `RouteConflictError` on the next run. SIGTERM → 400ms poll →-// SIGKILL stragglers, then drop matching entries.-export async function claimAppHosts(- branchPrefix: string,- appIds: readonly AppId[]-): Promise<number> {- const path = `${homedir()}/.portless/routes.json`;- if (!existsSync(path)) return 0;-- let routes: { hostname: string; port: number; pid: number }[];- try {- routes = JSON.parse(readFileSync(path, "utf8"));- } catch {- return 0;- }-- const ourHosts = new Set(- appIds.flatMap((id) => {- const name = withPrefix(id, branchPrefix);- return [`${name}.dev`, `${name}.localhost`];- })- );-- const pidsToKill = new Set<number>();- for (const r of routes) {- if (ourHosts.has(r.hostname) && r.pid > 0 && isProcessAlive(r.pid)) {- pidsToKill.add(r.pid);- }- }-- for (const pid of pidsToKill) {- try {- process.kill(pid, "SIGTERM");- // biome-ignore lint/suspicious/noEmptyBlockStatements: ignored using `--suppress`- } catch {}- }-- const deadline = Date.now() + 400;- while (Date.now() < deadline) {- let allGone = true;- for (const pid of pidsToKill) {- if (isProcessAlive(pid)) {- allGone = false;- break;- }- }- if (allGone) break;- await sleep(50);- }- for (const pid of pidsToKill) {- if (isProcessAlive(pid)) {- try {- process.kill(pid, "SIGKILL");- // biome-ignore lint/suspicious/noEmptyBlockStatements: ignored using `--suppress`- } catch {}- }- }-- const filtered = routes.filter((r) => !ourHosts.has(r.hostname));- if (filtered.length !== routes.length) {- writeFileSync(path, JSON.stringify(filtered, null, 2));- }-- return pidsToKill.size;-}--// Drop stale alias entries (pid=0, our hostname pattern) from routes.json.-export function pruneStaleRoutes(branchPrefix: string) {- const path = `${homedir()}/.portless/routes.json`;- if (!existsSync(path)) return 0;- let routes: { hostname: string; pid: number }[];- try {- routes = JSON.parse(readFileSync(path, "utf8"));- } catch {- return 0;- }- const ourHosts = ALIAS_SERVICES.flatMap((s) => {- const name = withPrefix(s, branchPrefix);- return [`${name}.dev`, `${name}.localhost`];+// Let portless handle its own cleanup — kills orphaned dev servers from+// crashed sessions and removes their stale route entries.+export async function pruneStaleRoutes() {+ await execa("portless", ["prune"], {+ reject: false,+ stdio: "ignore",+ extendEnv: false,+ env: portlessEnv()});- const before = routes.length;- const filtered = routes.filter(- (r) => !(r.pid === 0 && ourHosts.includes(r.hostname))- );- if (filtered.length !== before) {- writeFileSync(path, JSON.stringify(filtered, null, 2));- return before - filtered.length;- }- return 0;}// Branch-independent OAuth callback host. Last `crbn up` wins. Keep in sync@@ -465,12 +381,17 @@ function withPrefix(name: string, prefix: string): string {return `${name}.${prefix}`;}-// Compose-service host:port aliases mirroring portless's app-host shape.+// All portless-routed services: compose services + apps. Every hostname+// follows `<name>.<prefix>.dev` via `portless alias` so we control the+// exact format without relying on portless auto-prefix (which reverses+// the order in linked worktrees).function aliasMap(branchPrefix: string,ports: PortMap): { name: string; port: number }[] {return [+ { name: withPrefix("erp", branchPrefix), port: ports.PORT_ERP },+ { name: withPrefix("mes", branchPrefix), port: ports.PORT_MES },{ name: withPrefix("api", branchPrefix), port: ports.PORT_API },{ name: withPrefix("studio", branchPrefix), port: ports.PORT_STUDIO },{ name: withPrefix("mail", branchPrefix), port: ports.PORT_INBUCKET },