mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-05-15 18:25:18 +02:00
feat: initialize agent and claude skill libraries with comprehensive knowledge bases, workflow templates, and implementation artifacts.
This commit is contained in:
parent
956d8c6322
commit
b35b4337bb
2028 changed files with 565614 additions and 0 deletions
36
docs/api-contracts.md
Normal file
36
docs/api-contracts.md
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
# SurfSense API Contracts
|
||||
|
||||
## Tổng quan
|
||||
SurfSense Backend cấu trúc hệ thống APIs thành các Routers chuẩn RESTful (thư mục `api/routes`). Toàn bộ API đều trả về type hints giúp FastAPI tự động serialize Pydantic ra Swagger UI và các Frontend Generator có thể tiêu thụ.
|
||||
|
||||
## 1. Nhóm API Quản Trị Hệ Thống / Tài Khoản
|
||||
- **`auth_routes.py`**: Quản lý OAuth/Login, Tokens, Session Refresh.
|
||||
- **`rbac_routes.py`**: Role-based Access Control API, lấy quyền truy cập Workspace/Search Spaces.
|
||||
- **`stripe_routes.py`**: Webhooks và API phục vụ payment/subscriptions nếu có.
|
||||
- **`logs_routes.py`**, **`notifications_routes.py`**: Đẩy Log errors, gửi các Notifications system.
|
||||
|
||||
## 2. Nhóm API Core Search & AI
|
||||
- **`search_spaces_routes.py`**: Tạo, cập nhật, xóa các Knowledge Bases cô lập.
|
||||
- **`new_chat_routes.py`**, **`public_chat_routes.py`**: Mọi call Stream SSE/WebSocket cho tin nhắn từ AI Agent, cũng như query dữ liệu Chat Threads cũ.
|
||||
- **`search_source_connectors_routes.py`**: Trung tâm điều hướng cấu hình các External Syncs. Thường làm việc chung với Backend Workers.
|
||||
|
||||
## 3. Nhóm Connectors Bên Thứ 3
|
||||
Các Connectors này định nghĩa quá trình OAuth Consent hoặc Add Webhooks để cào dữ liệu:
|
||||
- **`google_drive_add_connector_route.py`**
|
||||
- **`slack_add_connector_route.py`**
|
||||
- **`notion_add_connector_route.py`**
|
||||
- **`confluence_add_connector_route.py`**, **`jira_add_connector_route.py`**
|
||||
- **`discord_add_connector_route.py`**
|
||||
*(Và khoảng 10 nền tảng khác).*
|
||||
|
||||
## 4. Nhóm AI Outputs Đa Phương Tiện
|
||||
Mở rộng LLM capabilities beyond text:
|
||||
- **`image_generation_routes.py`**: Sinh hình ảnh từ context.
|
||||
- **`vision_llm_routes.py`**: Parse hình ảnh thành Text (OCR hoặc Context).
|
||||
- **`podcasts_routes.py`**: Sinh Audio / Deep Dive từ documents.
|
||||
- **`video_presentations_routes.py`**: Tạo video tổng hợp.
|
||||
- **`reports_routes.py`**, **`export_routes.py`**: Chuyển đổi Chat Output thành format Markdown, PDF.
|
||||
|
||||
## Quy Chuẩn Tương Tác
|
||||
- Backend sử dụng chuẩn Pydantic Models (nằm ở `surfsense_backend/app/schemas/`) rải đều qua response `response_model=...`.
|
||||
- Client gọi thông qua tanstack-query được define trong `surfsense_web/api/`. Riêng đối với dữ liệu Realtime, Client hoàn toàn bypass API POST/GET truyền thống mà dùng `@rocicorp/zero` để mutate trực tiếp vào Schema.
|
||||
63
docs/architecture-backend.md
Normal file
63
docs/architecture-backend.md
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
# Kiến Trúc Hệ Thống: Backend (`surfsense_backend`)
|
||||
|
||||
## 1. Tổng Quan
|
||||
Backend của SurfSense (viết bằng Python 3.12) chịu trách nhiệm chính trong việc xử lý Data Ingestion, Indexing, LLM Orchestration và cung cấp REST APIs cho các Client.
|
||||
|
||||
## 2. Công Nghệ Cốt Lõi
|
||||
- **Môi trường Server**: FastAPI, Uvicorn
|
||||
- **Database & ORM**: PostgreSQL, SQLAlchemy, Alembic (Migration), pgvector (Vector DB)
|
||||
- **Task Queue & Background Jobs**: Celery, Redis
|
||||
- **AI / LLM Framework**: LangChain, LangGraph, LiteLLM
|
||||
- **Xử lý Dữ liệu**: Unstructured, Docling, Playwright
|
||||
|
||||
## 3. Cấu Trúc Mã Nguồn (Directory Structure)
|
||||
```text
|
||||
surfsense_backend/app/
|
||||
├── agents/ # Định nghĩa LangGraph agents / chains để xử lý luồng AI
|
||||
├── api/routes/ # Chứa các endpoint API (users, chat, documents...)
|
||||
├── connectors/ # Logic kết nối bên thứ 3 (Google Drive, Slack, Composio)
|
||||
├── db.py # Điểm khai báo Core Models của SQLAlchemy
|
||||
├── etl_pipeline/ # Pipeline trích xuất dữ liệu, chunking text, transform
|
||||
├── indexing_pipeline/ # Chịu trách nhiệm tạo embedding và push vào VectorDB
|
||||
├── prompts/ # Template lưu trữ prompt chuẩn cho các luồng LLM
|
||||
├── schemas/ # Pydantic models (validation cho request/response)
|
||||
├── services/ # Tầng Business Logic (CRUD, gọi API ngoài)
|
||||
├── tasks/ # Các Celery task (Background jobs xử lý nặng)
|
||||
└── utils/ # Các hàm tiện ích (helper functions, formats, parsing)
|
||||
```
|
||||
|
||||
## 4. Pipeline Architecture & Search (Deep Dive)
|
||||
|
||||
### 4.1 ETL Pipeline (`etl_pipeline/`)
|
||||
Chịu trách nhiệm trích xuất văn bản từ nhiều định dạng file khác nhau.
|
||||
- **Entry point**: `EtlPipelineService.extract()` phân loại file (`classify_file`) thành các nhóm (PLAINTEXT, DIRECT_CONVERT, AUDIO, IMAGE, DOCUMENT).
|
||||
- **Parsers Tích Hợp**:
|
||||
- `docling`: Xử lý PDF/tài liệu phức tạp (via `parse_with_docling`).
|
||||
- `unstructured`: Parser thay thế cho tài liệu chung.
|
||||
- `llamacloud` / `Azure Document Intelligence`: Dùng làm internal accelerator để tối ưu chi phí/tốc độ.
|
||||
- `vision_llm`: Fallback parse ảnh nếu model Vision có sẵn.
|
||||
- `audio`: Dùng model transcribe.
|
||||
|
||||
### 4.2 Indexing Pipeline (`indexing_pipeline/`)
|
||||
Chịu trách nhiệm chunking, tính toán embedding, chống trùng lặp và lưu trữ vào Vector DB.
|
||||
- **State Feedback Tức Thì**: `create_placeholder_documents()` tạo ra các Document "Pending" vào DB ngay khi upload, giúp đồng bộ Zero Sync hiển thị UI lập tức.
|
||||
- **Deduplication**: Dựa vào `compute_content_hash` và `compute_unique_identifier_hash` để chống duplicate khi document đã tồn tại và không đổi.
|
||||
- **Chunking & Embedding**: Chạy bất đồng bộ (`asyncio.to_thread`) với hàm `chunk_text()` (có hỗ trợ riêng cho code chunking) và `embed_texts()` (chạy qua LiteLLM/OpenAI).
|
||||
- **Concurrency Control**: Hàm `index_batch_parallel()` dùng `asyncio.Semaphore` để giới hạn số luồng (mặc định 4) tránh rate-limit từ APIs.
|
||||
|
||||
### 4.3 Retriever & Hybrid Search (`retriever/`)
|
||||
Kết hợp sức mạnh Full-text search của Postgres và Vector search của `pgvector`.
|
||||
- **Hybrid Search Flow (`chunks_hybrid_search.py`)**:
|
||||
- Tính toán tsvector/tsquery (Keyword Search) và L2 Distance / Cosine Similarity `Chunk.embedding.op("<=>")` (Semantic Search).
|
||||
- Sử dụng chung RRF (Reciprocal Rank Fusion) ở cấp database (bằng CTE) để cho điểm `1.0 / (k + rank)`.
|
||||
- Phân trang & giới hạn: Fetch một số chunk nhất định mỗi document bằng `ROW_NUMBER()` trong subquery, tăng performance khi đọc những file dài/nhiều chunk.
|
||||
|
||||
## 5. Patterns Hiện Có
|
||||
- **Tiêm Phụ Thuộc (Dependency Injection)**: Backend chia nhỏ logic theo các Service Class (`services/`, `EtlPipelineService`, `IndexingPipelineService`) sau đó inject vào Router thông qua `Depends()`.
|
||||
- **Bất Đồng Bộ (Asynchronous Operations)**:
|
||||
- Database Call: Sử dụng `asyncpg` và session async từ SQLAlchemy.
|
||||
- Xử lý nặng (Compute-Bound): Offload qua `asyncio.to_thread()` (VD: chunking, embedding generation).
|
||||
- **Tách Biệt Task Queue**: Các thao tác Indexing bulk hoặc crawl dữ liệu qua Playwright đều được push qua Redis để Celery worker processing.
|
||||
|
||||
## 6. Deployment Info
|
||||
Dự án được triển khai bằng Docker (có `docker-compose.yml` đi kèm cho Dev Environment chạy đủ bộ FastAPI, Postgres (pg17 vector), Redis, Celery Worker, Zero-Cache cache sync daemon).
|
||||
36
docs/architecture-web.md
Normal file
36
docs/architecture-web.md
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
# Kiến Trúc Hệ Thống: Frontend (`surfsense_web`)
|
||||
|
||||
## 1. Tổng Quan
|
||||
Frontend (Web Application) cung cấp giao diện tương tác chính cho người dùng: bao gồm Dashboard, Chat Interface, Trình quản lý tài liệu, và Cấu hình kết nối. Ứng dụng theo hơi hướng **Local-First**, nghĩa là tải nhanh và phản hồi tức thì nhờ đồng bộ trạng thái ngầm.
|
||||
|
||||
## 2. Công Nghệ Cốt Lõi
|
||||
- **Framework Chính**: Next.js 16 (App Router)
|
||||
- **View Layer**: React 19
|
||||
- **Styling**: TailwindCSS 4, Radix UI primitives, Lucide Icons
|
||||
- **Quản lý State & Đồng Bộ**: `@rocicorp/zero` (cho Realtime DB Sync), Zustand (Global UI State), TanStack Query (Server State fetch)
|
||||
- **Database Access / Schema**: Drizzle ORM
|
||||
|
||||
## 3. Cấu Trúc Mã Nguồn (Directory Structure)
|
||||
```text
|
||||
surfsense_web/
|
||||
├── app/ # Next.js App Router
|
||||
│ ├── (home)/ # Landing page / Trang chủ
|
||||
│ ├── api/ # Route handlers / API routes của NextJS (Proxy/Webhooks)
|
||||
│ ├── auth/ # Luồng xác thực đăng nhập
|
||||
│ ├── dashboard/ # Bảng điều khiển quản trị và sử dụng chính
|
||||
│ ├── docs/ # Trang tài liệu dành cho end-user (Tích hợp Fumadocs)
|
||||
│ ├── layout.tsx # Global Layout / App Provider
|
||||
│ └── globals.css # Global styles (Tailwind directives)
|
||||
├── components/ # Hơn 200 UI components tái sử dụng
|
||||
├── hooks/ # Custom React Hooks
|
||||
├── lib/ # Tiện ích chung, utils cho UI
|
||||
└── store/ # Nơi định nghĩa Zustand store
|
||||
```
|
||||
|
||||
## 4. Patterns Hiện Có
|
||||
- **Server Components Mặc Định**: Giao diện cố định và data fetching tĩnh đều đặt ở Server Components. Các Hook/State mới chuyển qua Client Component (`"use client"`).
|
||||
- **Zero Local-First Sync**: Thay vì fetch API liên tục để xem file hay chat log, frontend đọc trực tiếp từ Local Zero State, trong khi Zero Client ngầm đồng bộ với Backend Data trên Postgres. Đảm bảo trải nghiệm tức thì (Optimistic Updates).
|
||||
- **Zustand cho Component State Liên Kết**: Dùng nhiều cho các side-panels, tooltips hay modal triggers mà không cần truyền Props quá rườm rà.
|
||||
|
||||
## 5. UI/UX Design System
|
||||
Hệ thống UI được thiết kế riêng với TailwindCSS. Sử dụng phong cách Modern Interface (bo góc mềm, Glassmorphism, Focus ring rõ ràng) giúp ứng dụng thân thiện, sạch sẽ và phù hợp với một công cụ tìm kiếm tri thức AI cá nhân. Dữ liệu theme nằm ở `globals.css` và `tailwind.config.ts` (hoặc chuẩn Tailwind v4).
|
||||
38
docs/component-inventory.md
Normal file
38
docs/component-inventory.md
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
# Component Inventory (Giao Diện)
|
||||
|
||||
## Tổng quan
|
||||
SurfSense Frontend sử dụng hệ thống Component quy mô lớn (hơn 200 components) đặt tại `surfsense_web/components/`.
|
||||
Hệ thống tuân thủ thiết kế phân rã (Atomic/Feature-based) để tái sử dụng.
|
||||
|
||||
## Mục Lục Các Trụ Cột Thành Phần (Major Folders)
|
||||
|
||||
### 1. `ui/` - Components Dùng Chung (Atoms & Molecules)
|
||||
Bao gồm toàn bộ nền tảng Shadcn (Button, Dialog, Dropdown, Table, Input, Accordion...). Đây là các component độc lập không chứa Business Logic, tuỳ chỉnh styles trực tiếp qua Tailwind.
|
||||
|
||||
### 2. `chat-comments/`, `public-chat/`, `new-chat/` - Cụm Hội Thoại
|
||||
Chịu trách nhiệm render View của AI Chat.
|
||||
- Hỗ trợ Markdown rendering (`markdown-viewer.tsx`).
|
||||
- Rendering Metadata nội bộ do AI suy luận ra (`json-metadata-viewer.tsx`).
|
||||
- Các UI liên quan đến Public Sharing và Reply Comment trên từng node hội thoại.
|
||||
|
||||
### 3. `connectors/`, `sources/` - Cụm Integrations
|
||||
- UI dạng Form và Dialog để thêm kết nối bên thứ 3 (Slack, Docs, Airtable...).
|
||||
- Quản lý trạng thái Sync / Load Error.
|
||||
|
||||
### 4. `documents/`, `editor/`, `editor-panel/` - Cụm Quản Lý Tri Thức
|
||||
- Preview tài liệu nội bộ / PDF / Docs.
|
||||
- Bảng hiển thị thông tin (`document-viewer.tsx`).
|
||||
- Soạn thảo và tinh chỉnh tài liệu với Editor đi kèm.
|
||||
|
||||
### 5. `dashboard/`, `settings/`, `pricing/`, `auth/` - Cụm Tài Khoản & Ứng Dụng
|
||||
- Các thiết lập Profile User, Tokens, RBAC, Billing UI (`pricing.tsx`).
|
||||
- Authentication UIs (Login screen, Invite dialog, Onboarding flow).
|
||||
|
||||
### 6. Cụm AI & Tools Đặc Biệt
|
||||
- `tool-ui/`: Các UI tương tác với công cụ do Agent gọi ra (Ví dụ: Công cụ lấy thời tiết, vẽ biểu đồ...).
|
||||
- `prompt-kit/`: UI thiết lập thư viện câu lệnh cá nhân hóa.
|
||||
- `assistant-ui/`: Khung bọc giao diện LLM Assistant (LangChain/Vercel AI SDK integration).
|
||||
- `inference-params-editor.tsx`: Bảng cấu hình AI Models (Temperature, Top K, Provider switch).
|
||||
|
||||
---
|
||||
*Ghi chú: Components thường xuyên kết hợp Zustand (`store/`) để lấy Global State. Hạn chế sử dụng Context API tránh re-render domino.*
|
||||
41
docs/data-models.md
Normal file
41
docs/data-models.md
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
# SurfSense Data Models
|
||||
|
||||
## Tổng quan
|
||||
SurfSense xử lý hệ thống dữ liệu vô cùng phức tạp với nhiều nguồn Integration (Slack, Discord, Confluence...) kết nối với LLM RAG System. Hệ thống Models dưới đây được định nghĩa bằng SQLAlchemy tại `surfsense_backend/app/db.py` và có ánh xạ Typescript bên `surfsense_web/db/`.
|
||||
|
||||
## 1. Phân Hệ Core Documents & RAG (Retrieval-Augmented Generation)
|
||||
|
||||
Đây là trung tâm lưu trữ khối lượng dữ liệu chính của AI.
|
||||
- **`Document` / `DocumentVersion`**: Lưu trữ Metadata của các tập tin tải lên nội bộ hoặc import từ Internet.
|
||||
- **`Chunk`**: Phân mảnh văn bản (Splitted text) sinh ra từ `Document` đi kèm với Vector Embeddings (`pgvector`). Dùng cho Vector Search khi RAG.
|
||||
- **`SurfsenseDocsDocument` / `SurfsenseDocsChunk`**: Bộ models riêng quản lý tài liệu nội bộ / hệ thống hướng dẫn của SurfSense.
|
||||
|
||||
## 2. Phân Hệ Search Spaces & Connectors
|
||||
|
||||
Để tách biệt quyền và phân mảnh RAG theo Workspaces hoặc Project.
|
||||
- **`SearchSpace`**: Định nghĩa một vùng không gian RAG cô lập cho một dự án.
|
||||
- **`SearchSourceConnector`**: Dùng lưu trữ Credentials và State đồng bộ với các nền tảng bên thứ ba (Slack, Notion, Jira...). Dữ liệu kéo về từ con này sẽ nằm trong `SearchSpace`.
|
||||
- **RBAC (Role-Based Access Control)**: Được quản lý thông qua `SearchSpaceRole`, `SearchSpaceMembership` và `SearchSpaceInvite`.
|
||||
|
||||
## 3. Phân Hệ Chats & Collaboration
|
||||
|
||||
Quản lý tương tác trực tiếp với Agent và Multi-user Chat.
|
||||
- **`NewChatThread` / `NewChatMessage`**: Lịch sử hội thoại cốt lõi. Chứa Role của người gửi (User/Assistant/System).
|
||||
- **`PublicChatSnapshot`**: Lưu trữ các luồng chat publish ra ngoài hệ thống (public sharing).
|
||||
- **`ChatComment` / `ChatCommentMention`**: Tính năng bình luận nhóm trên một đoạn trả lời của LLM.
|
||||
- **`ChatSessionState`**: Quản lý biến ngữ cảnh, bộ nhớ session của AI.
|
||||
|
||||
## 4. Phân Hệ AI Configurations
|
||||
|
||||
Cấu hình cho các Nodes Agent xử lý.
|
||||
- **`NewLLMConfig` / `Prompt`**: Cấu hình Provider (OpenAI/Anthropic/Gemini) và System Prompts (độ dài tokens, temp...).
|
||||
- **`ImageGenerationConfig` / `ImageGeneration`**: Quản lý lịch sử và API sinh ảnh do Agent tạo.
|
||||
- **`Podcast` / `VideoPresentation`**: Các dạng Outputs tổng hợp xuất bản từ văn bản bằng Voice / Video AI.
|
||||
|
||||
## 5. Tổ Chức & Telemetry
|
||||
- **`Folder`**: Hệ thống tổ chức cây Chat / Document.
|
||||
- **`Notification`**: Thông báo realtime push qua Zero.
|
||||
- **`Log`**: Hệ thống Telemetry, Log usage cho API Calls của Agent.
|
||||
|
||||
---
|
||||
_Lưu ý: Do Zero Framework yêu cầu, các Primary Keys lưu trữ thường theo chuẩn chuỗi UUIDv4 string, tích hợp 2 chiều Pydantic (Backend) và Drizzle (Frontend)._
|
||||
43
docs/deployment-guide.md
Normal file
43
docs/deployment-guide.md
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
# SurfSense Deployment Guide
|
||||
|
||||
## Overview
|
||||
SurfSense uses Docker and Docker Compose as its primary mechanism for deployment, scaling, and infrastructure orchestration. CI/CD is fully managed via GitHub Actions mapping to GitHub Container Registry (GHCR).
|
||||
|
||||
## Docker Compose Production Stack
|
||||
Located at `docker/docker-compose.yml`, the production stack orchestrates:
|
||||
1. **db**: `pgvector/pgvector:pg17` (Postgres 17 with vector search).
|
||||
2. **redis**: `redis:8-alpine` (Task queuing and caching).
|
||||
3. **searxng**: Private metasearch instance (`searxng/searxng`).
|
||||
4. **backend**: The FastAPI application serving REST endpoints (`ghcr.io/modsetter/surfsense-backend:latest`).
|
||||
5. **celery_worker**: Background processing worker.
|
||||
6. **celery_beat**: Background cron/recurring tasks scheduler.
|
||||
7. **zero-cache**: `rocicorp/zero:0.26.2` (Sync engine connecting Postgres and Next.js).
|
||||
8. **frontend**: Next.js App Router Web Interface (`ghcr.io/modsetter/surfsense-web:latest`).
|
||||
|
||||
## CI/CD Pipeline (GitHub Actions)
|
||||
The workflow is defined at `.github/workflows/docker-build.yml`.
|
||||
|
||||
### Triggers
|
||||
- Automatic on pushes to `main` and `dev` branches for paths inside `surfsense_backend/**` and `surfsense_web/**`.
|
||||
- Manual via `workflow_dispatch`.
|
||||
|
||||
### Stages
|
||||
1. **Tag Release (`tag_release`)**:
|
||||
- Calculates the App Version from the `VERSION` file.
|
||||
- Automatically increments build numbers and creates Git Tags.
|
||||
2. **Build (`build`)**:
|
||||
- Compiles independent Docker images for `backend` and `web`.
|
||||
- Utilizes a matrix to build multi-architecture images (`linux/amd64` and `linux/arm64`).
|
||||
- Caches layers using GitHub Actions cache (`type=gha`).
|
||||
- Exports the docker image digest into temporary artifacts.
|
||||
3. **Manifest Creation (`create_manifest`)**:
|
||||
- Takes the isolated `amd64` and `arm64` images and merges them into a single manifest list.
|
||||
- Pushes to `ghcr.io/modsetter/surfsense-backend` and `ghcr.io/modsetter/surfsense-web`.
|
||||
|
||||
## Environment Handling
|
||||
- **Frontend Build args**: Next.js requires environment constants baked at build time (e.g. `NEXT_PUBLIC_FASTAPI_BACKEND_URL`). The GH Action pipes dummy values `__NEXT_PUBLIC_FASTAPI_BACKEND_URL__` which are presumably swapped via `docker-entrypoint.sh` at runtime execution.
|
||||
- **Backend Configuration**: Read exclusively via Docker Compose `env_file` mapping to `.env` dynamically.
|
||||
|
||||
## Update & Maintenance
|
||||
- Images pushed to GHCR automatically tag with the repository commit and 'latest'.
|
||||
- Watchtower (`com.centurylinklabs.watchtower.enable=true` label on containers) can be used alongside this stack to enable automatic Rolling Updates when GHCR provides a new version.
|
||||
64
docs/development-guide.md
Normal file
64
docs/development-guide.md
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
# SurfSense Development Guide
|
||||
|
||||
## Prerequisites
|
||||
- **Node.js**: v18+ with `pnpm` (managed via packageManager: "pnpm@10.24.0").
|
||||
- **Python**: v3.12+ for the FastAPI backend.
|
||||
- **Docker & Docker Compose**: Required for spin-up of PostgreSQL (pgvector), Redis, SearXNG, and Zero-Cache.
|
||||
- **Git**
|
||||
|
||||
## Monorepo Setup
|
||||
|
||||
The SurfSense project relies on a multi-part configuration.
|
||||
The core directories include:
|
||||
- `surfsense_web/`: Next.js frontend (App Router)
|
||||
- `surfsense_backend/`: FastAPI backend with language models and Celery integration.
|
||||
- `docker/`: Docker compose files.
|
||||
|
||||
## Environment Configuration
|
||||
You must configure environmental variables before starting the platform.
|
||||
1. Copy `.env.example` to `.env` in the root folder, and also in individual sub-projects if needed.
|
||||
2. Typical variables include `DATABASE_URL`, `REDIS_URL`, `SEARXNG_SECRET`, and frontend endpoints (`NEXT_PUBLIC_FASTAPI_BACKEND_URL`).
|
||||
|
||||
## Starting the Infrastructure (Docker)
|
||||
For local development, it is highly recommended to offload the database and cache to Docker:
|
||||
```bash
|
||||
# In the project root or docker folder
|
||||
docker compose -f docker/docker-compose.dev.yml up -d db redis searxng zero-cache
|
||||
```
|
||||
|
||||
## Running the Web Frontend
|
||||
The frontend uses Next.js with Zero for local-first syncing.
|
||||
```bash
|
||||
cd surfsense_web
|
||||
pnpm install
|
||||
pnpm dev
|
||||
# Runs on http://localhost:3000
|
||||
```
|
||||
|
||||
## Running the Backend
|
||||
The backend utilizes Python FastAPI.
|
||||
```bash
|
||||
cd surfsense_backend
|
||||
# Set up virtual environment
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
pip install -e .[dev]
|
||||
|
||||
# Start the API SERVER
|
||||
uvicorn app.main:app --reload --port 8929
|
||||
|
||||
# Start Celery Worker (In a separate terminal)
|
||||
celery -A app.celery_app worker --loglevel=info
|
||||
|
||||
# Start Celery Beat (For scheduled tasks)
|
||||
celery -A app.celery_app beat --loglevel=info
|
||||
```
|
||||
|
||||
## Testing Protocol
|
||||
- Backend tests use `pytest` with `pytest-asyncio`. Run from `surfsense_backend` via `pytest`.
|
||||
- Backend code standards are maintained with `ruff`.
|
||||
|
||||
## Contribution Guidelines
|
||||
- Ensure `ruff` linting passes before committing python code.
|
||||
- All dependencies for the frontend should be added using `pnpm`.
|
||||
- Ensure new backend models have Alembic migrations generated.
|
||||
55
docs/index.md
Normal file
55
docs/index.md
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
# SurfSense Project Documentation Index
|
||||
|
||||
## 🌟 Project Overview
|
||||
- **Type:** monorepo with 4 parts
|
||||
- **Primary Languages:** Python, TypeScript, TSX
|
||||
- **Architecture:** API Service (FastAPI) + Web App (Next.js App Router) + Desktop + Extension
|
||||
|
||||
## 🏗️ Quick Reference
|
||||
|
||||
### Frontend (`surfsense_web/`)
|
||||
- **Type:** web
|
||||
- **Tech Stack:** Next.js 16 (App Router), React 19, TailwindCSS 4, Drizzle ORM, @rocicorp/zero (Local-first sync)
|
||||
|
||||
### Backend (`surfsense_backend/`)
|
||||
- **Type:** backend
|
||||
- **Tech Stack:** FastAPI (Python 3.12), SQLAlchemy, Alembic, Celery, Redis, LangGraph, pgvector
|
||||
|
||||
### Browser Extension (`surfsense_browser_extension/`)
|
||||
- **Type:** extension
|
||||
- **Tech Stack:** React, TypeScript
|
||||
|
||||
### Desktop Client (`surfsense_desktop/`)
|
||||
- **Type:** desktop
|
||||
- **Tech Stack:** TypeScript (TBD frameworks)
|
||||
|
||||
## 🌐 Code Review Graph & Communities
|
||||
Dự án đã được phân tích bằng công cụ Code Review Graph, trích xuất thành công:
|
||||
- **6,578 nodes** & **55,487 edges**
|
||||
- **696 communities/modules** architecture pages (Được lưu ở `.code-review-graph/wiki/`)
|
||||
|
||||
## 📑 Generated Documentation
|
||||
|
||||
- [Project Overview](./project-overview.md)
|
||||
- [Architecture (Frontend)](./architecture-web.md)
|
||||
- [Architecture (Backend)](./architecture-backend.md)
|
||||
- [Source Tree Analysis](./source-tree-analysis.md)
|
||||
- [Component Inventory](./component-inventory.md)
|
||||
- [Development Guide](./development-guide.md)
|
||||
- [Deployment Guide](./deployment-guide.md)
|
||||
- [API Contracts](./api-contracts.md)
|
||||
- [Data Models](./data-models.md)
|
||||
- [Integration Architecture](./integration-architecture.md)
|
||||
|
||||
## 📁 Existing Documentation
|
||||
- [Code Review Graph Wiki](../.code-review-graph/wiki/_index.md) - Chi tiết từng community và file dependency.
|
||||
- [Project Scan Report](./project-scan-report.json) - Trạng thái scan ban đầu của BMad.
|
||||
|
||||
## 🚀 Getting Started
|
||||
Để bắt đầu cài đặt và phát triển trên dự án này:
|
||||
1. Đọc [Development Guide](./development-guide.md) để biết cách spin up hệ thống Backend (FastAPI, Redis, Celery, Postgres pgvector) và Frontend (Next.js, Zero-Cache) bằng Docker.
|
||||
2. Tham khảo [Integration Architecture](./integration-architecture.md) để hiểu cách Zero-Cache đồng bộ trạng thái Frontend-Backend và cách Celery Worker xử lý các pipeline lấy dữ liệu bằng LLM.
|
||||
3. Tham khảo [Architecture (Backend)](./architecture-backend.md) hoặc [Architecture (Frontend)](./architecture-web.md) khi muốn trace sâu vào tầng mã nguồn (EtlPipelineService, HybridSearch, Next App Router, etc.).
|
||||
|
||||
---
|
||||
*This documentation is part of the BMAD generation process.*
|
||||
36
docs/integration-architecture.md
Normal file
36
docs/integration-architecture.md
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
# SurfSense Integration Architecture
|
||||
|
||||
## System Topography
|
||||
SurfSense operates via a multi-part integration model separating state syncing, background processing, and web presentation.
|
||||
|
||||
### 1. Data Sync Layer (Zero + Next.js + PostgreSQL)
|
||||
- **Zero Cache (`zero-cache`)**: Acts as the real-time CVR (Client View Record) layer synchronizing mutations.
|
||||
- **Flow**:
|
||||
- The Next.js frontend uses `@rocicorp/zero` to mutate or query data locally.
|
||||
- Zero Cache connects directly to the PostgreSQL upstream DB (`ZERO_UPSTREAM_DB` & `ZERO_CVR_DB`) polling for replication changes.
|
||||
- Conflicts and syncing are orchestrated between Zero Cache (`port 4848`) and Frontend API endpoints (`/api/zero/query` and `/api/zero/mutate`).
|
||||
|
||||
### 2. General API / Action Layer (FastAPI + Next.js)
|
||||
- **FastAPI Layer**: When synchronous REST operations, authentication, or triggers are needed (like initiating a scrape), Next.js performs HTTP REST calls to the FastAPI backend at `BACKEND_PORT`: `8929/8000`.
|
||||
- The FastAPI layer accesses the Postgres DB directly utilizing `asyncpg` and `SQLAlchemy`.
|
||||
|
||||
### 3. AI / RAG Processing Layer (SearXNG + Celery + FastAPI)
|
||||
- **Search**: FastAPI contacts `SearXNG` at `http://searxng:8080` (Internal Docker network) for anonymized agent searches.
|
||||
- **Offloaded Processing**:
|
||||
- Web scraping/Agent LLM processes are handed off from FastAPI to **Celery**.
|
||||
- `Celery` uses `Redis` at `redis:6379/0` as its Broker and Result Backend.
|
||||
- A detached **Celery Worker** process natively handles LangGraph workflows, processing large web contexts and storing vector outputs back into PostgreSQL via `pgvector`.
|
||||
- **Celery Beat** provides ongoing scheduled tasks, waking up the worker for cron jobs.
|
||||
|
||||
## Component Integrations Summary
|
||||
|
||||
| Origin | Target | Protocol | Description |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Next.js (Web)** | Zero Cache | WebSocket / HTTP | Local-first State Sync API. |
|
||||
| **Next.js (Web)** | FastAPI | HTTP/REST | Triggering synchronous jobs, user logic. |
|
||||
| **Zero Cache** | PostgreSQL | TCP (PG Protocol) | Standard relational sync and conflict resolution via CVR. |
|
||||
| **FastAPI** | PostgreSQL | TCP (PG Protocol) | AsyncPG DB Reads/Writes. |
|
||||
| **FastAPI** | Redis | TCP | Celery queue pipelining / PubSub. |
|
||||
| **FastAPI** | SearXNG | HTTP | Metasearch queries. |
|
||||
| **Celery Worker** | Redis | TCP | Consuming asynchronous processing queues. |
|
||||
| **Celery Worker** | PostgreSQL | TCP | Saving LangGraph context and PgVector embeddings. |
|
||||
44
docs/project-overview.md
Normal file
44
docs/project-overview.md
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
# SurfSense Project Overview
|
||||
|
||||
## Mục Đích Dự Án
|
||||
SurfSense là một hệ thống đa nền tảng (Web, Desktop, Extension) cho phép thu thập, lưu trữ, lập chỉ mục (indexing) và phân tích dữ liệu qua AI. Hệ thống sử dụng phương pháp **local-first** sync (ưu tiên đồng bộ local realtime qua Zero) để mang lại trải nghiệm người dùng liền mạch và không có độ trễ.
|
||||
|
||||
## Cấp Độ Kiến Trúc (Executive Summary)
|
||||
Dự án được xây dựng dưới dạng **Monorepo** chia làm 4 bộ phận độc lập có tính kết nối cao qua API và Websocket (Sync):
|
||||
1. **Frontend App (`surfsense_web`)**: Dashboard và giao diện end-user.
|
||||
2. **Backend Service (`surfsense_backend`)**: Nơi xử lý dữ liệu nặng (Extract-Transform-Load, LLM processing, Background Tasks, Embedding).
|
||||
3. **Browser Extension (`surfsense_browser_extension`)**: Tool capture dữ liệu từ trình duyệt người dùng.
|
||||
4. **Desktop App (`surfsense_desktop`)**: Native client hỗ trợ sâu các tính năng OS-level.
|
||||
|
||||
## Tiêu Chuẩn Công Nghệ Cốt Lõi
|
||||
| Hạng Mục | Công Nghệ | Vai trò / Justification |
|
||||
| ---------|----------| ----------------------- |
|
||||
| **Frontend Framework** | Next.js 16 (App Router) | Hỗ trợ Server Components, SEO & routing tối giản. Mặc định SSR. |
|
||||
| **Frontend State/Sync** | @rocicorp/zero, Zustand | Zero cho đồng bộ realtime state từ CSDL đến client. |
|
||||
| **UI Components** | React 19, TailwindCSS 4, Shadcn | Thiết kế tái sử dụng cao, tối ưu performance. |
|
||||
| **Backend API** | FastAPI (Python 3.12) | API xử lý tốc độ cao, type-hinting tự động generate Swagger/OpenAPI. |
|
||||
| **Database/ORM** | PostgreSQL, pgvector, SQLAlchemy, Drizzle | Vector database phục vụ embedding/LLM. Quản lý schema 2 chiều Python/TS. |
|
||||
| **Async Tasks** | Celery + Redis | Đảm nhận các heavy background jobs: AI processing, indexing files. |
|
||||
| **RAG & Agents** | LangChain, LangGraph | Quản lý graph agent logic, query LLM API. |
|
||||
|
||||
## Thư Mục Mã Nguồn Chính
|
||||
Kiến trúc mã nguồn được phân bổ như sau:
|
||||
```text
|
||||
SurfSense/
|
||||
├── docs/ # Tài liệu dự án (kết quả sau scan BMAD)
|
||||
├── docker/ # Cấu hình container & infra (Compose)
|
||||
├── surfsense_web/ # Giao diện Next.js
|
||||
│ ├── app/ # Page routers
|
||||
│ ├── components/ # ~200 ui components
|
||||
│ └── public/ # Static assets
|
||||
├── surfsense_backend/ # Server APIs
|
||||
│ ├── app/
|
||||
│ │ ├── api/routes # Định tuyến API
|
||||
│ │ ├── schemas/ # Pydantic validation
|
||||
│ │ ├── services/ # Core business logic / DI
|
||||
│ │ └── tasks/ # Background task workers
|
||||
│ └── tests/ # Pytest suites
|
||||
└── ... # Extension & Desktop folders
|
||||
```
|
||||
---
|
||||
*Được khởi tạo bởi Agent theo tiêu chuẩn BMAD (Full-Scan Workflow).*
|
||||
85
docs/project-scan-report.json
Normal file
85
docs/project-scan-report.json
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
{
|
||||
"workflow_version": "1.2.0",
|
||||
"timestamps": {
|
||||
"started": "2026-04-12T23:49:16+07:00",
|
||||
"last_updated": "2026-04-13T00:20:00+07:00"
|
||||
},
|
||||
"mode": "full_rescan",
|
||||
"scan_level": "exhaustive",
|
||||
"project_root": "/Users/luisphan/Documents/GitHub/SurfSense",
|
||||
"project_knowledge": "/Users/luisphan/Documents/GitHub/SurfSense/docs",
|
||||
"completed_steps": [
|
||||
"step_1",
|
||||
"step_2",
|
||||
"step_3",
|
||||
"step_4",
|
||||
"step_5",
|
||||
"step_6",
|
||||
"step_7",
|
||||
"step_8",
|
||||
"step_9"
|
||||
],
|
||||
"current_step": "completed",
|
||||
"findings": {
|
||||
"project_type_id": "web_monorepo",
|
||||
"structure": [
|
||||
"surfsense_web/",
|
||||
"surfsense_backend/",
|
||||
"surfsense_browser_extension/",
|
||||
"surfsense_desktop/",
|
||||
"docker/",
|
||||
"scripts/"
|
||||
],
|
||||
"dependencies": {
|
||||
"frontend": ["next", "react", "tailwindcss", "drizzle-orm", "@rocicorp/zero", "fumadocs"],
|
||||
"backend": ["fastapi", "alembic", "psycopg", "celery", "redis", "langgraph", "langchain"]
|
||||
},
|
||||
"architectural_patterns": [
|
||||
"Monorepo structure",
|
||||
"Next.js App Router",
|
||||
"Local-first state sync with Zero",
|
||||
"Backend API via FastAPI",
|
||||
"Task Queues via Celery & Redis"
|
||||
],
|
||||
"components": {
|
||||
"api_endpoints_count": 46,
|
||||
"data_models_count": 34,
|
||||
"ui_components_count": 200
|
||||
},
|
||||
"entry_points": [
|
||||
"surfsense_backend/app/main.py",
|
||||
"surfsense_backend/app/celery_app.py",
|
||||
"surfsense_web/app/layout.tsx"
|
||||
],
|
||||
"config_files": [
|
||||
"docker/docker-compose.yml",
|
||||
"surfsense_web/package.json",
|
||||
"surfsense_backend/pyproject.toml"
|
||||
],
|
||||
"data_storage": [
|
||||
"PostgreSQL (Drizzle/SQLAlchemy)",
|
||||
"Redis"
|
||||
],
|
||||
"integrations": [
|
||||
"Zero Sync",
|
||||
"Google Auth",
|
||||
"LangGraph Agents",
|
||||
"SearXNG"
|
||||
]
|
||||
},
|
||||
"outputs_generated": [
|
||||
"index.md",
|
||||
"project-overview.md",
|
||||
"architecture-backend.md",
|
||||
"architecture-web.md",
|
||||
"data-models.md",
|
||||
"api-contracts.md",
|
||||
"source-tree-analysis.md",
|
||||
"component-inventory.md",
|
||||
"development-guide.md",
|
||||
"deployment-guide.md",
|
||||
"integration-architecture.md",
|
||||
"project-scan-report.json"
|
||||
],
|
||||
"resume_instructions": "Scan completed"
|
||||
}
|
||||
32
docs/source-tree-analysis.md
Normal file
32
docs/source-tree-analysis.md
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
# Báo Cáo Source Tree (Monorepo)
|
||||
|
||||
## 1. Cấu trúc Root (Monorepo)
|
||||
Dự án SurfSense sử dụng mô hình Monorepo (quản lý ở cấp độ thư mục gốc) chứa tất cả Client và Backend, giúp dễ dàng chia sẻ Scripts và Docker Configurations. Cấu trúc gồm 4 cột trụ chính và các files bổ trợ:
|
||||
|
||||
```text
|
||||
SurfSense/
|
||||
├── .agent/ # Cấu hình BMad Framework (Agent settings, prompts)
|
||||
├── .github/ # GitHub Actions CI/CD workflows
|
||||
├── _bmad/ # Dữ liệu phục vụ BMAD chạy nội bộ
|
||||
├── _bmad-output/ # Nơi lưu kết quả, sprints, architect docs của BMAD
|
||||
├── docker/ # Nơi chứa config deploy Docker & Compose
|
||||
├── docs/ # [Mục lục này] Output docs đã generate/review
|
||||
├── scripts/ # Bash scripts để setup, format, chạy tools cục bộ
|
||||
├── surfsense_backend/ # Core FastAPI, Python Codebase
|
||||
├── surfsense_browser_extension/ # Extension build folder
|
||||
├── surfsense_desktop/ # Native Web-wrappers Desktop / Electron-Tauri
|
||||
└── surfsense_web/ # Next.js Web App Core
|
||||
```
|
||||
|
||||
## 2. Chi Tiết Từng Phân Hệ Core
|
||||
|
||||
### 2.1 Backend (`surfsense_backend`)
|
||||
Bao gồm App FastAPI có cấu trúc Layered Architecture cổ điển. Python version yêu cầu 3.12+. Dependency được quản lý qua `poetry` hoặc `requirements.txt`. (Chi tiết tại `architecture-backend.md`).
|
||||
|
||||
### 2.2 Frontend Web (`surfsense_web`)
|
||||
Bao gồm một lượng lớn UI/UX logic bằng NextJS 16 App Router. Đi kèm với nó là Setup Shadcn UI tĩnh. (Chi tiết tại `architecture-web.md`).
|
||||
|
||||
### 2.3 Phân hệ Setup Nội Bộ
|
||||
- `.secrets.baseline`: Công cụ phát hiện secret rò rỉ (Yelp detect-secrets).
|
||||
- `.pre-commit-config.yaml`: Các pre-commit hooks khi lập trình viên submit code (biome, ruff...).
|
||||
- `biome.json`: Sử dụng BiomeJS làm Formatter / Linter chính thay thế cho Prettier/ESLint cho Frontend nhằm đem lại hiệu năng vượt trội.
|
||||
Loading…
Add table
Add a link
Reference in a new issue