(req: Request)
| 156 | |
| 157 | // Inner handler function |
| 158 | async function handleChatRequest(req: Request): Promise<Response> { |
| 159 | // Check for access code |
| 160 | const accessCodes = |
| 161 | process.env.ACCESS_CODE_LIST?.split(",") |
| 162 | .map((code) => code.trim()) |
| 163 | .filter(Boolean) || [] |
| 164 | if (accessCodes.length > 0) { |
| 165 | const accessCodeHeader = req.headers.get("x-access-code") |
| 166 | if (!accessCodeHeader || !accessCodes.includes(accessCodeHeader)) { |
| 167 | return Response.json( |
| 168 | { |
| 169 | error: "Invalid or missing access code. Please configure it in Settings.", |
| 170 | }, |
| 171 | { status: 401 }, |
| 172 | ) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | const { messages, xml, previousXml, sessionId } = await req.json() |
| 177 | |
| 178 | // Get user IP for Langfuse tracking |
| 179 | const forwardedFor = req.headers.get("x-forwarded-for") |
| 180 | const userId = forwardedFor?.split(",")[0]?.trim() || "anonymous" |
| 181 | |
| 182 | // Validate sessionId for Langfuse (must be string, max 200 chars) |
| 183 | const validSessionId = |
| 184 | sessionId && typeof sessionId === "string" && sessionId.length <= 200 |
| 185 | ? sessionId |
| 186 | : undefined |
| 187 | |
| 188 | // Extract user input text for Langfuse trace |
| 189 | const currentMessage = messages[messages.length - 1] |
| 190 | const userInputText = |
| 191 | currentMessage?.parts?.find((p: any) => p.type === "text")?.text || "" |
| 192 | |
| 193 | // Update Langfuse trace with input, session, and user |
| 194 | setTraceInput({ |
| 195 | input: userInputText, |
| 196 | sessionId: validSessionId, |
| 197 | userId: userId, |
| 198 | }) |
| 199 | |
| 200 | // === FILE VALIDATION START === |
| 201 | const fileValidation = validateFileParts(messages) |
| 202 | if (!fileValidation.valid) { |
| 203 | return Response.json({ error: fileValidation.error }, { status: 400 }) |
| 204 | } |
| 205 | // === FILE VALIDATION END === |
| 206 | |
| 207 | // === CACHE CHECK START === |
| 208 | const isFirstMessage = messages.length === 1 |
| 209 | const isEmptyDiagram = !xml || xml.trim() === "" || isMinimalDiagram(xml) |
| 210 | |
| 211 | if (isFirstMessage && isEmptyDiagram) { |
| 212 | const lastMessage = messages[0] |
| 213 | const textPart = lastMessage.parts?.find((p: any) => p.type === "text") |
| 214 | const filePart = lastMessage.parts?.find((p: any) => p.type === "file") |
| 215 |
no test coverage detected