Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 7
Implement Clerk↔Supabase Auth, Chat CRUD, Document RAG, and Real-Time Collaboration#730
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
ngoiyaeric
merged 3 commits into
main
from
feat/clerk-supabase-rag-realtime-13454999576171299600Jul 11, 2026
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -6,7 +6,8 @@ import { | ||
| getAIState, | ||
| getMutableAIState | ||
| } from 'ai/rsc' | ||
| import { CoreMessage, ToolResultPart, TextPart, ImagePart } from 'ai' | ||
| import { CoreMessage, ToolResultPart, TextPart, ImagePart, embedMany } from 'ai' | ||
| import { openai } from '@ai-sdk/openai' | ||
| import { nanoid } from '@/lib/utils' | ||
| import type { FeatureCollection } from 'geojson' | ||
| import { Spinner } from '@/components/ui/spinner' | ||
| @@ -29,12 +30,26 @@ import RetrieveSection from '@/components/retrieve-section' | ||
| import { VideoSearchSection } from '@/components/video-search-section' | ||
| import { MapQueryHandler } from '@/components/map/map-query-handler' | ||
| import { getCurrentUserIdOnServer } from '@/lib/auth/get-current-user' | ||
| import { createClient } from '@/lib/supabase/client' | ||
| import { db } from '@/lib/db' | ||
| import { documents, documentChunks } from '@/lib/db/schema' | ||
| import { eq } from 'drizzle-orm' | ||
| // Define the type for related queries | ||
| type RelatedQueries = { | ||
| items: { query: string }[] | ||
| } | ||
| function chunkText(text: string, chunkSize = 800, overlap = 100): string[] { | ||
| const chunks: string[] = [] | ||
| let i = 0 | ||
| while (i < text.length) { | ||
| chunks.push(text.slice(i, i + chunkSize)) | ||
| i += chunkSize - overlap | ||
| } | ||
| return chunks | ||
| } | ||
| async function submit(formData?: FormData, skip?: boolean) { | ||
| 'use server' | ||
| @@ -325,6 +340,97 @@ async function submit(formData?: FormData, skip?: boolean) { | ||
| } | ||
| const userId = await getCurrentUserIdOnServer() | ||
| // Handle document attachment if uploaded via browser client to Storage | ||
| const documentStoragePath = formData?.get('documentStoragePath') as string | ||
| const documentMime = formData?.get('documentMime') as string | ||
| const documentName = formData?.get('documentName') as string | ||
| if (documentStoragePath && userId) { | ||
| let docId: string | null = null | ||
| try { | ||
| const supabase = createClient() | ||
| // First, create the document row | ||
| const [docRow] = await db.insert(documents).values({ | ||
| userId: userId, | ||
| chatId: aiState.get().chatId, | ||
| storagePath: documentStoragePath, | ||
| mime: documentMime, | ||
| status: 'processing' | ||
| }).returning({ id: documents.id }) | ||
| docId = docRow.id | ||
| const { data: fileData, error: downloadError } = await supabase.storage | ||
| .from('chat-attachments') | ||
| .download(documentStoragePath) | ||
| if (downloadError) { | ||
| throw downloadError | ||
| } | ||
| if (!fileData) { | ||
| throw new Error('Downloaded file data is null') | ||
| } | ||
| // Validate the actual file: trust the downloaded content over the submitted MIME | ||
| const buffer = await fileData.arrayBuffer() | ||
| const byteLength = buffer.byteLength | ||
| // Reject oversized files (max 5 MB) | ||
| const MAX_FILE_SIZE = 5 * 1024 * 1024 | ||
| if (byteLength > MAX_FILE_SIZE) { | ||
| throw new Error(`File too large: ${byteLength} bytes exceeds ${MAX_FILE_SIZE} byte limit`) | ||
| } | ||
| // Validate MIME type against allowed types | ||
| const ALLOWED_MIMES = ['text/plain', 'text/markdown', 'application/pdf', 'text/csv', 'application/json'] | ||
| const actualMime = fileData.type || documentMime || '' | ||
| if (!ALLOWED_MIMES.includes(actualMime)) { | ||
| throw new Error(`Unsupported MIME type: ${actualMime}`) | ||
| } | ||
| const text = await fileData.text() | ||
| const chunks = chunkText(text) | ||
| // Cap chunks to prevent runaway embedding costs (max 50 chunks) | ||
| const MAX_CHUNKS = 50 | ||
| const cappedChunks = chunks.slice(0, MAX_CHUNKS) | ||
| if (cappedChunks.length > 0) { | ||
| const { embeddings } = await embedMany({ | ||
| model: openai.embedding('text-embedding-ada-002'), | ||
| values: cappedChunks, | ||
| }) | ||
coderabbitai[bot] marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| const chunkRows = cappedChunks.map((chunk, idx) => ({ | ||
| documentId: docRow.id, | ||
| chunkText: chunk, | ||
| embedding: embeddings[idx] | ||
| })) | ||
| await db.insert(documentChunks).values(chunkRows) | ||
| } | ||
| await db.update(documents) | ||
| .set({ status: 'complete' }) | ||
| .where(eq(documents.id, docRow.id)) | ||
| } catch (err) { | ||
| console.error('[Document Ingestion] Failed to ingest document:', err) | ||
| // Update the existing row to error status instead of inserting a duplicate | ||
| if (docId) { | ||
| try { | ||
| await db.update(documents) | ||
| .set({ status: 'error' }) | ||
| .where(eq(documents.id, docId)) | ||
| } catch (e) { | ||
| console.error('[Document Ingestion] Failed to update document to error status:', e) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| const currentSystemPrompt = userId ? await getSystemPrompt(userId) : null | ||
| const maxMessages = 10 | ||
| const messages = aiState.get().messages.map(message => ({ | ||
| @@ -722,6 +828,22 @@ export const getUIStateFromAIState = (aiState: AIState): UIState => { | ||
| ), | ||
| isCollapsed: isCollapsed.value | ||
| } | ||
| case 'documentRetrieve': { | ||
| const adaptedResults = { | ||
| results: toolOutput.map((r: any) => ({ | ||
| title: `Document Match (Similarity: ${(r.similarity * 100).toFixed(1)}%)`, | ||
| content: r.chunkText, | ||
| url: '' | ||
| })), | ||
| query: '', | ||
| images: [] | ||
| } | ||
| return { | ||
| id, | ||
| component: <RetrieveSection data={adaptedResults} />, | ||
| isCollapsed: isCollapsed.value | ||
| } | ||
| } | ||
| default: | ||
| console.warn( | ||
| `Unhandled tool result in getUIStateFromAIState: ${name}` | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| import { NextResponse, NextRequest } from 'next/server'; | ||
| import { addParticipant, removeParticipant, listParticipants } from '@/lib/actions/chat'; | ||
| import { getCurrentUserIdOnServer } from '@/lib/auth/get-current-user'; | ||
| export async function GET( | ||
| request: NextRequest, | ||
| { params }: { params: Promise<{ id: string }> } | ||
| ) { | ||
| try { | ||
| const userId = await getCurrentUserIdOnServer(); | ||
| if (!userId) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); | ||
| } | ||
| const { id: chatId } = await params; | ||
| const result = await listParticipants(chatId); | ||
| if (result === null) { | ||
| // Access denied — user is not authorized to view this chat | ||
| return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); | ||
| } | ||
| // result is an empty array means authorized but no collaborators | ||
| return NextResponse.json({ participants: result }, { status: 200 }); | ||
| } catch (error) { | ||
| console.error('Error listing participants via API:', error); | ||
| return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); | ||
| } | ||
| } | ||
| export async function POST( | ||
| request: NextRequest, | ||
| { params }: { params: Promise<{ id: string }> } | ||
| ) { | ||
| try { | ||
| const userId = await getCurrentUserIdOnServer(); | ||
| if (!userId) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); | ||
| } | ||
| const { id: chatId } = await params; | ||
| const { emailOrClerkId } = await request.json(); | ||
| if (!emailOrClerkId) { | ||
| return NextResponse.json({ error: 'Missing emailOrClerkId' }, { status: 400 }); | ||
| } | ||
| // Ignore untrusted role from request — always use 'collaborator' | ||
| const success = await addParticipant(chatId, emailOrClerkId, 'collaborator'); | ||
| if (success) { | ||
| return NextResponse.json({ message: 'Participant added successfully' }, { status: 200 }); | ||
| } else { | ||
| return NextResponse.json({ error: 'Failed to add participant (user not found or unauthorized)' }, { status: 404 }); | ||
| } | ||
| } catch (error) { | ||
| console.error('Error adding participant via API:', error); | ||
| return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); | ||
| } | ||
| } | ||
| export async function DELETE( | ||
| request: NextRequest, | ||
| { params }: { params: Promise<{ id: string }> } | ||
| ) { | ||
| try { | ||
| const userId = await getCurrentUserIdOnServer(); | ||
| if (!userId) { | ||
| return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); | ||
| } | ||
| const { id: chatId } = await params; | ||
| const { targetUserId } = await request.json(); | ||
| if (!targetUserId) { | ||
| return NextResponse.json({ error: 'Missing targetUserId' }, { status: 400 }); | ||
| } | ||
| const success = await removeParticipant(chatId, targetUserId); | ||
| if (success) { | ||
| return NextResponse.json({ message: 'Participant removed successfully' }, { status: 200 }); | ||
| } else { | ||
| return NextResponse.json({ error: 'Failed to remove participant or unauthorized' }, { status: 404 }); | ||
| } | ||
| } catch (error) { | ||
| console.error('Error removing participant via API:', error); | ||
| return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); | ||
| } | ||
| } |
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Do not document consistency guarantees that
saveChatdoes not provide.The implementation trusts
msg.userId, replaces duplicate IDs with random UUIDs, and performs an unrestricted conflict update by message ID. That permits misattribution, repeated-save duplication, and unrelated message overwrites rather than deterministic deduplication. Revise this section after fixing the persistence path.🧰 Tools
🪛 LanguageTool
[style] ~171-~171: ‘exact same’ might be wordy. Consider a shorter alternative.
Context: ...abase Realtime subscriptions follow the exact same RLS policies deployed in QCX-BACKEND. B...
(EN_WORDINESS_PREMIUM_EXACT_SAME)
🤖 Prompt for AI Agents