From 4eefd16dff4f4fc6f62b35d199a668f23a741d57 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Jul 2025 09:00:35 -0700 Subject: [PATCH] feat: exit endpoint --- src/commands/serve.test.ts | 90 ++++++++++++++++++++++++++++++++++++++ src/commands/serve.ts | 31 +++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 src/commands/serve.test.ts diff --git a/src/commands/serve.test.ts b/src/commands/serve.test.ts new file mode 100644 index 000000000..848af3bca --- /dev/null +++ b/src/commands/serve.test.ts @@ -0,0 +1,90 @@ +import { describe, it, expect, beforeEach, afterEach, jest } from "@jest/globals"; +import request from "supertest"; +import express from "express"; + +// Mock dependencies +jest.mock("../auth/workos.js", () => ({ + loadAuthConfig: jest.fn(() => null), + ensureOrganization: jest.fn(), + getOrganizationId: jest.fn(), +})); + +jest.mock("../onboarding.js", () => ({ + runNormalFlow: jest.fn(() => Promise.resolve({ + config: {}, + llmApi: {}, + model: {}, + })), +})); + +jest.mock("../session.js", () => ({ + saveSession: jest.fn(), +})); + +jest.mock("../systemMessage.js", () => ({ + constructSystemMessage: jest.fn(() => Promise.resolve("System message")), +})); + +jest.mock("../telemetry/telemetryService.js", () => ({ + recordSessionStart: jest.fn(), + startActiveTime: jest.fn(), + stopActiveTime: jest.fn(), + updateOrganization: jest.fn(), +})); + +jest.mock("../util/logger.js", () => ({ + error: jest.fn(), + debug: jest.fn(), +})); + +describe("serve command", () => { + let originalProcessExit: typeof process.exit; + + beforeEach(() => { + // Mock process.exit to prevent actual exit during tests + originalProcessExit = process.exit; + process.exit = jest.fn() as any; + }); + + afterEach(() => { + // Restore original process.exit + process.exit = originalProcessExit; + jest.clearAllMocks(); + }); + + it("should have /exit endpoint that returns success response", async () => { + // Import serve after mocking dependencies + const { serve } = await import("./serve.js"); + + // Start server with a random port to avoid conflicts + const port = Math.floor(Math.random() * 10000) + 30000; + + // Start the server in the background + const serverPromise = serve(undefined, { port: port.toString() }); + + // Give the server a moment to start + await new Promise(resolve => setTimeout(resolve, 100)); + + try { + // Test the /exit endpoint + const response = await request(`http://localhost:${port}`) + .post("/exit") + .expect(200); + + expect(response.body).toEqual({ + message: "Server shutting down", + success: true, + }); + + // Give the server a moment to shut down + await new Promise(resolve => setTimeout(resolve, 200)); + + // Verify process.exit was called + expect(process.exit).toHaveBeenCalledWith(0); + } catch (error) { + // If the test fails, we still want to try to clean up + console.error("Test failed:", error); + throw error; + } + }, 10000); // 10 second timeout for this test +}); \ No newline at end of file diff --git a/src/commands/serve.ts b/src/commands/serve.ts index 33794fbe3..d5a7f1916 100644 --- a/src/commands/serve.ts +++ b/src/commands/serve.ts @@ -169,6 +169,36 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { } }); + // POST /exit - Gracefully shut down the server + app.post("/exit", async (_req: Request, res: Response) => { + console.log(chalk.yellow("\nReceived exit request, shutting down server...")); + + // Respond immediately before shutting down + res.json({ + message: "Server shutting down", + success: true + }); + + // Set server running flag to false to stop processing + state.serverRunning = false; + + // Abort any current processing + if (state.currentAbortController) { + state.currentAbortController.abort(); + } + + // Clear the message queue + state.messageQueue = []; + + // Give a moment for the response to be sent + setTimeout(() => { + server.close(() => { + telemetryService.stopActiveTime(); + process.exit(0); + }); + }, 100); + }); + const server = app.listen(port, () => { console.log(chalk.green(`Server started on http://localhost:${port}`)); console.log(chalk.dim("Endpoints:")); @@ -177,6 +207,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { chalk.dim(" POST /message - Send a message (body: { message: string })") ); console.log(chalk.dim(" GET /diff - Get git diff against main branch")); + console.log(chalk.dim(" POST /exit - Gracefully shut down the server")); console.log( chalk.dim( `\nServer will shut down after ${timeoutSeconds} seconds of inactivity`