(req: Request)
| 9 | }) |
| 10 | |
| 11 | export async function POST(req: Request) { |
| 12 | const langfuse = getLangfuseClient() |
| 13 | if (!langfuse) { |
| 14 | return Response.json({ success: true, logged: false }) |
| 15 | } |
| 16 | |
| 17 | // Validate input |
| 18 | let data |
| 19 | try { |
| 20 | data = saveSchema.parse(await req.json()) |
| 21 | } catch { |
| 22 | return Response.json( |
| 23 | { success: false, error: "Invalid input" }, |
| 24 | { status: 400 }, |
| 25 | ) |
| 26 | } |
| 27 | |
| 28 | const { filename, format, sessionId } = data |
| 29 | |
| 30 | try { |
| 31 | const timestamp = new Date().toISOString() |
| 32 | |
| 33 | // Find the most recent chat trace for this session to attach the save flag |
| 34 | const tracesResponse = await langfuse.api.trace.list({ |
| 35 | sessionId, |
| 36 | limit: 1, |
| 37 | }) |
| 38 | |
| 39 | const traces = tracesResponse.data || [] |
| 40 | const latestTrace = traces[0] |
| 41 | |
| 42 | if (latestTrace) { |
| 43 | // Add a score to the existing trace to flag that user saved |
| 44 | await langfuse.api.ingestion.batch({ |
| 45 | batch: [ |
| 46 | { |
| 47 | type: "score-create", |
| 48 | id: randomUUID(), |
| 49 | timestamp, |
| 50 | body: { |
| 51 | id: randomUUID(), |
| 52 | traceId: latestTrace.id, |
| 53 | name: "diagram-saved", |
| 54 | value: 1, |
| 55 | comment: `User saved diagram as ${filename}.${format}`, |
| 56 | }, |
| 57 | }, |
| 58 | ], |
| 59 | }) |
| 60 | } |
| 61 | // If no trace found, skip logging (user hasn't chatted yet) |
| 62 | |
| 63 | return Response.json({ success: true, logged: !!latestTrace }) |
| 64 | } catch (error) { |
| 65 | console.error("Langfuse save error:", error) |
| 66 | return Response.json( |
| 67 | { success: false, error: "Failed to log save" }, |
| 68 | { status: 500 }, |
nothing calls this directly
no test coverage detected