diff --git a/apps/t3/src/runtimeApiServer.test.ts b/apps/t3/src/runtimeApiServer.test.ts index b5c9d5a12f..3d057feb4d 100644 --- a/apps/t3/src/runtimeApiServer.test.ts +++ b/apps/t3/src/runtimeApiServer.test.ts @@ -199,6 +199,52 @@ describe("runtimeApiServer", () => { } }); + it("handles repeated bootstrap requests under failure conditions", async () => { + const originalPath = process.env.PATH; + process.env.PATH = ""; + try { + const server = await startRuntimeApiServer({ + port: 0, + launchCwd: process.cwd(), + bootstrapSessionTimeoutMs: 100, + }); + servers.push(server); + + const client = await connectClient(server.wsUrl); + await client.nextMessage(); + + const first = await sendRequest( + client.socket, + client.nextMessage, + "bootstrap-repeat-1", + "app.bootstrap", + ); + const second = await sendRequest( + client.socket, + client.nextMessage, + "bootstrap-repeat-2", + "app.bootstrap", + ); + + expect(first.ok).toBe(true); + expect(second.ok).toBe(true); + if (!first.ok || !second.ok) { + throw new Error("Expected both bootstrap responses to succeed."); + } + + const firstSession = first.result as { session: { sessionId: string; status: string } }; + const secondSession = second.result as { session: { sessionId: string; status: string } }; + expect(firstSession.session.status).toBe("error"); + expect(firstSession.session.sessionId.length).toBeGreaterThan(0); + expect(secondSession.session.sessionId.length).toBeGreaterThan(0); + expect(secondSession.session.status).not.toBe("closed"); + + client.socket.close(); + } finally { + process.env.PATH = originalPath; + } + }); + it("returns structured errors for unknown methods", async () => { const server = await startRuntimeApiServer({ port: 0, diff --git a/apps/t3/src/runtimeApiServer.ts b/apps/t3/src/runtimeApiServer.ts index 16a0d4800a..f3bfb28b7c 100644 --- a/apps/t3/src/runtimeApiServer.ts +++ b/apps/t3/src/runtimeApiServer.ts @@ -89,6 +89,11 @@ interface JsonRpcErrorResult { const BOOTSTRAP_SESSION_TIMEOUT_MS = 3_000; +interface BootstrapSessionResult { + session: ProviderSession; + bootstrapError: string | undefined; +} + function responseSuccess(id: string, result: unknown): WsResponseMessage { return { type: "response", @@ -260,6 +265,8 @@ export async function startRuntimeApiServer( await todoStore.init(); let activeClient: WebSocket | null = null; + let launchSessionPromise: Promise | null = null; + let bootstrapFallbackSession: ProviderSession | null = null; const emitEvent = (channel: string, payload: unknown) => { if (!activeClient) { @@ -297,46 +304,80 @@ export async function startRuntimeApiServer( }; }; - const ensureLaunchSession = async () => { + const ensureLaunchSession = async (): Promise => { const existingSession = providerManager .listSessions() .find((session) => session.cwd === launchCwd && session.status !== "closed"); if (existingSession) { + bootstrapFallbackSession = null; return { session: existingSession, bootstrapError: undefined, }; } - try { - const startedSession = await Promise.race([ - providerManager.startSession({ - provider: "codex", - cwd: launchCwd, - model: DEFAULT_MODEL, - approvalPolicy: "never", - sandboxMode: "danger-full-access", - }), - new Promise((_, reject) => { - setTimeout(() => { - reject(new Error("Timed out starting launch session.")); - }, bootstrapSessionTimeoutMs); - }), - ]); + if (bootstrapFallbackSession) { return { - session: startedSession, - bootstrapError: undefined, - }; - } catch (error) { - const message = - error instanceof Error - ? error.message - : "Failed to initialize Codex launch session."; - return { - session: createBootstrapErrorSession(message), - bootstrapError: message, + session: bootstrapFallbackSession, + bootstrapError: bootstrapFallbackSession.lastError, }; } + + if (launchSessionPromise) { + return launchSessionPromise; + } + + launchSessionPromise = (async () => { + try { + const startedSession = await Promise.race([ + providerManager.startSession({ + provider: "codex", + cwd: launchCwd, + model: DEFAULT_MODEL, + approvalPolicy: "never", + sandboxMode: "danger-full-access", + }), + new Promise((_, reject) => { + setTimeout(() => { + reject(new Error("Timed out starting launch session.")); + }, bootstrapSessionTimeoutMs); + }), + ]); + bootstrapFallbackSession = null; + return { + session: startedSession, + bootstrapError: undefined, + }; + } catch (error) { + const message = + error instanceof Error + ? error.message + : "Failed to initialize Codex launch session."; + const fallbackSession = (() => { + if (!bootstrapFallbackSession) { + return createBootstrapErrorSession(message); + } + + return Object.assign({}, bootstrapFallbackSession, { + lastError: message, + updatedAt: new Date().toISOString(), + }) as ProviderSession; + })(); + bootstrapFallbackSession = fallbackSession; + return { + session: fallbackSession, + bootstrapError: message, + }; + } finally { + launchSessionPromise = null; + } + })(); + + const pendingLaunchSessionPromise = launchSessionPromise; + if (!pendingLaunchSessionPromise) { + throw new Error("Could not initialize launch session promise."); + } + return pendingLaunchSessionPromise; }; const wss = new WebSocketServer({ @@ -392,7 +433,11 @@ export async function startRuntimeApiServer( } if (method === "providers.startSession") { - return providerManager.startSession(providerSessionStartInputSchema.parse(params)); + const session = await providerManager.startSession( + providerSessionStartInputSchema.parse(params), + ); + bootstrapFallbackSession = null; + return session; } if (method === "providers.sendTurn") { return providerManager.sendTurn(providerSendTurnInputSchema.parse(params));