| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373 |
- import {
- createServer,
- type IncomingMessage,
- type Server,
- type ServerResponse,
- } from 'node:http';
- import { URL } from 'node:url';
- import { extractResumeSlug, readJsonBody, sendHtml, sendJson } from './helpers';
- import type {
- InterviewAnswer,
- InterviewFileItem,
- InterviewListItem,
- InterviewState,
- } from './types';
- import { renderDashboardPage, renderInterviewPage } from './ui';
- function getSubmissionStatus(error: unknown): number {
- if (error instanceof SyntaxError) {
- return 400;
- }
- const message = error instanceof Error ? error.message : '';
- if (message === 'Interview not found') {
- return 404;
- }
- if (message.includes('busy')) {
- return 409;
- }
- if (
- message.includes('waiting for a valid agent update') ||
- message.includes('There are no active interview questions') ||
- message.includes('Answer every active interview question') ||
- message.includes('Answers do not match') ||
- message.includes('Request body too large') ||
- message.includes('Invalid answers payload') ||
- message.includes('no longer active')
- ) {
- return 400;
- }
- return 500;
- }
- function parseAnswersPayload(value: unknown): { answers: InterviewAnswer[] } {
- if (!value || typeof value !== 'object') {
- throw new Error('Invalid answers payload.');
- }
- const answersRaw = (value as { answers?: unknown }).answers;
- if (!Array.isArray(answersRaw)) {
- throw new Error('Invalid answers payload.');
- }
- return {
- answers: answersRaw.map((answer) => {
- if (!answer || typeof answer !== 'object') {
- throw new Error('Invalid answers payload.');
- }
- const record = answer as { questionId?: unknown; answer?: unknown };
- if (
- typeof record.questionId !== 'string' ||
- typeof record.answer !== 'string'
- ) {
- throw new Error('Invalid answers payload.');
- }
- return {
- questionId: record.questionId.trim(),
- answer: record.answer.trim(),
- };
- }),
- };
- }
- export function createInterviewServer(deps: {
- getState: (interviewId: string) => Promise<InterviewState>;
- listInterviewFiles: () => Promise<InterviewFileItem[]>;
- listInterviews: () => InterviewListItem[];
- submitAnswers: (
- interviewId: string,
- answers: InterviewAnswer[],
- ) => Promise<void>;
- submitBlockComment: (
- interviewId: string,
- section: string,
- comment: string,
- ) => Promise<void>;
- submitChat: (interviewId: string, message: string) => Promise<void>;
- handleNudgeAction: (
- interviewId: string,
- action: 'more-questions' | 'confirm-complete',
- ) => Promise<void>;
- outputFolder: string;
- port: number;
- }): {
- ensureStarted: () => Promise<string>;
- close: () => void;
- } {
- let baseUrl: string | null = null;
- let startPromise: Promise<string> | null = null;
- let activeServer: Server | null = null;
- async function loadDashboardData() {
- const interviews = deps.listInterviews().map((item) => {
- const resumeSlug = extractResumeSlug(item.id);
- return {
- ...item,
- url: `/interview/${item.id}`,
- mode: 'active',
- resumeSlug,
- };
- });
- const files = await deps.listInterviewFiles();
- return { interviews, files };
- }
- async function handle(
- request: IncomingMessage,
- response: ServerResponse,
- ): Promise<void> {
- let url: URL;
- try {
- url = new URL(request.url ?? '/', 'http://127.0.0.1');
- } catch {
- sendJson(response, 400, { error: 'Invalid request URL' });
- return;
- }
- const pathname = url.pathname;
- // Dashboard: root page listing all interviews
- if (request.method === 'GET' && pathname === '/') {
- try {
- const { interviews, files } = await loadDashboardData();
- sendHtml(
- response,
- renderDashboardPage(interviews, files, deps.outputFolder),
- );
- } catch {
- sendJson(response, 500, { error: 'Failed to load interviews' });
- }
- return;
- }
- // API: list all interviews as JSON
- if (request.method === 'GET' && pathname === '/api/interviews') {
- try {
- const { interviews, files } = await loadDashboardData();
- sendJson(response, 200, { active: interviews, files });
- } catch {
- sendJson(response, 500, { error: 'Failed to load interviews' });
- }
- return;
- }
- if (request.method === 'GET' && pathname.startsWith('/interview/')) {
- const rawId = decodeURIComponent(pathname.split('/').pop() ?? 'unknown');
- sendHtml(response, renderInterviewPage(rawId, extractResumeSlug(rawId)));
- return;
- }
- const stateMatch = pathname.match(/^\/api\/interviews\/([^/]+)\/state$/);
- if (request.method === 'GET' && stateMatch) {
- try {
- const state = await deps.getState(decodeURIComponent(stateMatch[1]));
- sendJson(response, 200, state);
- } catch (error) {
- const message =
- error instanceof Error ? error.message : 'Interview not found';
- const status = message === 'Interview not found' ? 404 : 500;
- sendJson(response, status, { error: message });
- }
- return;
- }
- // CSRF note: This endpoint intentionally sends no CORS headers.
- // The browser's same-origin policy blocks cross-origin POST with
- // Content-Type: application/json (it triggers a preflight, which
- // 404s here). Do NOT add Access-Control-Allow-Origin without also
- // adding an Origin check or CSRF token.
- const answersMatch = pathname.match(
- /^\/api\/interviews\/([^/]+)\/answers$/,
- );
- if (request.method === 'POST' && answersMatch) {
- try {
- const body = parseAnswersPayload(await readJsonBody(request));
- await deps.submitAnswers(
- decodeURIComponent(answersMatch[1]),
- body.answers,
- );
- sendJson(response, 200, {
- ok: true,
- message: 'Answers submitted to the OpenCode session.',
- });
- } catch (error) {
- const message =
- error instanceof Error ? error.message : 'Failed to submit answers.';
- const status = getSubmissionStatus(error);
- sendJson(response, status, {
- ok: false,
- message,
- });
- }
- return;
- }
- const blockCommentMatch = pathname.match(
- /^\/api\/interviews\/([^/]+)\/block-comment$/,
- );
- if (request.method === 'POST' && blockCommentMatch) {
- try {
- const body = (await readJsonBody(request)) as {
- section?: string;
- comment?: string;
- };
- if (
- typeof body.section !== 'string' ||
- typeof body.comment !== 'string'
- ) {
- sendJson(response, 400, {
- error: 'section and comment must be strings',
- });
- return;
- }
- await deps.submitBlockComment(
- decodeURIComponent(blockCommentMatch[1]),
- body.section,
- body.comment,
- );
- sendJson(response, 200, {
- ok: true,
- message: 'Block feedback forwarded.',
- });
- } catch (error) {
- const message =
- error instanceof Error
- ? error.message
- : 'Failed to submit block comment.';
- const status = getSubmissionStatus(error);
- sendJson(response, status, { ok: false, message });
- }
- return;
- }
- // ── Chat: freeform message to agent ─────────────────────────────
- const chatMatch = pathname.match(/^\/api\/interviews\/([^/]+)\/chat$/);
- if (request.method === 'POST' && chatMatch) {
- try {
- const body = (await readJsonBody(request)) as {
- message?: string;
- };
- if (typeof body.message !== 'string' || !body.message.trim()) {
- sendJson(response, 400, {
- error: 'message must be a non-empty string',
- });
- return;
- }
- await deps.submitChat(
- decodeURIComponent(chatMatch[1]),
- body.message.trim(),
- );
- sendJson(response, 200, {
- ok: true,
- message: 'Chat message forwarded to agent.',
- });
- } catch (error) {
- const message =
- error instanceof Error
- ? error.message
- : 'Failed to submit chat message.';
- const status = getSubmissionStatus(error);
- sendJson(response, status, { ok: false, message });
- }
- return;
- }
- // Nudge: ask more questions or confirm complete
- const nudgeMatch = pathname.match(/^\/api\/interviews\/([^/]+)\/nudge$/);
- if (request.method === 'POST' && nudgeMatch) {
- try {
- const body = (await readJsonBody(request)) as {
- action?: string;
- };
- if (
- body.action !== 'more-questions' &&
- body.action !== 'confirm-complete'
- ) {
- sendJson(response, 400, {
- error: 'action must be "more-questions" or "confirm-complete"',
- });
- return;
- }
- await deps.handleNudgeAction(
- decodeURIComponent(nudgeMatch[1]),
- body.action,
- );
- sendJson(response, 200, { ok: true, message: 'Nudge sent.' });
- } catch (error) {
- const message =
- error instanceof Error ? error.message : 'Failed to nudge.';
- const status = message === 'Interview not found' ? 404 : 500;
- sendJson(response, status, { ok: false, message });
- }
- return;
- }
- sendJson(response, 404, { error: 'Not found' });
- }
- async function ensureStarted(): Promise<string> {
- if (baseUrl) {
- return baseUrl;
- }
- if (startPromise) {
- return startPromise;
- }
- startPromise = new Promise((resolve, reject) => {
- const server = createServer((request, response) => {
- handle(request, response).catch((error) => {
- sendJson(response, 500, {
- error:
- error instanceof Error ? error.message : 'Internal server error',
- });
- });
- });
- server.requestTimeout = 30_000;
- server.headersTimeout = 10_000;
- activeServer = server;
- server.on('error', (error: NodeJS.ErrnoException) => {
- server.close();
- activeServer = null;
- startPromise = null;
- if (error.code === 'EADDRINUSE') {
- reject(
- new Error(
- `Interview server port ${deps.port} is already in use. Choose a different port or set port to 0 for an OS-assigned port.`,
- ),
- );
- } else {
- reject(error);
- }
- });
- server.listen(deps.port, '127.0.0.1', () => {
- const address = server.address();
- if (!address || typeof address === 'string') {
- startPromise = null;
- reject(new Error('Failed to start interview server'));
- return;
- }
- baseUrl = `http://127.0.0.1:${address.port}`;
- resolve(baseUrl);
- });
- });
- return startPromise;
- }
- return {
- ensureStarted,
- close: () => {
- if (activeServer) {
- activeServer.closeAllConnections();
- activeServer.close();
- activeServer = null;
- }
- baseUrl = null;
- startPromise = null;
- },
- };
- }
|