feat: replace SSE with WebSocket for real-time build progress

- Custom server wrapper monkey-patches http.createServer to add WS upgrade
- WebSocket endpoint: /ws/build/:buildId polls build worker every 1s
- Frontend connects via WebSocket with polling fallback
- Smoother progress updates, no Cloudflare SSE buffering issues
This commit is contained in:
Zebratic committed 2026-03-15 00:17:51 +00:00
1 parent 81fb6a9a7e
commit 80cb8dd802
5 files changed
+181 -31

No files matched your search

+7 -1
View File
@@ -53,6 +53,12 @@ COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
# Install ws for WebSocket support in the custom server
RUN cd /app && npm install ws
# Custom server with WebSocket support (replaces default server.js)
COPY server.custom.js /app/server.custom.js
# ── Build worker ──
COPY build-worker/server.js /worker/server.js
COPY build-worker/package.json /worker/package.json
@@ -68,7 +74,7 @@ logfile=/dev/null
logfile_maxbytes=0
[program:nextjs]
command=node /app/server.js
command=node /app/server.custom.js
directory=/app
autostart=true
autorestart=true
+34 -1
View File
@@ -24,7 +24,8 @@
"react-dom": "19.2.3",
"shadcn": "^4.0.6",
"tailwind-merge": "^3.5.0",
"tw-animate-css": "^1.4.0"
"tw-animate-css": "^1.4.0",
"ws": "^8.19.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
@@ -33,6 +34,7 @@
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/ws": "^8.18.1",
"eslint": "^9",
"eslint-config-next": "16.1.6",
"tailwindcss": "^4",
@@ -3726,6 +3728,16 @@
"@types/webidl-conversions": "*"
}
},
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.57.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.57.0.tgz",
@@ -13245,6 +13257,27 @@
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
},
"node_modules/ws": {
"version": "8.19.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz",
"integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/wsl-utils": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-0.3.1.tgz",
+3 -1
View File
@@ -25,7 +25,8 @@
"react-dom": "19.2.3",
"shadcn": "^4.0.6",
"tailwind-merge": "^3.5.0",
"tw-animate-css": "^1.4.0"
"tw-animate-css": "^1.4.0",
"ws": "^8.19.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
@@ -34,6 +35,7 @@
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@types/ws": "^8.18.1",
"eslint": "^9",
"eslint-config-next": "16.1.6",
"tailwindcss": "^4",
+77
View File
@@ -0,0 +1,77 @@
// Wrapper: starts Next.js standalone, then attaches WebSocket to the same HTTP server
const http = require("http");
const { parse } = require("url");
const { WebSocketServer } = require("ws");
const BUILD_WORKER_URL = process.env.BUILD_WORKER_URL || "http://localhost:3001";
// Monkey-patch http.createServer to intercept the server Next.js creates
const origCreateServer = http.createServer;
let patched = false;
http.createServer = function (...args) {
const server = origCreateServer.apply(this, args);
if (!patched) {
patched = true;
const wss = new WebSocketServer({ noServer: true });
server.on("upgrade", (req, socket, head) => {
const { pathname } = parse(req.url || "");
const match = pathname?.match(/^\/ws\/build\/([a-f0-9]{24})$/);
if (!match) {
// Not our path — destroy (Next.js doesn't use WS in production)
socket.destroy();
return;
}
const buildId = match[1];
wss.handleUpgrade(req, socket, head, (ws) => {
handleBuildWs(ws, buildId);
});
});
console.log("[ws] WebSocket upgrade handler attached to Next.js server");
}
return server;
};
function handleBuildWs(ws, buildId) {
let closed = false;
ws.on("close", () => { closed = true; });
ws.on("error", () => { closed = true; });
let lastJson = "";
const poll = async () => {
if (closed) return;
try {
const res = await fetch(`${BUILD_WORKER_URL}/build/${buildId}/status`);
if (!res.ok) {
if (!closed) setTimeout(poll, 2000);
return;
}
const data = await res.json();
const json = JSON.stringify(data);
if (json !== lastJson) {
lastJson = json;
try { ws.send(json); } catch { closed = true; return; }
}
if (data.status === "completed" || data.status === "failed") {
try { ws.close(1000, data.status); } catch { /* ignore */ }
return;
}
} catch {
// Worker unreachable — retry
}
if (!closed) setTimeout(poll, 1000);
};
poll();
}
// Now load the real Next.js standalone server, which will call http.createServer
require("./server.js");
+60 -28
View File
@@ -230,7 +230,7 @@ export default function ChatBuilderPage() {
statusMessage?: string;
progress?: number;
}>>({});
const esRefs = useRef<Record<string, EventSource>>({});
const wsRefs = useRef<Record<string, WebSocket>>({});
const pollRefs = useRef<Record<string, ReturnType<typeof setInterval>>>({});
const chatEndRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
@@ -307,12 +307,29 @@ export default function ChatBuilderPage() {
progress: latest.status === "completed" ? 100 : 0,
},
}));
// If still building/queued, start polling
// If still building/queued, connect WebSocket for live updates
if (latest.status === "queued" || latest.status === "building") {
startPolling(key, latest._id);
// Use WebSocket if available
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const ws = new WebSocket(`${protocol}//${window.location.host}/ws/build/${latest._id}`);
ws.onmessage = (e) => {
try {
const d = JSON.parse(e.data);
const status = d.status || "queued";
const msg = d.message || "";
const progress = d.progress ?? (status === "completed" ? 100 : undefined);
setBuildStates((prev) => ({ ...prev, [key]: { buildId: latest._id, status, statusMessage: msg, progress } }));
if (status === "completed" || status === "failed") {
toast(status === "completed" ? "APK build complete!" : (msg || "Build failed"), status === "completed" ? "success" : "error");
}
} catch { /* ignore */ }
};
ws.onerror = () => { startPolling(key, latest._id); };
ws.onclose = () => { delete wsRefs.current[key]; };
wsRefs.current[key] = ws;
}
} catch { /* ignore */ }
}, [projectId, startPolling]);
}, [projectId, startPolling, toast]);
useEffect(() => { loadProject(); loadLatestBuild(); }, [loadProject, loadLatestBuild]);
useEffect(() => { setTimeout(() => chatEndRef.current?.scrollIntoView({ behavior: "smooth" }), 100); }, [messages, streamingSteps]);
@@ -436,6 +453,40 @@ export default function ChatBuilderPage() {
}
}
const connectBuildWs = useCallback((key: string, buildId: string) => {
// Close existing connection for this key
if (wsRefs.current[key]) {
try { wsRefs.current[key].close(); } catch { /* ignore */ }
}
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const ws = new WebSocket(`${protocol}//${window.location.host}/ws/build/${buildId}`);
ws.onmessage = (e) => {
try {
const d = JSON.parse(e.data);
const status = d.status || "queued";
const msg = d.message || "";
const progress = d.progress ?? (status === "completed" ? 100 : undefined);
setBuildStates((prev) => ({ ...prev, [key]: { buildId, status, statusMessage: msg, progress } }));
if (status === "completed" || status === "failed") {
toast(status === "completed" ? "APK build complete!" : (msg || "Build failed"), status === "completed" ? "success" : "error");
}
} catch { /* ignore */ }
};
ws.onerror = () => {
// WebSocket failed — fall back to polling
startPolling(key, buildId);
};
ws.onclose = () => {
delete wsRefs.current[key];
};
wsRefs.current[key] = ws;
}, [toast, startPolling]);
const startBuild = useCallback(async (key: string) => {
try {
const res = await fetch("/api/build", {
@@ -447,28 +498,9 @@ export default function ChatBuilderPage() {
if (!res.ok) { toast(data.error || "Build failed", "error"); return; }
const buildId = data.buildId as string;
setBuildStates((prev) => ({ ...prev, [key]: { buildId, status: "queued", statusMessage: "Queued...", progress: 0 } }));
const es = new EventSource(`/api/build/${buildId}/stream`);
es.onmessage = (e) => {
try {
const d = JSON.parse(e.data);
const status = d.status || "queued";
const msg = d.message || "";
const progress = d.progress ?? (status === "completed" ? 100 : undefined);
setBuildStates((prev) => ({ ...prev, [key]: { buildId, status, statusMessage: msg, progress } }));
if (status === "completed" || status === "failed") {
es.close();
toast(status === "completed" ? "APK build complete!" : (msg || "Build failed"), status === "completed" ? "success" : "error");
}
} catch { /* ignore */ }
};
es.onerror = () => {
es.close();
// SSE disconnected (likely Cloudflare timeout) — fall back to polling
startPolling(key, buildId);
};
esRefs.current[key] = es;
connectBuildWs(key, buildId);
} catch { toast("Build failed", "error"); }
}, [projectId, toast, startPolling]);
}, [projectId, toast, connectBuildWs]);
function downloadApk(buildId: string) {
const a = document.createElement("a");
@@ -565,12 +597,12 @@ export default function ChatBuilderPage() {
const hasBuildReady = messages.some((m) => m.buildReady);
const fileCount = Object.keys(files).length;
// Cleanup EventSources on unmount
// Cleanup WebSockets on unmount
useEffect(() => {
const refs = esRefs.current;
const refs = wsRefs.current;
const polls = pollRefs.current;
return () => {
Object.values(refs).forEach(es => es.close());
Object.values(refs).forEach(ws => { try { ws.close(); } catch { /* ignore */ } });
Object.values(polls).forEach(id => clearInterval(id));
};
}, []);