feat: exit endpoint

This commit is contained in:
Nate 2025-07-21 09:00:35 -07:00
parent cba72ba69a
commit 4eefd16dff
2 changed files with 121 additions and 0 deletions

View file

@ -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
});

View file

@ -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`