Project Overview
Flux is a full-stack AI research workspace designed to help students, researchers, and knowledge workers synthesize information across heterogeneous sources. Users organize their work into isolated workspaces, upload documents or import web and video content, ask grounded questions with inline citations, and generate structured learning artifacts such as summaries, flashcards, quizzes, reports, and interactive mind maps.
Rather than treating AI chat as a stateless wrapper around a single prompt, Flux combines a multi-stage Retrieval-Augmented Generation (RAG) pipeline, durable background job orchestration, cross-session user memory, and a three-panel adaptive workspace interface.
Problem Statement
Working across mixed research materials (PDFs, slide decks, spreadsheets, web articles, and lecture videos) typically forces users to switch between disconnected tools and manually synthesize context. Standard single-query vector search also struggles with several common failure modes:
- Query-document vocabulary mismatch: Short or conversational user questions (e.g., "what are the main insights?") often have low cosine similarity against dense source passages.
- Redundant context windows: Naive top-K vector retrieval frequently returns adjacent, overlapping chunks from the same section of a document, wasting context budget and crowding out diverse evidence.
- Long-running ingestion bottlenecks: Extracting, chunking, and embedding large files synchronously inside HTTP request handlers risks timeouts and leaves partial state behind on failure.
The Solution
Flux addresses these challenges through an asynchronous, workspace-scoped knowledge pipeline:
- Unified Ingestion: Normalizes PDFs, Word documents, PowerPoint decks, Excel spreadsheets, plain text/Markdown, scraped web pages, and timestamped YouTube transcripts into a single
sourceandsource_chunkdata model. - Durable Background Orchestration: Offloads extraction, chunking, embedding, artifact generation, and conversation summarization to step-based Inngest workflows with automatic retries and failure tracking.
- Hybrid Retrieval Optimization: Uses a batched LLM call for query rewriting and Hypothetical Document Embeddings (HyDE), runs dual parallel Pinecone searches, merges results via Reciprocal Rank Fusion (RRF), and deduplicates adjacent chunks before streaming grounded answers.
Key Features
Multi-Format Source Ingestion
Users can populate a workspace from six distinct input channels:
- Document Uploads (up to 50 MB): Parses
.pdf(unpdf),.docx(mammoth, preserving both raw text and HTML preview),.pptx(jszipXML slide/shape parsing),.xlsx(exceljs, capped at 1,000 rows per sheet for preview safety),.txt, and.md. Raw files are stored in Cloudflare R2 with presigned download URLs. - Website Scraping: Extracts clean Markdown and OpenGraph metadata from public URLs via Firecrawl.
- YouTube Transcripts: Fetches timestamped transcripts (
[MM:SS]/[HH:MM:SS]) via Supadata (with async job polling for long videos on cloud IPs) and falls back toyt-caption-kitin local environments without a Supadata key, alongside parallel YouTube oEmbed metadata retrieval. - Direct Text & Markdown: Supports pasting raw notes directly into a workspace.
Grounded Streaming Chat with Inline Citations & Web Search
- User benefit: Answers stay anchored to the user's uploaded materials with verifiable
[1],[2]source citations, while an optional web search toggle ([W1],[W2]) fills gaps outside the workspace. - Technical implementation:
ConversationService.streamWorkspaceChatstreams responses via the Vercel AI SDK (streamText) usinggpt-5.4-miniorgpt-5.4-nano, persists both user messages and partial/complete assistant responses (includingCitationMetadata[]) to PostgreSQL, and optionally attaches a Firecrawl-backedweb_searchtool capped at 3 agent steps (isStepCount(3)).
Automated Learning Artifacts Studio
- User benefit: Converts workspace sources into six study formats on demand: Summary, Key Takeaways, Flashcards, Quiz (with explanations), Mind Map, and AI Report.
- Technical implementation: Triggered asynchronously via Inngest,
generateArtifactContentusesgenerateTextand schema-validatedgenerateObjectcalls over up to 120,000 characters ofREADYworkspace sources. Mind maps are rendered client-side as interactive, depth-styled directed acyclic graphs using React Flow and Dagre (LRlayout).
Cross-Session Memory & Rolling Conversation Summaries
- User benefit: Long conversations remain fast and coherent without losing earlier context, while user preferences and facts persist across sessions.
- Technical implementation: Every 8 persisted messages (
CONVERSATION_SUMMARY_INTERVAL = 8), an Inngest job generates a rolling summary (under 250 words) and extracts user facts into Mem0. Subsequent turns send only the rolling summary plus the most recent 12 messages (RECENT_MESSAGE_WINDOW = 12). Users can also inspect, add, edit, and delete stored memories via a dedicated UI sheet and/api/memoriesendpoints.
Adaptive 3-Panel Workspace & Interactive Landing Demo
- User benefit: Keeps sources, chat, and generated artifacts visible side by side on desktop while adapting cleanly to mobile viewports.
- Technical implementation: Desktop renders resizable left (Sources) and right (Studio) rails backed by a custom
usePanelResizehook withlocalStoragepersistence; mobile switches to a bottom tab bar. The public landing page also includes a deterministic, cursor-driven interactive workspace demo (WorkspaceDemo) with reduced-motion support.
Technology Stack
| Category | Technologies | Purpose in Flux |
|---|---|---|
| Frontend | Next.js 16, React 19, TypeScript, Tailwind CSS v4, Radix UI | App Router SSR/client shell, component primitives, and responsive styling |
| State & Data | TanStack React Query v5 | Client cache management, optimistic source mutations, and conditional 4s polling |
| Visualization | React Flow (@xyflow/react), Dagre, react-markdown, prism-react-renderer | Interactive mind map DAGs, GFM markdown, and syntax-highlighted code blocks |
| AI & RAG | Vercel AI SDK (ai, @ai-sdk/openai), OpenAI API, Pinecone, Mem0 | Streaming chat, structured artifact generation, 512-dim embeddings, vector search, and long-term memory |
| Background Jobs | Inngest (inngest) | Step-based durable execution for source ingestion, artifact generation, and summarization |
| Persistence | PostgreSQL, Drizzle ORM, Cloudflare R2 (@aws-sdk/client-s3) | Relational storage for workspaces/sources/messages and S3-compatible object storage for uploaded files |
| Ingestion Parsers | unpdf, mammoth, jszip, exceljs, Firecrawl, Supadata, yt-caption-kit | Local document parsing, web scraping to Markdown, and YouTube transcript extraction |
| Auth & Security | Better Auth (better-auth), Upstash Redis & Ratelimit, Zod, Pino | Email/password + OAuth sessions with JWT cookie cache, sliding-window rate limits, env/input validation, and structured logging |
| Infrastructure | Docker, Docker Compose, Bun, Node.js 20 | Multi-stage container build and local orchestration for app, PostgreSQL, and Inngest |
System Architecture
Flux follows a modular, layered full-stack architecture inside a single Next.js App Router codebase. HTTP requests flow through authenticated API route handlers into thin controllers, domain services (which enforce workspace ownership), and Drizzle ORM repositories, while heavy AI and ingestion workloads are dispatched to Inngest background functions.
Data Model
The PostgreSQL schema (server/db/schema/) is anchored by workspace, with cascading workspace-scoped entities:
workspace: Owned byuser.id, storestitle,description,icon, anddefaultModel.source&source_chunk: Trackstype(PDF,WEBSITE,YOUTUBE,TEXT,MARKDOWN),status(PENDING,PROCESSING,READY,FAILED), JSONB metadata, extracted text, and ordered chunks (unique(sourceId, index)).conversation&message: Stores rollingsummary,summaryMessageCount,summarizedAt, messagerole(USER,ASSISTANT), and JSONBcitations.learning_artifact: Storestype(SUMMARY,TAKEAWAYS,FLASHCARDS,QUIZ,MINDMAP,REPORT),status,sourceIds, and structured JSONBcontent.
Technical Implementation
1. Multi-Stage RAG Pipeline (Query Enhancement + HyDE + RRF)
Instead of embedding the raw user prompt directly, retrieveWorkspaceContextAdvanced executes a five-stage retrieval pipeline:
- Query Enhancement + HyDE: A single structured LLM call (
gpt-5.4-miniviaOutput.object) rewrites the user's question into a self-contained retrieval query and generates a 2–4 sentence hypothetical passage (hydePassage). - Parallel Dual Embedding: Embeds both strings concurrently using
text-embedding-3-smallat 512 dimensions. - Dual Pinecone Search: Queries Pinecone in parallel (
topK = 12,minScore = 0.2) filtered byworkspaceIdand optionalsourceIds. - Reciprocal Rank Fusion (RRF): Merges both ranked lists using
1 / (60 + rank + 1). - Adjacent-Chunk Deduplication: Greedily keeps only the highest-scored chunk per
(sourceId, Math.floor(chunkIndex / 2))bucket and trims to the top 8 chunks.
// lib/ai/rag.ts
function rrfFuse(rankedLists: string[][], k = 60): Map<string, number> {
const scores = new Map<string, number>();
for (const list of rankedLists) {
list.forEach((id, rank) => {
const contribution = 1 / (k + rank + 1);
scores.set(id, (scores.get(id) ?? 0) + contribution);
});
}
return scores;
}
2. Durable Source Ingestion & Maintenance Scripts
Source processing runs as a multi-step Inngest function (process-source, 3 retries) with discrete memoized steps (mark-processing, extract-content, chunk-content, embed-and-index).
- Chunking uses a recursive separator strategy (
["\n\n", "\n", ". ", " ", ""]) targeting 1,000 characters with 100-character overlap, or page-preservingchunkPageswhen page arrays are present. - Embeddings are generated in batches of 50 (clamped to 24,000 characters per chunk) and upserted to Pinecone in batches of 100.
- Chunk text is stored directly in Pinecone metadata (
text.slice(0, 35000)) to avoid PostgreSQL joins during retrieval, while full source text remains in PostgreSQL for artifact generation and re-indexing (scripts/reindex.ts).
3. Resilient Streaming Chat & Partial Persistence
ConversationService.streamWorkspaceChat wraps streamText in a custom ReadableStream that accumulates streamed tokens and persists the assistant message, along with pre-computed CitationMetadata[], once the stream completes. If the client aborts mid-stream, the catch block attempts to persist any partial assistant response accumulated so far so conversation history is not lost.
Engineering Decisions
| Decision | Rationale | Trade-offs |
|---|---|---|
512-dim text-embedding-3-small embeddings | Reduces Pinecone vector storage and query latency while maintaining semantic quality; RAG_MIN_SCORE is tuned to 0.2 for broad thematic queries. | Slightly lower fine-grained recall compared to 1536-dim or text-embedding-3-large embeddings. |
| Denormalized chunk text in Pinecone metadata | Eliminates database round-trips/joins during RAG retrieval. | Duplicates chunk text between PostgreSQL and Pinecone, requiring synchronized cleanup on delete (removeSourceFromIndex) and a reindex.ts script. |
| Local async fallback for source ingestion | If inngest.send fails (e.g., local dev without Inngest running), SourceService.enqueueSourceProcessing falls back to an in-process async processSourcePipeline call. | Ensures sources still process in degraded environments, though without Inngest's cross-restart durability. |
| Dual-provider YouTube transcript strategy | Uses Supadata in cloud/Vercel deployments where direct YouTube scraping is blocked, and falls back to yt-caption-kit locally when SUPADATA_API_KEY is unset. | Requires managing two transcript response formats (millisecond vs. second offsets) and polling Supadata jobs for long videos. |
| Conditional Redis rate limiting with in-memory fallback | Uses Upstash Redis sliding-window rate limiting in distributed environments and falls back to a local Map with 5-minute pruning when Redis credentials are omitted. | Simplifies local setup, though the in-memory fallback is per-instance and not shared across serverless workers. |
Technical Challenges & Solutions
1. Preventing Context Redundancy in Chunked Retrieval
- Challenge: Standard vector search often returns multiple consecutive chunks from the same paragraph or page, reducing topical diversity in the LLM's context window.
- Approach:
deduplicateChunksgroups chunks by${sourceId}:${Math.floor(chunkIndex / 2)}after RRF scoring and greedily retains only the highest-ranked representative per adjacent pair. - Outcome: Surfaces broader coverage across workspace sources within the 8-chunk budget.
2. Cloud-Reliable YouTube Transcript Ingestion
- Challenge: Direct YouTube caption scraping libraries frequently fail from cloud/datacenter IPs (such as Vercel), and long videos can exceed synchronous API response limits.
- Approach:
getYoutubeTranscriptroutes requests through Supadata whenSUPADATA_API_KEYis configured (pollinggetJobStatusup to 10 times at 3-second intervals when ajobIdis returned), while running oEmbed metadata fetching in parallel. - Outcome: Reliable transcript ingestion across both local development and cloud deployments without blocking metadata resolution.
3. Optimistic UI vs. Background Polling Race Conditions
- Challenge: Immediately polling
GET /api/sourceswhile an import mutation is still in flight can overwrite optimistic source placeholders in React Query's cache. - Approach:
useSourceschecksuseIsMutating()and pauses its 4-secondrefetchIntervalwhile mutations are active, then swaps the temporaryoptimistic-*item with the server-returned record inonSuccess. - Outcome: Smooth optimistic feedback during uploads and automatic status transitions from
PENDINGtoREADYonce background jobs finish.
User Experience & Design
- Adaptive Layout: Desktop features collapsible, drag-resizable left and right rails (
SidebarSources,SidebarArtifacts) with collapsed icon rails; mobile (belowmd) transitions to a bottom tab bar. - Loading, Empty & Error States: Dedicated skeleton loaders (
DashboardContentSkeleton,WorkspaceViewSkeleton,ChatSkeleton), empty-state prompts guiding users to upload their first source, and toast notifications via Sonner. - Rich Content Rendering: Assistant messages and prose artifacts render GitHub-Flavored Markdown with syntax-highlighted code blocks (
prism-react-renderer). Mind maps dynamically importMindmapFlowwithssr: falseand a spinner fallback, and support node selection/dimming to focus on connected branches. - Theming & Typography: Light and dark themes via
next-themes, pairingSchibsted Groteskheadings,Interbody text, andGeist Monometadata/code.
Performance, Security & Reliability
- Authentication & Route Protection: Better Auth manages email/password and optional GitHub/Google OAuth sessions with JWT cookie caching.
proxy.tsredirects unauthenticated users away from/dashboardand/workspace, while every API controller callsgetAuthenticatedUserand services verify workspace ownership (WorkspaceService.getWorkspaceById). - Input & Environment Validation: All API payloads and query parameters are validated with Zod (
safeParse+ structured field errors viagetZodFieldErrors), file uploads are capped at 50 MB and restricted to six extensions, andlib/env.tsvalidates required secrets (including a 32+ characterBETTER_AUTH_SECRET) at startup. - Rate Limiting: Chat streaming and all source import endpoints enforce a 15-requests-per-minute sliding window per user (
checkRateLimit). - Error Handling & Observability:
asyncHandlernormalizes thrownApiErrorand unexpected errors into consistent JSON responses,sanitizeExternalErrorhides raw external service errors inproduction, and Pino provides structured module-scoped logging. - Containerization: Multi-stage
Dockerfilebuilds a standalone Next.js bundle with Bun and runs as an unprivilegednextjsuser on Node 20 Alpine with a/-routeHEALTHCHECK.
Results & Impact
Flux demonstrates a complete end-to-end AI research platform with:
- 6 supported ingestion formats/channels (
.pdf,.docx,.pptx,.xlsx,.txt/.md, websites, YouTube videos, and raw text). - 6 structured learning artifact types generated asynchronously and rendered with specialized interactive viewers.
- 5-stage RAG retrieval pipeline combining query rewriting, HyDE, dual vector search, RRF fusion, and adjacent-chunk deduplication.
- Containerized 3-service local stack (
app,postgres:16-alpine,inngest) ready for reproducible deployment.
Learnings & Skills Demonstrated
- Full-Stack TypeScript Architecture: Designing clean controller → service → repository boundaries in Next.js App Router with end-to-end Zod validation and Drizzle ORM.
- Applied Information Retrieval (RAG): Implementing HyDE, Reciprocal Rank Fusion, metadata filtering, and chunk deduplication to improve retrieval quality over naive vector search.
- Distributed & Durable Workflows: Decoupling slow document parsing, embedding, and LLM generation from HTTP request lifecycles using Inngest step functions.
- Real-Time & Optimistic Frontend Engineering: Coordinating
ReadableStreamAI responses, abort handling, React Query cache synchronization, and interactive React Flow visualizations.
Future Improvements
- Automated Test Suite: Add unit tests for
chunker.ts,rrfFuse,deduplicateChunks, and API validators, plus integration tests for workspace access control and RAG retrieval. - Artifact Generation Fallback & Streaming: Mirror
SourceService's local fallback inLearningArtifactServicewhen Inngest is unavailable, and consider streaming artifact generation progress. - Token-Accurate Chunking: Replace the
Math.ceil(length / 4)character-length approximation inchunkSourceContentwith a tokenizer (e.g.,tiktoken) for tighter context-window budgeting. - Multi-Conversation Switching UI: Expose full conversation switching/history management in the workspace UI if users create multiple threads per workspace.