diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts new file mode 100644 index 0000000000..22e3561b21 --- /dev/null +++ b/apps/server/src/index.ts @@ -0,0 +1,97 @@ +import fs from "node:fs"; +import net from "node:net"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { fixPath } from "./fixPath"; +import { createServer } from "./wsServer"; + +fixPath(); + +const DEFAULT_PORT = 3773; +const cwd = process.cwd(); + +async function findAvailablePort(preferred: number): Promise { + return new Promise((resolve, reject) => { + const server = net.createServer(); + server.listen(preferred, () => { + server.close(() => resolve(preferred)); + }); + server.on("error", () => { + // Preferred port busy — let the OS pick one + const fallback = net.createServer(); + fallback.listen(0, () => { + const addr = fallback.address(); + const port = + typeof addr === "object" && addr !== null ? addr.port : 0; + fallback.close(() => { + if (port > 0) resolve(port); + else reject(new Error("Could not find an available port.")); + }); + }); + fallback.on("error", reject); + }); + }); +} + +function resolveStaticDir(): string | undefined { + // In production, the renderer dist is next to the server dist: + // apps/server/dist/index.js → apps/renderer/dist/ + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + const rendererDist = path.resolve(__dirname, "../../renderer/dist"); + + try { + const stat = fs.statSync(path.join(rendererDist, "index.html")); + if (stat.isFile()) return rendererDist; + } catch { + // Not found — probably dev mode, Vite will serve + } + + return undefined; +} + +async function main() { + const port = await findAvailablePort(DEFAULT_PORT); + const devUrl = process.env.VITE_DEV_SERVER_URL; + const staticDir = devUrl ? undefined : resolveStaticDir(); + + if (!devUrl && !staticDir) { + console.warn( + "⚠ No built renderer found and no VITE_DEV_SERVER_URL set. The web UI will not be available.", + ); + console.warn( + " Run `bun run --cwd apps/renderer build` or set VITE_DEV_SERVER_URL for dev mode.", + ); + } + + const server = createServer({ port, cwd, staticDir, devUrl }); + await server.start(); + + const url = `http://localhost:${port}`; + console.log(`\n ✦ CodeThing running at ${url}`); + console.log(` ✦ Project: ${cwd}\n`); + + // Open browser (dynamic import because `open` is ESM-only) + try { + const open = await import("open"); + const target = devUrl ?? url; + await open.default(target); + } catch { + console.log(` Open ${devUrl ?? url} in your browser to get started.\n`); + } + + // Graceful shutdown + const shutdown = () => { + console.log("\n Shutting down...\n"); + server.stop(); + process.exit(0); + }; + + process.on("SIGINT", shutdown); + process.on("SIGTERM", shutdown); +} + +main().catch((err) => { + console.error("Failed to start CodeThing:", err); + process.exit(1); +}); diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts new file mode 100644 index 0000000000..2e3e649c99 --- /dev/null +++ b/apps/server/src/wsServer.ts @@ -0,0 +1,253 @@ +import { spawn } from "node:child_process"; +import fs from "node:fs"; +import http from "node:http"; +import path from "node:path"; + +import { + EDITORS, + WS_CHANNELS, + WS_METHODS, + type WsPush, + type WsRequest, + type WsResponse, + wsRequestSchema, +} from "@acme/contracts"; +import { WebSocketServer, type WebSocket } from "ws"; + +import { ProviderManager } from "./providerManager"; + +const MIME_TYPES: Record = { + ".html": "text/html; charset=utf-8", + ".js": "application/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".json": "application/json; charset=utf-8", + ".png": "image/png", + ".jpg": "image/jpeg", + ".svg": "image/svg+xml", + ".ico": "image/x-icon", + ".woff": "font/woff", + ".woff2": "font/woff2", + ".ttf": "font/ttf", + ".map": "application/json", +}; + +export interface ServerOptions { + port: number; + cwd: string; + staticDir?: string | undefined; + devUrl?: string | undefined; +} + +export function createServer(options: ServerOptions) { + const { port, cwd, staticDir, devUrl } = options; + const providerManager = new ProviderManager(); + const clients = new Set(); + + // Forward provider events to all connected WebSocket clients + providerManager.on("event", (event) => { + const push: WsPush = { + type: "push", + channel: WS_CHANNELS.providerEvent, + data: event, + }; + const message = JSON.stringify(push); + for (const client of clients) { + if (client.readyState === client.OPEN) { + client.send(message); + } + } + }); + + // HTTP server — serves static files or redirects to Vite dev server + const httpServer = http.createServer((req, res) => { + // In dev mode, redirect to Vite dev server + if (devUrl) { + res.writeHead(302, { Location: devUrl }); + res.end(); + return; + } + + // Serve static files from the renderer build + if (!staticDir) { + res.writeHead(503, { "Content-Type": "text/plain" }); + res.end("No static directory configured and no dev URL set."); + return; + } + + const url = new URL(req.url ?? "/", `http://localhost:${port}`); + let filePath = path.join(staticDir, url.pathname); + + // SPA fallback: if no file extension and not found, serve index.html + const ext = path.extname(filePath); + if (!ext) { + filePath = path.join(filePath, "index.html"); + } + + fs.stat(filePath, (err, stats) => { + if (err || !stats?.isFile()) { + // SPA fallback + const indexPath = path.join(staticDir, "index.html"); + fs.readFile(indexPath, (readErr, data) => { + if (readErr) { + res.writeHead(404, { "Content-Type": "text/plain" }); + res.end("Not Found"); + return; + } + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); + res.end(data); + }); + return; + } + + const fileExt = path.extname(filePath); + const contentType = MIME_TYPES[fileExt] ?? "application/octet-stream"; + + fs.readFile(filePath, (readErr, data) => { + if (readErr) { + res.writeHead(500, { "Content-Type": "text/plain" }); + res.end("Internal Server Error"); + return; + } + res.writeHead(200, { "Content-Type": contentType }); + res.end(data); + }); + }); + }); + + // WebSocket server — upgrades from the HTTP server + const wss = new WebSocketServer({ server: httpServer }); + + wss.on("connection", (ws) => { + clients.add(ws); + + // Send welcome message with project info + const projectName = + cwd.split("/").filter(Boolean).pop() ?? + cwd.split("\\").filter(Boolean).pop() ?? + "project"; + + const welcome: WsPush = { + type: "push", + channel: WS_CHANNELS.serverWelcome, + data: { cwd, projectName }, + }; + ws.send(JSON.stringify(welcome)); + + ws.on("message", (raw) => { + void handleMessage(ws, raw); + }); + + ws.on("close", () => { + clients.delete(ws); + }); + + ws.on("error", () => { + clients.delete(ws); + }); + }); + + async function handleMessage(ws: WebSocket, raw: unknown) { + let request: WsRequest; + try { + const parsed = JSON.parse(String(raw)); + request = wsRequestSchema.parse(parsed); + } catch { + const errorResponse: WsResponse = { + id: "unknown", + error: { message: "Invalid request format" }, + }; + ws.send(JSON.stringify(errorResponse)); + return; + } + + try { + const result = await routeRequest(request); + const response: WsResponse = { id: request.id, result }; + ws.send(JSON.stringify(response)); + } catch (err) { + const message = + err instanceof Error ? err.message : "Unknown server error"; + const response: WsResponse = { + id: request.id, + error: { message }, + }; + ws.send(JSON.stringify(response)); + } + } + + async function routeRequest(request: WsRequest): Promise { + switch (request.method) { + case WS_METHODS.providersStartSession: + return providerManager.startSession(request.params as never); + + case WS_METHODS.providersSendTurn: + return providerManager.sendTurn(request.params as never); + + case WS_METHODS.providersInterruptTurn: + return providerManager.interruptTurn(request.params as never); + + case WS_METHODS.providersRespondToRequest: + return providerManager.respondToRequest(request.params as never); + + case WS_METHODS.providersStopSession: { + providerManager.stopSession(request.params as never); + return undefined; + } + + case WS_METHODS.providersListSessions: + return providerManager.listSessions(); + + case WS_METHODS.shellOpenInEditor: { + const params = request.params as { + cwd: string; + editor: string; + }; + if (!params?.cwd) throw new Error("cwd is required"); + const editorDef = EDITORS.find((e) => e.id === params.editor); + if (!editorDef) throw new Error(`Unknown editor: ${params.editor}`); + if (!editorDef.command) { + // Can't open file manager programmatically from server, just succeed silently + return undefined; + } + const child = spawn(editorDef.command, [params.cwd], { + detached: true, + stdio: "ignore", + }); + child.on("error", () => { + /* ignore spawn failures for detached editors */ + }); + child.unref(); + return undefined; + } + + case WS_METHODS.serverGetConfig: + return { cwd }; + + default: + throw new Error(`Unknown method: ${request.method}`); + } + } + + function start() { + return new Promise((resolve) => { + httpServer.listen(port, () => { + resolve(); + }); + }); + } + + function stop() { + providerManager.stopAll(); + providerManager.dispose(); + + for (const client of clients) { + client.close(); + } + clients.clear(); + + wss.close(); + httpServer.close(); + } + + return { start, stop, httpServer }; +}