Codex web app architecture #8
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 15 commits into
main fromcursor/codex-web-app-architecture-f06fopened View on GitHub- @@ -0,0 +16,21 @@16+ private nextId = 1;17+ private readonly pending = new Map<string, PendingRequest>();18+ private readonly listeners = new Map<string, Set<PushListener>>();19+ private reconnectAttempt = 0;20+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;21+ private disposed = false;22+ private readonly url: string;23+24+ constructor(url?: string) {25+ // In dev mode, VITE_WS_URL points to the server's WebSocket endpoint.26+ // In production, the page is served by the WS server on the same host:port.27+ const envUrl = import.meta.env.VITE_WS_URL as string | undefined;28+ this.url =29+ url ??30+ (envUrl && envUrl.length > 031+ ? envUrl32+ : `ws://${window.location.hostname}:${window.location.port}`);33+ this.connect();34+ }35+36+ async request<T = unknown>(method: string, params?: unknown): Promise<T> {@@ -0,0 +98,21 @@98+ });99+ return;100+ }101+102+ const fileExt = path.extname(filePath);103+ const contentType = MIME_TYPES[fileExt] ?? "application/octet-stream";104+105+ fs.readFile(filePath, (readErr, data) => {106+ if (readErr) {107+ res.writeHead(500, { "Content-Type": "text/plain" });108+ res.end("Internal Server Error");109+ return;110+ }111+ res.writeHead(200, { "Content-Type": contentType });112+ res.end(data);113+ });114+ });115+ });116+117+ // WebSocket server — upgrades from the HTTP server118+ const wss = new WebSocketServer({ server: httpServer });@@ -0,0 +58,21 @@58+ }59+ });60+61+ // HTTP server — serves static files or redirects to Vite dev server62+ const httpServer = http.createServer((req, res) => {63+ // In dev mode, redirect to Vite dev server64+ if (devUrl) {65+ res.writeHead(302, { Location: devUrl });66+ res.end();67+ return;68+ }69+70+ // Serve static files from the renderer build71+ if (!staticDir) {72+ res.writeHead(503, { "Content-Type": "text/plain" });73+ res.end("No static directory configured and no dev URL set.");74+ return;75+ }76+77+ const url = new URL(req.url ?? "/", `http://localhost:${port}`);78+ let filePath = path.join(staticDir, url.pathname);@@ -0,0 +1,18 @@1+import fs from "node:fs";2+import net from "node:net";3+import path from "node:path";4+import { fileURLToPath } from "node:url";5+6+import { fixPath } from "./fixPath";7+import { createServer } from "./wsServer";8+9+fixPath();10+11+const DEFAULT_PORT = 3773;12+const cwd = process.cwd();13+14+async function findAvailablePort(preferred: number): Promise<number> {15+ return new Promise((resolve, reject) => {16+ const server = net.createServer();17+ server.listen(preferred, () => {18+ server.close(() => resolve(preferred));
- @@ -0,0 +144,21 @@144+145+ clearTimeout(pending.timeout);146+ this.pending.delete(response.id);147+148+ if (response.error) {149+ pending.reject(new Error(response.error.message));150+ } else {151+ pending.resolve(response.result);152+ }153+ }154+ }155+156+ private send(message: WsRequest) {157+ if (this.ws?.readyState === WebSocket.OPEN) {158+ this.ws.send(JSON.stringify(message));159+ return;160+ }161+162+ // If not connected, wait for connection163+ const waitForOpen = () => {164+ const check = setInterval(() => {@@ -0,0 +83,21 @@83+ filePath = path.join(filePath, "index.html");84+ }85+86+ fs.stat(filePath, (err, stats) => {87+ if (err || !stats?.isFile()) {88+ // SPA fallback89+ const indexPath = path.join(staticDir, "index.html");90+ fs.readFile(indexPath, (readErr, data) => {91+ if (readErr) {92+ res.writeHead(404, { "Content-Type": "text/plain" });93+ res.end("Not Found");94+ return;95+ }96+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });97+ res.end(data);98+ });99+ return;100+ }101+102+ const fileExt = path.extname(filePath);103+ const contentType = MIME_TYPES[fileExt] ?? "application/octet-stream";
- @@ -0,0 +1,14 @@1+import fs from "node:fs";2+import net from "node:net";3+import path from "node:path";4+import { fileURLToPath } from "node:url";5+6+import { fixPath } from "./fixPath";7+import { createServer } from "./wsServer";8+9+fixPath();10+11+const DEFAULT_PORT = 3773;12+const cwd = process.cwd();13+14+async function findAvailablePort(preferred: number): Promise<number> {
- @@ -17,4 +17,4 @@1717 - name: Setup Bun1818 uses: oven-sh/setup-bun@v21919 with:20- bun-version: 1.1.3820+ bun-version: 1.3.9@@ -1 +1 @@1-# AGENTS.md1+# CLAUDE.md@@ -27,0 +72,21 @@72+ });73+ dispatch({74+ type: "ADD_THREAD",75+ thread: {76+ id: crypto.randomUUID(),77+ codexThreadId: null,78+ projectId,79+ title: "New thread",80+ model: DEFAULT_MODEL,81+ session: null,82+ messages: [],83+ events: [],84+ error: null,85+ createdAt: new Date().toISOString(),86+ },87+ });88+ });89+ }, [state.projects, state.threads, state.activeThreadId, dispatch]);90+91+ return null;92+}@@ -0,0 +13,21 @@13+14+export class WsTransport {15+ private ws: WebSocket | null = null;16+ private nextId = 1;17+ private readonly pending = new Map<string, PendingRequest>();18+ private readonly listeners = new Map<string, Set<PushListener>>();19+ private reconnectAttempt = 0;20+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;21+ private disposed = false;22+ private readonly url: string;23+24+ constructor(url?: string) {25+ // In dev mode, VITE_WS_URL points to the server's WebSocket endpoint.26+ // In production, the page is served by the WS server on the same host:port.27+ const envUrl = import.meta.env.VITE_WS_URL as string | undefined;28+ this.url =29+ url ??30+ (envUrl && envUrl.length > 031+ ? envUrl32+ : `ws://${window.location.hostname}:${window.location.port}`);33+ this.connect();@@ -0,0 +1,15 @@1+import { spawn } from "node:child_process";2+import fs from "node:fs";3+import http from "node:http";4+import path from "node:path";5+6+import {7+ EDITORS,8+ WS_CHANNELS,9+ WS_METHODS,10+ type WsPush,11+ type WsRequest,12+ type WsResponse,13+ wsRequestSchema,14+} from "@acme/contracts";15+import { WebSocketServer, type WebSocket } from "ws";@@ -0,0 +19,21 @@19+const MIME_TYPES: Record<string, string> = {20+ ".html": "text/html; charset=utf-8",21+ ".js": "application/javascript; charset=utf-8",22+ ".css": "text/css; charset=utf-8",23+ ".json": "application/json; charset=utf-8",24+ ".png": "image/png",25+ ".jpg": "image/jpeg",26+ ".svg": "image/svg+xml",27+ ".ico": "image/x-icon",28+ ".woff": "font/woff",29+ ".woff2": "font/woff2",30+ ".ttf": "font/ttf",31+ ".map": "application/json",32+};33+34+export interface ServerOptions {35+ port: number;36+ cwd: string;37+ staticDir?: string | undefined;38+ devUrl?: string | undefined;39+}@@ -7,0 +7,21 @@7+## Architecture8+9+CodeThing runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.10+11+```12+┌─────────────────────────────────┐13+│ Browser (React + Vite) │14+│ Connected via WebSocket │15+└──────────┬──────────────────────┘16+ │ ws://localhost:377317+┌──────────▼──────────────────────┐18+│ apps/server (Node.js) │19+│ WebSocket + HTTP static server │20+│ ProviderManager │21+│ CodexAppServerManager │22+└──────────┬──────────────────────┘23+ │ JSON-RPC over stdio24+┌──────────▼──────────────────────┐25+│ codex app-server │26+└─────────────────────────────────┘27+```
- @@ -0,0 +241,21 @@241+ });242+ child.on("error", () => {243+ /* ignore spawn failures for detached editors */244+ });245+ child.unref();246+ return undefined;247+ }248+249+ case WS_METHODS.serverGetConfig:250+ return { cwd };251+252+ default:253+ throw new Error(`Unknown method: ${request.method}`);254+ }255+ }256+257+ function start() {258+ return new Promise<void>((resolve) => {259+ httpServer.listen(port, () => {260+ resolve();261+ });@@ -0,0 +81,21 @@81+82+ const url = `http://localhost:${port}`;83+ logger.info("CodeThing running", { url, cwd });84+85+ // Open browser (dynamic import because `open` is ESM-only)86+ try {87+ const open = await import("open");88+ const target = devUrl ?? url;89+ await open.default(target);90+ } catch {91+ logger.info("browser auto-open unavailable", {92+ hint: `Open ${devUrl ?? url} in your browser.`,93+ });94+ }95+96+ // Graceful shutdown97+ const shutdown = () => {98+ logger.info("shutting down");99+ server.stop();100+ process.exit(0);101+ };
juliusmarminge closed this
Sign in to join this conversation.


Cursor Agent can help with this pull request. Just
@cursorin comments and I'll start working on changes in this branch. Learn more about Cursor Agents