New application architecture #9
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 250+ commits into
main fromcursor/new-application-architecture-f8d0opened View on GitHub- apps/t3/src/cli.ts lines 361 to 365Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +12,21 @@12+ return fallback;13+ }14+15+ const parsed = Number(value);16+ if (!Number.isInteger(parsed) || parsed <= 0) {17+ return fallback;18+ }19+20+ return parsed;21+}22+23+function openBrowser(url: string): void {24+ const command =25+ process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";26+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];27+28+ const child = spawn(command, args, {29+ detached: true,30+ stdio: "ignore",31+ });32+ child.unref();@@ -0,0 +26,21 @@26+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];27+28+ const child = spawn(command, args, {29+ detached: true,30+ stdio: "ignore",31+ });32+ child.unref();33+}34+35+function ensureRendererBuild(rendererRoot: string): void {36+ const distPath = path.join(rendererRoot, "dist", "index.html");37+ if (fs.existsSync(distPath)) {38+ return;39+ }40+41+ const bunPath = process.env.BUN_BIN ?? "bun";42+ const build = spawnSync(bunPath, ["run", "--cwd", rendererRoot, "build"], {43+ stdio: "inherit",44+ env: {45+ ...process.env,46+ PATH: `${process.env.HOME}/.bun/bin:${process.env.PATH}`,apps/t3/src/runtimeApiServer.ts line 211Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +110,21 @@110+ socket.send(JSON.stringify(message));111+}112+113+function openPathInFileManager(targetPath: string): void {114+ const command =115+ process.platform === "win32" ? "explorer" : process.platform === "darwin" ? "open" : "xdg-open";116+117+ const child = spawn(command, [targetPath], {118+ detached: true,119+ stdio: "ignore",120+ });121+ child.unref();122+}123+124+async function tryCommand(command: string, args: string[]): Promise<string | null> {125+ return new Promise((resolve) => {126+ const child = spawn(command, args, {127+ stdio: ["ignore", "pipe", "ignore"],128+ });129+130+ let output = "";apps/t3/src/runtimeApiServer.ts lines 202 to 202Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +101,21 @@101+ error,102+ };103+}104+105+function sendMessage(socket: WebSocket, message: unknown): void {106+ if (socket.readyState !== socket.OPEN) {107+ return;108+ }109+110+ socket.send(JSON.stringify(message));111+}112+113+function openPathInFileManager(targetPath: string): void {114+ const command =115+ process.platform === "win32" ? "explorer" : process.platform === "darwin" ? "open" : "xdg-open";116+117+ const child = spawn(command, [targetPath], {118+ detached: true,119+ stdio: "ignore",120+ });121+ child.unref();apps/t3/src/runtimeApiServer.ts line 297Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +186,21 @@186+ const shellPath =187+ process.platform === "win32"188+ ? (process.env.ComSpec ?? "cmd.exe")189+ : (process.env.SHELL ?? "/bin/sh");190+ const args =191+ process.platform === "win32" ? ["/d", "/s", "/c", parsed.command] : ["-lc", parsed.command];192+193+ return new Promise<{194+ stdout: string;195+ stderr: string;196+ code: number | null;197+ signal: string | null;198+ timedOut: boolean;199+ }>((resolve, reject) => {200+ const child = spawn(shellPath, args, {201+ cwd: parsed.cwd,202+ env: process.env,203+ stdio: ["ignore", "pipe", "pipe"],204+ });205+206+ let stdout = "";apps/t3/src/runtimeApiServer.ts line 214OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +194,21 @@194+ stdout: string;195+ stderr: string;196+ code: number | null;197+ signal: string | null;198+ timedOut: boolean;199+ }>((resolve, reject) => {200+ const child = spawn(shellPath, args, {201+ cwd: parsed.cwd,202+ env: process.env,203+ stdio: ["ignore", "pipe", "pipe"],204+ });205+206+ let stdout = "";207+ let stderr = "";208+ let timedOut = false;209+210+ const timeout = setTimeout(() => {211+ timedOut = true;212+ child.kill("SIGTERM");213+ setTimeout(() => {214+ if (!child.killed) {apps/renderer/src/wsNativeApi.ts lines 58 to 59OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +39,21 @@39+40+ this.connectPromise = new Promise<WebSocket>((resolve, reject) => {41+ const socket = new WebSocket(this.wsUrl);42+ this.socket = socket;43+44+ socket.addEventListener("open", () => {45+ this.connectPromise = null;46+ resolve(socket);47+ });48+49+ socket.addEventListener("error", () => {50+ this.connectPromise = null;51+ reject(new Error("Failed to connect to local t3 runtime."));52+ });53+54+ socket.addEventListener("message", (event) => {55+ this.handleMessage(event.data);56+ });57+58+ socket.addEventListener("close", () => {59+ this.socket = null;apps/t3/src/cli.ts lines 16 to 16OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,16 @@1+#!/usr/bin/env node2+import { spawn, spawnSync } from "node:child_process";3+import fs from "node:fs";4+import { createServer } from "node:http";5+import path from "node:path";6+import { fileURLToPath } from "node:url";7+8+import { startRuntimeApiServer } from "./runtimeApiServer";9+10+function parsePort(value: string | undefined, fallback: number): number {11+ if (!value) {12+ return fallback;13+ }14+15+ const parsed = Number(value);16+ if (!Number.isInteger(parsed) || parsed <= 0) {
- apps/t3/src/cli.ts line 146OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +126,21 @@126+127+ const wsParam = encodeURIComponent(runtimeServer.wsUrl);128+ const appUrl = `http://127.0.0.1:${webPort}?ws=${wsParam}`;129+ openBrowser(appUrl);130+131+ process.stdout.write(`CodeThing is running at ${appUrl}\n`);132+133+ const shutdown = async () => {134+ await Promise.all([staticServer.close(), runtimeServer.close()]);135+ process.exit(0);136+ };137+138+ process.on("SIGINT", () => {139+ void shutdown();140+ });141+ process.on("SIGTERM", () => {142+ void shutdown();143+ });144+}145+146+void main();
- apps/t3/src/runtimeApiServer.ts line 202Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +105,21 @@105+106+function sendMessage(socket: WebSocket, message: unknown): void {107+ if (socket.readyState !== socket.OPEN) {108+ return;109+ }110+111+ socket.send(JSON.stringify(message));112+}113+114+function openPathInFileManager(targetPath: string): void {115+ const command =116+ process.platform === "win32" ? "explorer" : process.platform === "darwin" ? "open" : "xdg-open";117+118+ const child = spawn(command, [targetPath], {119+ detached: true,120+ stdio: "ignore",121+ });122+ child.on("error", () => {123+ // Best-effort shell handoff.124+ });125+ child.unref();
- apps/renderer/src/wsNativeApi.ts line 436Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +118,21 @@118+ }119+120+ if (message.channel === WS_EVENT_CHANNELS.agentExit) {121+ for (const listener of this.agentExitListeners) {122+ listener(message.payload as AgentExit);123+ }124+ }125+ }126+127+ private handleMessage(raw: unknown) {128+ let parsedRaw: unknown;129+ try {130+ parsedRaw =131+ typeof raw === "string"132+ ? JSON.parse(raw)133+ : JSON.parse(new TextDecoder().decode(raw as ArrayBuffer));134+ } catch {135+ return;136+ }137+138+ const parsed = wsServerMessageSchema.safeParse(parsedRaw);apps/t3/src/runtimeApiServer.ts line 207Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +110,21 @@110+111+ socket.send(JSON.stringify(message));112+}113+114+function openPathInFileManager(targetPath: string): void {115+ const command =116+ process.platform === "win32" ? "explorer" : process.platform === "darwin" ? "open" : "xdg-open";117+118+ const child = spawn(command, [targetPath], {119+ detached: true,120+ stdio: "ignore",121+ });122+ child.on("error", () => {123+ // Best-effort shell handoff.124+ });125+ child.unref();126+}127+128+async function tryCommand(command: string, args: string[]): Promise<string | null> {129+ return new Promise((resolve) => {130+ const child = spawn(command, args, {
- apps/renderer/src/wsNativeApi.ts lines 304 to 337Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +67,21 @@67+ return this.connectPromise;68+ }69+70+ private async request(method: string, params?: unknown) {71+ const socket = await this.connect();72+ const id = String(this.nextRequestId);73+ this.nextRequestId += 1;74+75+ const requestMessage: WsClientMessage = {76+ type: "request",77+ id,78+ method,79+ params,80+ };81+82+ const requestPromise = new Promise<unknown>((resolve, reject) => {83+ this.pending.set(id, { resolve, reject });84+ });85+86+ socket.send(JSON.stringify(requestMessage));87+ return requestPromise;
- @@ -0,0 +157,21 @@157+158+ let parsedRaw: unknown;159+ try {160+ parsedRaw = JSON.parse(decoded);161+ } catch {162+ return;163+ }164+165+ const parsed = wsServerMessageSchema.safeParse(parsedRaw);166+ if (!parsed.success) {167+ return;168+ }169+170+ if (parsed.data.type === "response") {171+ this.handleResponse(parsed.data);172+ return;173+ }174+175+ if (parsed.data.type === "event") {176+ this.handleEvent(parsed.data);177+ }
- apps/t3/src/runtimeApiServer.ts line 320Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +214,21 @@214+ let timedOut = false;215+216+ const timeout = setTimeout(() => {217+ timedOut = true;218+ child.kill("SIGTERM");219+ setTimeout(() => {220+ if (!child.killed) {221+ child.kill("SIGKILL");222+ }223+ }, 1_000).unref();224+ }, parsed.timeoutMs ?? 30_000);225+226+ child.stdout?.on("data", (chunk: Buffer) => {227+ stdout += chunk.toString();228+ });229+ child.stderr?.on("data", (chunk: Buffer) => {230+ stderr += chunk.toString();231+ });232+ child.on("error", (error) => {233+ clearTimeout(timeout);234+ reject(error);
- apps/t3/src/runtimeApiServer.ts line 449Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +276,21 @@276+ emitEvent(WS_EVENT_CHANNELS.agentOutput, chunk);277+ });278+ processManager.on("exit", (payload) => {279+ emitEvent(WS_EVENT_CHANNELS.agentExit, payload);280+ });281+ providerManager.on("event", (payload) => {282+ emitEvent(WS_EVENT_CHANNELS.providerEvent, payload);283+ });284+285+ const createBootstrapErrorSession = (message: string): ProviderSession => {286+ const timestamp = new Date().toISOString();287+ return {288+ sessionId: `bootstrap-error-${Date.now()}`,289+ provider: "codex",290+ status: "error",291+ cwd: launchCwd,292+ model: DEFAULT_MODEL,293+ createdAt: timestamp,294+ updatedAt: timestamp,295+ lastError: message,296+ };
- apps/t3/src/cli.ts lines 194 to 196OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +176,21 @@176+ if (filePath.endsWith(".html")) return "text/html; charset=utf-8";177+ if (filePath.endsWith(".js")) return "application/javascript; charset=utf-8";178+ if (filePath.endsWith(".css")) return "text/css; charset=utf-8";179+ if (filePath.endsWith(".json")) return "application/json; charset=utf-8";180+ if (filePath.endsWith(".svg")) return "image/svg+xml";181+ if (filePath.endsWith(".png")) return "image/png";182+ if (filePath.endsWith(".jpg") || filePath.endsWith(".jpeg")) return "image/jpeg";183+ if (filePath.endsWith(".woff2")) return "font/woff2";184+ if (filePath.endsWith(".woff")) return "font/woff";185+ return "application/octet-stream";186+}187+188+function startStaticWebServer(distRoot: string, port: number) {189+ const server = createServer((request, response) => {190+ const requestPath = request.url ? request.url.split("?")[0] : "/";191+ const normalized =192+ requestPath === "/" ? "index.html" : (requestPath ?? "/").replace(/^\/+/, "");193+ const safePath = path.normalize(normalized).replace(/^(\.\.[/\\])+/, "");194+ const filePath = path.join(distRoot, safePath);195+196+ if (!filePath.startsWith(distRoot)) {apps/t3/src/cli.ts lines 190 to 190OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +170,21 @@170+ if (build.status !== 0) {171+ throw new Error("Failed to build renderer assets.");172+ }173+}174+175+function contentTypeFor(filePath: string): string {176+ if (filePath.endsWith(".html")) return "text/html; charset=utf-8";177+ if (filePath.endsWith(".js")) return "application/javascript; charset=utf-8";178+ if (filePath.endsWith(".css")) return "text/css; charset=utf-8";179+ if (filePath.endsWith(".json")) return "application/json; charset=utf-8";180+ if (filePath.endsWith(".svg")) return "image/svg+xml";181+ if (filePath.endsWith(".png")) return "image/png";182+ if (filePath.endsWith(".jpg") || filePath.endsWith(".jpeg")) return "image/jpeg";183+ if (filePath.endsWith(".woff2")) return "font/woff2";184+ if (filePath.endsWith(".woff")) return "font/woff";185+ return "application/octet-stream";186+}187+188+function startStaticWebServer(distRoot: string, port: number) {189+ const server = createServer((request, response) => {190+ const requestPath = request.url ? request.url.split("?")[0] : "/";apps/t3/src/cli.ts lines 202 to 203OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +183,21 @@183+ if (filePath.endsWith(".woff2")) return "font/woff2";184+ if (filePath.endsWith(".woff")) return "font/woff";185+ return "application/octet-stream";186+}187+188+function startStaticWebServer(distRoot: string, port: number) {189+ const server = createServer((request, response) => {190+ const requestPath = request.url ? request.url.split("?")[0] : "/";191+ const normalized =192+ requestPath === "/" ? "index.html" : (requestPath ?? "/").replace(/^\/+/, "");193+ const safePath = path.normalize(normalized).replace(/^(\.\.[/\\])+/, "");194+ const filePath = path.join(distRoot, safePath);195+196+ if (!filePath.startsWith(distRoot)) {197+ response.statusCode = 403;198+ response.end("Forbidden");199+ return;200+ }201+202+ const exists = fs.existsSync(filePath);203+ const targetPath = exists ? filePath : path.join(distRoot, "index.html");
- @@ -0,0 +74,21 @@74+ backendPort = parsePort(75+ readArgValue(argv, index, "--backend-port"),76+ DEFAULT_BACKEND_PORT,77+ );78+ index += 1;79+ continue;80+ }81+82+ if (arg.startsWith("--web-port=")) {83+ webPort = parsePort(arg.split("=")[1], DEFAULT_WEB_PORT);84+ continue;85+ }86+87+ if (arg === "--web-port") {88+ webPort = parsePort(readArgValue(argv, index, "--web-port"), DEFAULT_WEB_PORT);89+ index += 1;90+ continue;91+ }92+93+ if (arg.startsWith("--cwd=")) {94+ launchCwd = path.resolve(arg.split("=")[1] ?? cwd);@@ -0,0 +14,21 @@14+ reject(new Error("Could not resolve free port."));15+ return;16+ }17+ const { port } = address;18+ server.close((error) => {19+ if (error) {20+ reject(error);21+ return;22+ }23+ resolve(port);24+ });25+ });26+ server.on("error", (error) => reject(error));27+ });28+}29+30+function waitForProcessExit(processRef) {31+ return new Promise((resolve) => {32+ processRef.once("exit", (code) => resolve(code));33+ });34+}
- apps/t3/src/runtimeApiServer.ts line 406Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +239,21 @@239+ clearTimeout(timeout);240+ resolve({241+ stdout,242+ stderr,243+ code: code ?? null,244+ signal: signal ?? null,245+ timedOut,246+ });247+ });248+ });249+}250+251+export async function startRuntimeApiServer(252+ options: RuntimeApiServerOptions,253+): Promise<RuntimeApiServer> {254+ const launchCwd = path.resolve(options.launchCwd);255+ const bootstrapSessionTimeoutMs =256+ options.bootstrapSessionTimeoutMs ?? BOOTSTRAP_SESSION_TIMEOUT_MS;257+ const providerManager = new ProviderManager();258+ const processManager = new ProcessManager();259+ const todoStore = new TodoStore(path.join(os.homedir(), ".t3", "todos.json"));apps/t3/src/cli.ts lines 1096 to 1096Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +289,21 @@289+ server.listen(port, "127.0.0.1", () => {290+ resolve({291+ close: async () => {292+ await new Promise<void>((closeResolve) => {293+ server.close(() => closeResolve());294+ });295+ },296+ });297+ });298+ });299+}300+301+async function main() {302+ let options: CliOptions;303+ try {304+ options = parseCliOptions(process.argv.slice(2), process.env, process.cwd());305+ } catch (error) {306+ process.stderr.write(`${error instanceof Error ? error.message : "Invalid arguments."}\n\n`);307+ printHelp();308+ process.exit(1);309+ return;apps/t3/src/cli.ts lines 497 to 498Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +227,21 @@227+ return;228+ }229+230+ const bunPath = process.env.BUN_BIN ?? "bun";231+ const build = spawnSync(bunPath, ["run", "--cwd", rendererRoot, "build"], {232+ stdio: "inherit",233+ env: {234+ ...process.env,235+ PATH: `${process.env.HOME}/.bun/bin:${process.env.PATH}`,236+ },237+ });238+ if (build.status !== 0) {239+ throw new Error("Failed to build renderer assets.");240+ }241+}242+243+function contentTypeFor(filePath: string): string {244+ if (filePath.endsWith(".html")) return "text/html; charset=utf-8";245+ if (filePath.endsWith(".js")) return "application/javascript; charset=utf-8";246+ if (filePath.endsWith(".css")) return "text/css; charset=utf-8";247+ if (filePath.endsWith(".json")) return "application/json; charset=utf-8";
- @@ -0,0 +192,21 @@192+ | undefined;193+ try {194+ staticServer = await startStaticWebServer(path.join(rendererRoot, "dist"), options.webPort);195+ } catch (error) {196+ await runtimeServer.close();197+ throw error;198+ }199+200+ const wsParam = encodeURIComponent(runtimeServer.wsUrl);201+ const appUrl = `http://127.0.0.1:${options.webPort}?ws=${wsParam}`;202+ openBrowser(appUrl, options.noOpen);203+204+ process.stdout.write(`CodeThing is running at ${appUrl}\n`);205+206+ let shutdownStarted = false;207+ const shutdown = async () => {208+ if (shutdownStarted) {209+ return;210+ }211+ shutdownStarted = true;212+ await Promise.all([staticServer.close(), runtimeServer.close()]);
- apps/t3/scripts/smoke-test.mjs lines 1879 to 1882Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +88,21 @@88+ id: "smoke",89+ method: "app.health",90+ }),91+ );92+ });93+ ws.addEventListener("message", (event) => {94+ const message = JSON.parse(String(event.data));95+ if (96+ message.type === "response" &&97+ message.id === "smoke" &&98+ message.ok === true &&99+ message.result?.status === "ok"100+ ) {101+ clearTimeout(timer);102+ resolve();103+ }104+ });105+ ws.addEventListener("error", () => {106+ clearTimeout(timer);107+ reject(new Error("Smoke test failed: websocket client error."));108+ });
- apps/t3/scripts/smoke-test.mjs line 94OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +74,21 @@74+ if (page.status !== 200) {75+ throw new Error(`Smoke test failed: expected web status 200, received ${page.status}.`);76+ }77+78+ const ws = new WebSocket(`ws://127.0.0.1:${backendPort}`);79+ await new Promise((resolve, reject) => {80+ const timer = setTimeout(81+ () => reject(new Error("Smoke test failed: websocket did not respond in time.")),82+ 20_000,83+ );84+ ws.addEventListener("open", () => {85+ ws.send(86+ JSON.stringify({87+ type: "request",88+ id: "smoke",89+ method: "app.health",90+ }),91+ );92+ });93+ ws.addEventListener("message", (event) => {94+ const message = JSON.parse(String(event.data));apps/t3/scripts/smoke-test.mjs lines 485 to 485Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +17,21 @@17+ const { port } = address;18+ server.close((error) => {19+ if (error) {20+ reject(error);21+ return;22+ }23+ resolve(port);24+ });25+ });26+ server.on("error", (error) => reject(error));27+ });28+}29+30+function waitForProcessExit(processRef) {31+ return new Promise((resolve) => {32+ processRef.once("exit", (code) => resolve(code));33+ });34+}35+36+async function main() {37+ const [backendPort, webPort] = await Promise.all([getFreePort(), getFreePort()]);
- @@ -25,3 +25,8 @@2525 return null;2626 }272728+function BootstrapRouter() {29+ const api = readNativeApi();30+ const { dispatch } = useStore();31+32+ useEffect(() => {
- apps/t3/src/runtimeApiServer.ts line 154Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +96,21 @@96+}97+98+function responseSuccess(id: string, result: unknown): WsResponseMessage {99+ return {100+ type: "response",101+ id,102+ ok: true,103+ result,104+ };105+}106+107+function responseError(id: string, error: JsonRpcErrorResult): WsResponseMessage {108+ return {109+ type: "response",110+ id,111+ ok: false,112+ error,113+ };114+}115+116+function sendMessage(socket: WebSocket, message: unknown): void {
- apps/t3/scripts/smoke-test.mjs lines 1799 to 1800Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +158,21 @@158+ if (!parsedWsUrl.searchParams.get("token")) {159+ throw new Error("Smoke test failed: websocket URL is missing runtime auth token.");160+ }161+162+ const unauthorizedWsUrl = `${parsedWsUrl.origin}${parsedWsUrl.pathname}`;163+ const unauthorizedWs = new WebSocket(unauthorizedWsUrl);164+ const unauthorizedCode = await waitForSocketCloseCode(unauthorizedWs);165+ if (unauthorizedCode !== 4001) {166+ throw new Error(167+ `Smoke test failed: expected unauthorized close code 4001, received ${unauthorizedCode}.`,168+ );169+ }170+171+ const ws = new WebSocket(wsUrl);172+ await new Promise((resolve, reject) => {173+ const timer = setTimeout(174+ () => reject(new Error("Smoke test failed: websocket did not respond in time.")),175+ 20_000,176+ );177+ ws.addEventListener("open", () => {178+ ws.send(
- apps/t3/scripts/smoke-test.mjs line 63OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +43,21 @@43+ new Promise((resolve) => {44+ setTimeout(() => resolve(false), timeoutMs);45+ }),46+ ]);47+48+ if (exited) {49+ return;50+ }51+52+ processRef.kill("SIGKILL");53+ await waitForProcessExit(processRef);54+}55+56+function waitForSocketCloseCode(socket, timeoutMs = 10_000) {57+ return new Promise((resolve, reject) => {58+ const timer = setTimeout(() => {59+ reject(new Error("Smoke test failed: websocket close event timed out."));60+ }, timeoutMs);61+ socket.addEventListener("close", (event) => {62+ clearTimeout(timer);63+ resolve(event.code);
- @@ -27,0 +69,21 @@69+ let cancelled = false;70+71+ const checkHealth = async () => {72+ try {73+ await api.app.health();74+ if (cancelled) return;75+ dispatch({ type: "SET_RUNTIME_ERROR", error: null });76+ } catch (error) {77+ if (cancelled) return;78+ dispatch({79+ type: "SET_RUNTIME_ERROR",80+ error:81+ error instanceof Error82+ ? error.message83+ : "Could not connect to the local t3 runtime.",84+ });85+ }86+ };87+88+ void checkHealth();89+ const interval = window.setInterval(() => {
- @@ -0,0 +56,21 @@56+ });57+58+ socket.addEventListener("message", (event) => {59+ void this.handleMessage(event.data);60+ });61+62+ socket.addEventListener("close", () => {63+ this.socket = null;64+ for (const [id, pending] of this.pending.entries()) {65+ clearTimeout(pending.timeout);66+ pending.reject(new Error(`Request ${id} failed: websocket disconnected.`));67+ }68+ this.pending.clear();69+ });70+ });71+72+ return this.connectPromise;73+ }74+75+ private async request(method: string, params?: unknown) {76+ const socket = await this.connect();
- @@ -0,0 +276,21 @@276+ stopSession: async (input) => {277+ await this.request("providers.stopSession", input);278+ },279+ listSessions: async () =>280+ this.request("providers.listSessions").then(281+ (value) => value as Awaited<ReturnType<NativeApi["providers"]["listSessions"]>>,282+ ),283+ onEvent: (callback) => {284+ this.providerEventListeners.add(callback);285+ return () => {286+ this.providerEventListeners.delete(callback);287+ };288+ },289+ },290+ shell: {291+ openInEditor: async (cwd, editor) => {292+ await this.request("shell.openInEditor", { cwd, editor });293+ },294+ },295+ };296+ }
- @@ -0,0 +150,21 @@150+ }151+ }152+ }153+154+ private async decodeIncomingMessage(raw: unknown): Promise<string | null> {155+ if (typeof raw === "string") {156+ return raw;157+ }158+159+ if (raw instanceof ArrayBuffer) {160+ return textDecoder.decode(raw);161+ }162+163+ if (raw instanceof Blob) {164+ return raw.text();165+ }166+167+ return null;168+ }169+170+ private async handleMessage(raw: unknown) {
- @@ -330,0 +357,21 @@357+ return {358+ ...state,359+ projects: existingProject360+ ? state.projects.map((entry) =>361+ entry.id === existingProject.id362+ ? {363+ ...entry,364+ model: resolveModelSlug(bootstrap.model),365+ }366+ : entry,367+ )368+ : [project, ...state.projects],369+ threads: state.threads370+ .map((entry) =>371+ entry.id === thread.id372+ ? {373+ ...entry,374+ session: bootstrap.session,375+ codexThreadId: bootstrap.session.threadId ?? entry.codexThreadId,376+ error: bootstrap.bootstrapError ?? entry.error,377+ }
- apps/t3/scripts/smoke-test.mjs line 254Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +38,21 @@38+ }39+40+ processRef.kill("SIGTERM");41+ const exited = await Promise.race([42+ waitForProcessExit(processRef).then(() => true),43+ new Promise((resolve) => {44+ setTimeout(() => resolve(false), timeoutMs);45+ }),46+ ]);47+48+ if (exited) {49+ return;50+ }51+52+ processRef.kill("SIGKILL");53+ await waitForProcessExit(processRef);54+}55+56+function waitForSocketCloseCode(socket, timeoutMs = 10_000) {57+ return new Promise((resolve, reject) => {58+ const timer = setTimeout(() => {
- @@ -0,0 +26,21 @@26+ });27+}28+29+function waitForProcessExit(processRef) {30+ return new Promise((resolve) => {31+ processRef.once("exit", (code) => resolve(code));32+ });33+}34+35+async function terminateProcess(processRef, timeoutMs = 5_000) {36+ if (processRef.exitCode !== null || processRef.signalCode !== null) {37+ return;38+ }39+40+ processRef.kill("SIGTERM");41+ const exited = await Promise.race([42+ waitForProcessExit(processRef).then(() => true),43+ new Promise((resolve) => {44+ setTimeout(() => resolve(false), timeoutMs);45+ }),46+ ]);
- @@ -0,0 +33,21 @@33+}34+35+async function terminateProcess(processRef, timeoutMs = 5_000) {36+ if (processRef.exitCode !== null || processRef.signalCode !== null) {37+ return;38+ }39+40+ processRef.kill("SIGTERM");41+ const exited = await Promise.race([42+ waitForProcessExit(processRef).then(() => true),43+ new Promise((resolve) => {44+ setTimeout(() => resolve(false), timeoutMs);45+ }),46+ ]);47+48+ if (exited) {49+ return;50+ }51+52+ processRef.kill("SIGKILL");53+ await waitForProcessExit(processRef);
- @@ -0,0 +79,21 @@79+ `Smoke test failed: unauthorized websocket received ${messageCount} message(s) before close.`,80+ ),81+ );82+ return;83+ }84+ resolve();85+ });86+ socket.addEventListener("error", () => {87+ clearTimeout(timer);88+ reject(new Error("Smoke test failed: websocket client error before close."));89+ });90+ });91+}92+93+function waitForStartupUrl(readOutput, processRef, timeoutMs = 20_000) {94+ return new Promise((resolve, reject) => {95+ const finish = (callback, value) => {96+ clearInterval(timer);97+ processRef.off("exit", onExit);98+ callback(value);99+ };
- @@ -0,0 +78,21 @@78+ new Error(79+ `Smoke test failed: unauthorized websocket received ${messageCount} message(s) before close.`,80+ ),81+ );82+ return;83+ }84+ resolve();85+ });86+ socket.addEventListener("error", () => {87+ clearTimeout(timer);88+ reject(new Error("Smoke test failed: websocket client error before close."));89+ });90+ });91+}92+93+function waitForStartupUrl(readOutput, processRef, timeoutMs = 20_000) {94+ return new Promise((resolve, reject) => {95+ const finish = (callback, value) => {96+ clearInterval(timer);97+ processRef.off("exit", onExit);98+ callback(value);
- apps/t3/scripts/smoke-test.mjs lines 514 to 514Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +130,21 @@130+ const distCli = path.join(appRoot, "dist", "cli.js");131+ if (!fs.existsSync(distCli)) {132+ throw new Error("Missing dist/cli.js. Run `bun run --cwd apps/t3 build` first.");133+ }134+135+ const child = spawn(136+ process.execPath,137+ [138+ distCli,139+ "-o=0",140+ "--backend-port",141+ String(backendPort),142+ "--web-port",143+ String(webPort),144+ ],145+ {146+ cwd: appRoot,147+ env: process.env,148+ stdio: ["ignore", "pipe", "pipe"],149+ },150+ );
- apps/t3/scripts/smoke-test.mjs lines 1827 to 1829Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +891,21 @@891+ );892+ });893+ ws.addEventListener("message", (event) => {894+ const message = JSON.parse(String(event.data));895+ if (message.type === "hello") {896+ if (message.version !== 1) {897+ clearTimeout(timer);898+ reject(899+ new Error(900+ `Smoke test failed: expected hello version 1, got ${String(message.version)}.`,901+ ),902+ );903+ return;904+ }905+ if (message.launchCwd !== appRoot) {906+ clearTimeout(timer);907+ reject(908+ new Error(909+ `Smoke test failed: expected hello launch cwd ${appRoot}, got ${String(910+ message.launchCwd,911+ )}.`,
- @@ -0,0 +32,21 @@32+ });33+}34+35+async function terminateProcess(processRef, timeoutMs = 5_000) {36+ if (processRef.exitCode !== null || processRef.signalCode !== null) {37+ return;38+ }39+40+ processRef.kill("SIGTERM");41+ const exited = await Promise.race([42+ waitForProcessExit(processRef).then(() => true),43+ new Promise((resolve) => {44+ setTimeout(() => resolve(false), timeoutMs);45+ }),46+ ]);47+48+ if (exited) {49+ return;50+ }51+52+ processRef.kill("SIGKILL");
- @@ -0,0 +1,15 @@1+import { spawn } from "node:child_process";2+import fs from "node:fs";3+import { createServer } from "node:net";4+import path from "node:path";5+import { fileURLToPath } from "node:url";6+7+function getFreePort() {8+ return new Promise((resolve, reject) => {9+ const server = createServer();10+ server.listen(0, "127.0.0.1", () => {11+ const address = server.address();12+ if (!address || typeof address !== "object") {13+ reject(new Error("Could not resolve free port."));14+ return;15+ }
- apps/t3/scripts/smoke-test.mjs lines 532 to 532Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +148,21 @@148+ stdio: ["ignore", "pipe", "pipe"],149+ },150+ );151+152+ let output = "";153+ child.stdout.on("data", (chunk) => {154+ output += chunk.toString();155+ });156+ child.stderr.on("data", (chunk) => {157+ output += chunk.toString();158+ });159+160+ try {161+ const appUrl = await waitForStartupUrl(() => output, child);162+ const parsedAppUrl = new URL(appUrl);163+164+ const page = await fetch(parsedAppUrl);165+ if (page.status !== 200) {166+ throw new Error(`Smoke test failed: expected web status 200, received ${page.status}.`);167+ }168+ if (page.headers.get("x-content-type-options") !== "nosniff") {
- @@ -0,0 +74,21 @@74+ return;75+ }76+ if (messageCount > 0) {77+ reject(78+ new Error(79+ `Smoke test failed: unauthorized websocket received ${messageCount} message(s) before close.`,80+ ),81+ );82+ return;83+ }84+ resolve();85+ });86+ socket.addEventListener("error", () => {87+ clearTimeout(timer);88+ reject(new Error("Smoke test failed: websocket client error before close."));89+ });90+ });91+}92+93+function waitForCloseCode(socket, expectedCode, label, timeoutMs = 10_000) {94+ return new Promise((resolve, reject) => {
- @@ -0,0 +126,21 @@126+ );127+ }, timeoutMs);128+129+ const onMessage = (event) => {130+ let message;131+ try {132+ message = JSON.parse(String(event.data));133+ } catch {134+ return;135+ }136+137+ if (message.type !== "response" || message.id !== request.id) {138+ return;139+ }140+141+ clearTimeout(timer);142+ socket.removeEventListener("message", onMessage);143+ resolve(message);144+ };145+146+ socket.addEventListener("message", onMessage);
- @@ -0,0 +158,21 @@158+function waitForWsEvent(socket, matcher, label, timeoutMs = 20_000) {159+ return new Promise((resolve, reject) => {160+ const timer = setTimeout(() => {161+ socket.removeEventListener("message", onMessage);162+ reject(new Error(`Smoke test failed: ${label} websocket event timed out.`));163+ }, timeoutMs);164+165+ const onMessage = (event) => {166+ let message;167+ try {168+ message = JSON.parse(String(event.data));169+ } catch {170+ return;171+ }172+173+ if (message.type !== "event") {174+ return;175+ }176+ if (!matcher(message)) {177+ return;178+ }
- apps/t3/scripts/smoke-test.mjs line 2413Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1752,21 @@1752+ method: "todos.add",1753+ params: { title: todoTitle },1754+ });1755+ if (addedTodosResponse.ok !== true || !Array.isArray(addedTodosResponse.result)) {1756+ throw new Error("Smoke test failed: expected successful todos.add response.");1757+ }1758+1759+ const addedTodo = addedTodosResponse.result.find((todo) => {1760+ return (1761+ typeof todo?.id === "string" &&1762+ todo.id.length > 0 &&1763+ todo.title === todoTitle &&1764+ todo.completed === false1765+ );1766+ });1767+ if (!addedTodo) {1768+ throw new Error("Smoke test failed: could not locate newly-added todo entry.");1769+ }1770+1771+ const toggledTodosResponse = await sendWsRequest(ws, {1772+ id: "smoke-todos-toggle",
- @@ -0,0 +111,21 @@111+ if (event.code !== expectedCode) {112+ reject(113+ new Error(114+ `Smoke test failed: expected ${label} close code ${expectedCode}, received ${event.code}.`,115+ ),116+ );117+ return;118+ }119+ if (label === "replaced-client" && event.reason !== "replaced-by-new-client") {120+ reject(121+ new Error(122+ `Smoke test failed: expected replaced-client close reason "replaced-by-new-client", received ${JSON.stringify(123+ event.reason,124+ )}.`,125+ ),126+ );127+ return;128+ }129+ resolve();130+ });131+ socket.addEventListener("error", () => {
- apps/renderer/src/wsNativeApi.ts lines 325 to 329Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +252,21 @@252+ this.pending.set(id, { resolve, reject, timeout });253+ });254+255+ try {256+ socket.send(JSON.stringify(requestMessage));257+ } catch (error) {258+ const pending = this.pending.get(id);259+ if (pending) {260+ clearTimeout(pending.timeout);261+ this.pending.delete(id);262+ pending.reject(263+ new Error(264+ `Failed to send runtime request '${method}': ${265+ error instanceof Error ? error.message : "unknown websocket failure"266+ }`,267+ ),268+ );269+ }270+ if (this.socket === socket) {271+ this.socket = null;272+ }
- @@ -27,0 +55,21 @@55+ return () => {56+ cancelled = true;57+ };58+ }, [api, dispatch]);59+60+ return null;61+}62+63+function RuntimeHealthRouter() {64+ const api = readNativeApi();65+ const { dispatch } = useStore();66+67+ useEffect(() => {68+ if (!api) return;69+ let cancelled = false;70+71+ const checkHealth = async () => {72+ try {73+ await api.app.health();74+ if (cancelled) return;75+ dispatch({ type: "SET_RUNTIME_ERROR", error: null });
- apps/renderer/src/wsNativeApi.ts lines 326 to 329Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +278,21 @@278+ });279+280+ try {281+ socket.send(JSON.stringify(requestMessage));282+ } catch (error) {283+ const pending = this.pending.get(id);284+ if (pending) {285+ clearTimeout(pending.timeout);286+ this.pending.delete(id);287+ pending.reject(288+ new Error(289+ `Failed to send runtime request '${method}': ${290+ error instanceof Error ? error.message : "unknown websocket failure"291+ }`,292+ ),293+ );294+ }295+ this.rejectPendingRequests((requestId) => requestSocketError(requestId, error));296+ if (this.socket === socket) {297+ this.socket = null;298+ }
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