Files
Momento/memento-note/app/api/brainstorm/[sessionId]/route.ts
Antigravity 1fcea6ed7d
All checks were successful
Deploy to Production / Build and Deploy (push) Successful in 7s
feat: brainstorm sessions, PDF document Q&A, embedding fixes, and UI improvements
- Add brainstorm feature with collaborative canvas, AI idea generation, live cursors, playback, and export
- Add PDF upload/extraction/ingestion pipeline with pgvector document search (RAG)
- Add document Q&A overlay with streaming chat and PDF preview
- Add note attachments UI with status polling, grid layout, and auto-scroll
- Add task extraction AI tool and agent executor improvements
- Fix NoteEmbedding missing updatedAt column, re-index 66 notes with 1536-dim embeddings
- Fix brainstorm 'Create Note' button: add success toast and redirect to created note
- Fix memory echo notification infinite polling
- Fix chat route to always include document_search tool
- Add brainstorm i18n keys across all 14 locales
- Add socket server for real-time brainstorm collaboration
- Add hierarchical notebook selector and organize notebook dialog improvements
- Add sidebar brainstorm section with session management
- Update prisma schema with brainstorm tables, attachments, and document chunks
2026-05-14 17:43:21 +00:00

216 lines
6.4 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { auth } from '@/auth'
function resolveAccessRole(
brainstormSession: any,
userId: string | null
): 'owner' | 'editor' | 'viewer' | 'guest' | 'none' {
if (!userId) {
return brainstormSession.isPublic ? 'guest' : 'none'
}
if (brainstormSession.userId === userId) return 'owner'
const participant = brainstormSession.participants?.find(
(p: any) => p.userId === userId
)
if (participant) return participant.role
const acceptedShare = brainstormSession.shares?.find(
(s: any) => s.userId === userId && s.status === 'accepted'
)
if (acceptedShare) return acceptedShare.permission
return brainstormSession.isPublic ? 'guest' : 'none'
}
function filterNoteRefsByRole(ideas: any[], role: string): any[] {
const allowedVis = role === 'owner'
? ['public', 'participants', 'owner_only']
: role === 'editor'
? ['public', 'participants', 'owner_only']
: role === 'viewer'
? ['public', 'participants']
: ['public']
return ideas.map((idea: any) => ({
...idea,
noteRefs: (idea.noteRefs || []).filter(
(ref: any) => allowedVis.includes(ref.visibility || 'participants')
),
}))
}
function sanitizeForGuest(session: any): any {
const { participants, shares, ...rest } = session
const filteredIdeas = filterNoteRefsByRole(rest.ideas || [], 'guest')
return {
...rest,
ideas: filteredIdeas,
sourceNote: null,
exportedNote: null,
}
}
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ sessionId: string }> }
) {
const authSession = await auth()
const userId = authSession?.user?.id || null
try {
const { sessionId } = await params
const brainstormSession = await prisma.brainstormSession.findFirst({
where: { id: sessionId },
include: {
ideas: {
orderBy: [{ waveNumber: 'asc' }, { createdAt: 'asc' }],
include: {
noteRefs: {
include: {
note: { select: { id: true, title: true } },
},
},
},
},
sourceNote: {
select: { id: true, title: true },
},
exportedNote: {
select: { id: true, title: true },
},
participants: {
where: userId ? { userId } : undefined,
select: { userId: true, role: true },
},
shares: userId
? {
where: { userId, status: 'accepted' },
select: { userId: true, permission: true },
}
: false,
},
})
if (!brainstormSession) {
return NextResponse.json({ error: 'Not found' }, { status: 404 })
}
const creatorIds = [...new Set(brainstormSession.ideas.map((i: any) => i.createdBy).filter(Boolean))]
const creators = creatorIds.length > 0
? await prisma.user.findMany({ where: { id: { in: creatorIds } }, select: { id: true, name: true, image: true } })
: []
const creatorMap = new Map(creators.map((c: any) => [c.id, c]))
for (const idea of brainstormSession.ideas) {
(idea as any).creator = (idea as any).createdBy ? creatorMap.get((idea as any).createdBy) || null : null
}
const role = resolveAccessRole(brainstormSession, userId)
if (role === 'none') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
let responseData: any = brainstormSession
if (role === 'guest') {
responseData = sanitizeForGuest(brainstormSession)
} else if (role === 'viewer') {
const { participants: _p, shares: _s, ...rest } = brainstormSession as any
responseData = {
...rest,
ideas: filterNoteRefsByRole(rest.ideas || [], 'viewer'),
}
} else {
const { participants: _p, shares: _s, ...rest } = brainstormSession as any
responseData = rest
}
return NextResponse.json({
success: true,
data: responseData,
_meta: { role, canEdit: ['owner', 'editor'].includes(role) || (role === 'guest' && brainstormSession.guestCanEdit) },
})
} catch (error) {
console.error('Error fetching brainstorm session:', error)
return NextResponse.json(
{ error: 'Failed to fetch session' },
{ status: 500 }
)
}
}
export async function PATCH(
request: NextRequest,
{ params }: { params: Promise<{ sessionId: string }> }
) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const { sessionId } = await params
const body = await request.json()
const brainstormSession = await prisma.brainstormSession.findFirst({
where: { id: sessionId, userId: session.user.id },
})
if (!brainstormSession) {
return NextResponse.json({ error: 'Not found' }, { status: 404 })
}
const updates: Record<string, any> = {}
if (typeof body.isPublic === 'boolean') updates.isPublic = body.isPublic
if (typeof body.guestCanEdit === 'boolean') updates.guestCanEdit = body.guestCanEdit
if (Object.keys(updates).length === 0) {
return NextResponse.json({ error: 'No valid fields to update' }, { status: 400 })
}
const updated = await prisma.brainstormSession.update({
where: { id: sessionId },
data: updates,
})
return NextResponse.json({ success: true, data: updated })
} catch (error) {
console.error('Error updating brainstorm session:', error)
return NextResponse.json(
{ error: 'Failed to update session' },
{ status: 500 }
)
}
}
export async function DELETE(
request: NextRequest,
{ params }: { params: Promise<{ sessionId: string }> }
) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
try {
const { sessionId } = await params
const brainstormSession = await prisma.brainstormSession.findFirst({
where: { id: sessionId, userId: session.user.id },
})
if (!brainstormSession) {
return NextResponse.json({ error: 'Not found' }, { status: 404 })
}
await prisma.brainstormSession.delete({
where: { id: sessionId },
})
return NextResponse.json({ success: true })
} catch (error) {
console.error('Error deleting brainstorm session:', error)
return NextResponse.json(
{ error: 'Failed to delete session' },
{ status: 500 }
)
}
}