Skip to content

Self-improving AI Employees for everyone

perf(scripts): TCP-probe ready detection in dev + start (saves ~2.21s)

trohitg077ad7824195
diff --git a/scripts/dev.js b/scripts/dev.js
index c09aad12..92835980 100644
--- a/scripts/dev.js
+++ b/scripts/dev.js
@@ -14,6 +14,7 @@ import {
ensureEnvFile,
killPort,
createLogger,
+ waitForTcpPort,
} from './utils.js';
const START_TIME = Date.now();
@@ -90,18 +91,6 @@ async function main() {
services.push('"pnpm run temporal:start"');
// Worker runs embedded in the backend (main.py TemporalWorkerManager)
- // Ready-detection patterns for each service
- const readyPatterns = [
- { name: 'Client', pattern: /ready in|VITE.*ready|Client:\s*http/i },
- { name: 'Backend', pattern: /Application startup complete|Uvicorn running/i },
- ];
- if (!skipWhatsApp) {
- readyPatterns.push({ name: 'WhatsApp', pattern: /listening on|WhatsApp.*ready|API.*started|:9400/i });
- }
- readyPatterns.push({ name: 'Temporal', pattern: /\[Temporal\] Worker started|temporal.*server.*started/i });
- const readySet = new Set();
- const totalExpected = readyPatterns.length;
-
// No --kill-others: uvicorn hot-reloads (exit code 1) would cascade-kill frontend
const proc = spawn('pnpm', ['exec', 'concurrently', '--raw', ...services], {
cwd: ROOT,
@@ -110,23 +99,37 @@ async function main() {
env: { ...process.env, FORCE_COLOR: '1' }
});
- proc.stdout.on('data', (data) => {
- process.stdout.write(data);
- const text = data.toString();
- for (const { name, pattern } of readyPatterns) {
- if (!readySet.has(name) && pattern.test(text)) {
- readySet.add(name);
- log(`${name} ready`);
- if (readySet.size === totalExpected) {
- log(`All services ready -- http://localhost:${config.clientPort}`);
- console.log('');
- }
- }
+ // Pass-through stdout/stderr so each service's logs reach the terminal.
+ proc.stdout.on('data', (data) => process.stdout.write(data));
+ proc.stderr.on('data', (data) => process.stderr.write(data));
+
+ // Detect ready state by probing TCP ports (the same primitive used by
+ // the wait-on package, Vercel CLI dev scripts, etc.). Replaces the
+ // previous stdout regex-matching, which trailed actual readiness by
+ // ~2s due to line-buffered stdout flush + Temporal worker startup
+ // gating the "Worker started" log line.
+ const readyTargets = [
+ { name: 'Client', port: config.clientPort },
+ { name: 'Backend', port: config.backendPort },
+ ];
+ if (!skipWhatsApp) {
+ readyTargets.push({ name: 'WhatsApp', port: config.ports.whatsapp });
+ }
+ readyTargets.push({ name: 'Temporal', port: config.ports.temporal });
+
+ Promise.all(
+ readyTargets.map(async ({ name, port }) => {
+ const ok = await waitForTcpPort(port);
+ log(ok ? `${name} ready (port ${port})` : `${name} did not become ready (port ${port})`);
+ return ok;
+ })
+ ).then((results) => {
+ if (results.every(Boolean)) {
+ log(`All services ready -- http://localhost:${config.clientPort}`);
+ console.log('');
}
});
- proc.stderr.on('data', (data) => process.stderr.write(data));
-
process.on('SIGINT', () => proc.kill('SIGINT'));
process.on('SIGTERM', () => proc.kill('SIGTERM'));
proc.on('close', (code) => {
diff --git a/scripts/start.js b/scripts/start.js
index 8634d29a..bb82efdb 100755
--- a/scripts/start.js
+++ b/scripts/start.js
@@ -15,6 +15,7 @@ import {
ensureEnvFile,
killPort,
createLogger,
+ waitForTcpPort,
} from './utils.js';
const START_TIME = Date.now();
@@ -108,30 +109,33 @@ async function main() {
if (!temporalRunning) services.push('"pnpm run temporal:start"');
// Worker runs embedded in the backend (main.py TemporalWorkerManager)
- // Ready-detection patterns for each service
- const readyPatterns = [
- { name: 'Client', pattern: /ready in|VITE.*ready|Client:\s*http/i },
- { name: 'Backend', pattern: /Application startup complete|Uvicorn running/i },
+ // Ready-detection via TCP port probes (same primitive used by the
+ // wait-on package and most production multi-service launchers).
+ // Replaces stdout regex-grep, which trailed actual readiness by ~2s
+ // due to line-buffered stdout flush. See scripts/utils.js:waitForTcpPort.
+ const readyTargets = [
+ { name: 'Client', port: config.clientPort },
+ { name: 'Backend', port: config.backendPort },
];
if (!skipWhatsApp) {
- readyPatterns.push({ name: 'WhatsApp', pattern: /listening on|WhatsApp.*ready|API.*started|:9400/i });
+ readyTargets.push({ name: 'WhatsApp', port: config.ports.whatsapp });
}
if (!temporalRunning) {
- readyPatterns.push({ name: 'Temporal', pattern: /\[Temporal\] Worker started|temporal.*server.*started/i });
+ readyTargets.push({ name: 'Temporal', port: config.ports.temporal });
}
- const readySet = new Set();
- const totalExpected = readyPatterns.length;
-
- function checkReady(text) {
- for (const { name, pattern } of readyPatterns) {
- if (!readySet.has(name) && pattern.test(text)) {
- readySet.add(name);
- log(`${name} ready`);
- if (readySet.size === totalExpected) {
- log(`All services ready`);
- }
+
+ function startReadyProbes() {
+ Promise.all(
+ readyTargets.map(async ({ name, port }) => {
+ const ok = await waitForTcpPort(port);
+ log(ok ? `${name} ready (port ${port})` : `${name} did not become ready (port ${port})`);
+ return ok;
+ })
+ ).then((results) => {
+ if (results.every(Boolean)) {
+ log('All services ready');
}
- }
+ });
}
if (isVerbose) {
@@ -143,12 +147,11 @@ async function main() {
env: { ...process.env, FORCE_COLOR: '1' },
});
- proc.stdout.on('data', (data) => {
- process.stdout.write(data);
- checkReady(data.toString());
- });
+ proc.stdout.on('data', (data) => process.stdout.write(data));
proc.stderr.on('data', (data) => process.stderr.write(data));
+ startReadyProbes();
+
process.on('SIGINT', () => proc.kill('SIGINT'));
process.on('SIGTERM', () => proc.kill('SIGTERM'));
proc.on('close', (code) => process.exit(code || 0));
@@ -176,12 +179,12 @@ async function main() {
env: { ...process.env, FORCE_COLOR: '1' },
});
- // Show only essential output: errors, ready messages, warnings
- const essential = /error|fatal|exception|failed|started|ready|listening|running|address already in use|application startup complete|\[Temporal\]/i;
+ // Show only essential output: errors and warnings (ready signals
+ // come from TCP probes via startReadyProbes(), not stdout grep).
+ const essential = /error|fatal|exception|failed|address already in use/i;
proc.stdout.on('data', (data) => {
const text = data.toString();
- checkReady(text);
for (const line of text.split('\n')) {
const trimmed = line.trim();
if (trimmed && essential.test(trimmed)) {
@@ -193,6 +196,8 @@ async function main() {
// Always show stderr
proc.stderr.on('data', (data) => process.stderr.write(data));
+ startReadyProbes();
+
process.on('SIGINT', () => proc.kill('SIGINT'));
process.on('SIGTERM', () => proc.kill('SIGTERM'));
proc.on('close', (code) => {
diff --git a/scripts/utils.js b/scripts/utils.js
index 474f64bc..346db814 100644
--- a/scripts/utils.js
+++ b/scripts/utils.js
@@ -7,6 +7,7 @@
* no shell pipes, works in all terminals including Git Bash on Windows).
*/
import { readFileSync, existsSync, copyFileSync } from 'fs';
+import { Socket } from 'net';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import { execSync } from 'child_process';
@@ -50,6 +51,49 @@ export function getPlatformName() {
*/
export const sleep = (ms) => new Promise(r => setTimeout(r, ms));
+/**
+ * TCP port readiness probe — same primitive used by the wait-on package,
+ * Vercel CLI dev scripts, and most production multi-service launchers.
+ * Resolves true the moment the port accepts a TCP connection, false on
+ * timeout / error. Zero new dependencies (Node built-in net.Socket).
+ */
+export function probeTcpPort(port, host = '127.0.0.1', timeoutMs = 500) {
+ return new Promise((resolveOuter) => {
+ const socket = new Socket();
+ let done = false;
+ const finish = (ok) => {
+ if (done) return;
+ done = true;
+ socket.destroy();
+ resolveOuter(ok);
+ };
+ socket.setTimeout(timeoutMs);
+ socket.once('connect', () => finish(true));
+ socket.once('timeout', () => finish(false));
+ socket.once('error', () => finish(false));
+ socket.connect(port, host);
+ });
+}
+
+/**
+ * Poll a TCP port until it accepts connections or maxWaitMs elapses.
+ * Use to detect when a child service (uvicorn, vite, temporal, etc.) is
+ * ready to accept traffic — significantly more reliable and faster than
+ * grepping stdout for ready-message patterns, which trail actual readiness
+ * by hundreds of ms due to line-buffered stdout flush.
+ */
+export async function waitForTcpPort(
+ port,
+ { intervalMs = 250, maxWaitMs = 60000, host = '127.0.0.1' } = {}
+) {
+ const start = Date.now();
+ while (Date.now() - start < maxWaitMs) {
+ if (await probeTcpPort(port, host)) return true;
+ await sleep(intervalMs);
+ }
+ return false;
+}
+
/**
* Normalize path for cross-platform comparison.
*/
@@ -68,7 +112,13 @@ export function loadEnvConfig() {
const env = {};
if (existsSync(envPath)) {
- for (const line of readFileSync(envPath, 'utf-8').split('\n')) {
+ // Normalize CRLF -> LF before splitting so the regex anchors work
+ // on Windows-edited .env files. Without this, `.` (which excludes
+ // line terminators including \r) made `(.*)$` fail to match every
+ // line that ended with \r, silently returning undefined for every
+ // env var and forcing the fallback values to apply.
+ const text = readFileSync(envPath, 'utf-8').replace(/\r\n?/g, '\n');
+ for (const line of text.split('\n')) {
const match = line.match(/^([^#=]+)=(.*)$/);
if (match) {
let value = match[2].trim();
@@ -85,10 +135,32 @@ export function loadEnvConfig() {
const backendPort = parseInt(env.PYTHON_BACKEND_PORT) || 3010;
const whatsappPort = parseInt(env.WHATSAPP_RPC_PORT) || 9400;
const nodejsPort = parseInt(env.NODEJS_EXECUTOR_PORT) || 3020;
+ // Temporal server gRPC port — parsed from TEMPORAL_SERVER_ADDRESS in
+ // .env / .env.template (e.g. "localhost:7233"). Strict: throws on
+ // missing/malformed value so misconfiguration surfaces at startup
+ // instead of silently degrading to a wrong port.
+ const temporalAddress = env.TEMPORAL_SERVER_ADDRESS;
+ if (!temporalAddress) {
+ throw new Error(
+ 'TEMPORAL_SERVER_ADDRESS is not set in .env. Required for service ready detection.',
+ );
+ }
+ const temporalPort = parseInt(temporalAddress.split(':').pop());
+ if (!Number.isFinite(temporalPort) || temporalPort <= 0) {
+ throw new Error(
+ `TEMPORAL_SERVER_ADDRESS='${temporalAddress}' has no valid port (expected "host:port").`,
+ );
+ }
return {
raw: env,
- ports: { client: clientPort, backend: backendPort, whatsapp: whatsappPort, nodejs: nodejsPort },
+ ports: {
+ client: clientPort,
+ backend: backendPort,
+ whatsapp: whatsappPort,
+ nodejs: nodejsPort,
+ temporal: temporalPort,
+ },
allPorts: [clientPort, backendPort, whatsappPort, nodejsPort],
clientPort,
backendPort,