Skip to content

About

Fusion-Doc — local-first AI document platform: writing, editing, and knowledge-aware document workflows powered by fusion-mlx

Resources

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

doc_id fusion-doc/readme
product fusion-doc
class platform
entry service
doc_type readme
title
zh en
Fusion-Doc 项目说明(英文)
Fusion-Doc README
audience engineer
status draft
version 1.0.17
updated 2026-11-07
owner @dahai
source_of_truth
README.md
Fusion-Doc Logo

Fusion-Doc V1.0

AI-First Document OS for Apple Silicon

TipTap Editor · AI Copilot · Knowledge Graph · Office Format

🇨🇳 中文 • 🇬🇧 English


Architecture

Fusion-Doc Server (:11449) — AI-First Document Operating System
├── Client (React 18 + Vite + TipTap 2.x)
│   ├── Editor (TipTap + AI Ghost Text + BubbleMenu + Slash Commands)
│   ├── Knowledge Graph (D3.js Force-Directed Layout)
│   ├── AI Chat Panel (office ai-client → fusion-gateway streaming)
│   ├── Office Import/Export
│   ├── Template System
│   ├── Workflow
│   └── Dark Theme (Tailwind CSS)
├── Server (Modular MVC)
│   ├── Controllers (25+ domain modules)
│   ├── Services (AI Copilot, RAG, Office, Workflow)
│   ├── Models (SQLite + JSON dual storage)
│   ├── Integrations (Fusion-MLX, fusion-office office-api)
│   └── Plugins (extensible plugin system)
└── WebSocket (real-time collaboration not released)

Zero external dependencies: No PostgreSQL, Redis, NestJS, or reverse proxy required.

Quick Start

Prerequisites: Node.js 24 LTS (with npm) is recommended. The locked better-sqlite3 dependency does not support Node.js 18. CI still uses Node.js 20.

# 1. Install
bash scripts/setup.sh

# 2. Start (local development only)
NODE_ENV=development FUSION_DOC_HOST=127.0.0.1 FUSION_DOC_LOCAL_AUTH=1 bash start.sh start

# 3. Access
#    http://127.0.0.1:11449            → Document editor
#    http://127.0.0.1:11449/api/health → Health check

First local run: clone the repo, create an admin, and save your first page

AI-First Features

Feature Description Shortcut
AI Ghost Text Inline completion suggestion Cmd+J trigger, Tab accept, Esc reject
AI BubbleMenu Rewrite/translate/summarize/expand selection Select text → floating toolbar
AI Slash Command Command palette with AI actions Type / in editor
AI Chat Panel Side panel with streaming AI chat (office ai-client transport) 🤖 AI button
Global Search Full-text search modal with FTS5 Cmd+K
RAG Enhancement In-document QA via fusion-rag (FUSION_RAG_KB_ID) /api/rag/query

Integrated Features

Source Feature API Endpoint Status
TipTap Rich-text editing and auto-save Built-in frontend ✅
DocMost Workspace → Book → Chapter → Page /api/workspaces ✅
Wiki.js Modular routing + SQLite FTS5 server/controllers/ ✅
BookStack Shelf → Chapter → Page 3-tier /api/books, /api/chapters ✅
Zettlr Bidirectional links + knowledge graph /api/graph, /api/graph/search ✅
D3.js Force-directed graph visualization /graph page ✅
fusion-office office-api xlsx/docx import + docx export + docx template fill (:11492) /api/office/import, /api/office/export/:id, /api/office/merge ✅
fusion-office ai-client Chat panel transport (browser → fusion-gateway :11432) + rollout-tap outcomes vendored client/src/vendor/ai-client ✅
Fusion-MLX Local Embedding + RAG /api/ai/embeddings, /api/rag/query ✅
AI Copilot Inline AI (complete/rewrite/translate) /api/copilot/* ✅
Template Document templates + instantiation /api/templates ✅
Workflow Document state machine (draft→review→publish) /api/workflow/* ✅
Real-time collaboration No live co-editing or collaborator cursors; no collaboration toggle in the editor /ws/collab/:pageId ⏸ Not released

Project Structure

fusion-doc/
├── client/                      ← React 18 + Vite frontend
│   ├── src/
│   │   ├── components/
│   │   │   ├── editor/          ← TipTap editor + AI extensions
│   │   │   │   ├── EditorPage.jsx      (TipTap + auto-save)
│   │   │   │   ├── EditorToolbar.jsx   (formatting toolbar)
│   │   │   │   ├── AIGhostText.jsx     (Cmd+J inline completion)
│   │   │   │   ├── AIBubbleMenu.jsx    (selection AI menu)
│   │   │   │   ├── AISlashCommand.jsx  (/ command palette)
│   │   │   │   └── BiLinkExtension.jsx ([[ bidirectional links + auto-backlinks)
│   │   │   ├── ai/             ← AI chat panel
│   │   │   ├── graph/          ← D3.js knowledge graph
│   │   │   ├── sidebar/        ← Navigation sidebar
│   │   │   ├── common/         ← Layout, HomePage, StatusBar, SearchModal
│   │   │   ├── office/         ← Office import/export panel
│   │   │   ├── template/       ← Template picker
│   │   │   └── workflow/       ← Workflow status badge
│   │   ├── stores/             ← Zustand state (page, book, ui)
│   │   ├── hooks/              ← Editor context hook
│   │   ├── lib/                ← API client (fetch + SSE stream)
│   │   └── styles/             ← Tailwind + TipTap CSS
│   ├── package.json
│   ├── vite.config.js
│   └── tailwind.config.js
├── server/                      ← Core server (modular MVC)
│   ├── controllers/            ← 25+ domain modules
│   │   ├── ai-copilot.js       ← AI inline actions
│   │   ├── office.js           ← Office import/export
│   │   ├── template.js         ← Template CRUD + instantiate
│   │   ├── workflow.js         ← Document workflow state machine
│   │   ├── collaboration.js    ← Stub route for unreleased real-time collaboration
│   │   ├── graph.js            ← Knowledge graph (enhanced + semantic search)
│   │   └── ...                 ← (health, auth, page, book, ai, etc.)
│   ├── services/               ← Business logic
│   │   ├── ai-copilot.js       ← Context building + system prompts
│   │   ├── office.js           ← Office service (xlsx import via office-api, docx fill merge)
│   │   ├── rag.js              ← Document chunking + vector search
│   │   ├── rag-hybrid.js       ← Hybrid RAG (vector+FTS5+BM25 + RRF + rerank)
│   │   ├── workflow.js         ← State transitions + audit trail
│   │   ├── workflow-engine.js  ← YAML workflow engine + 5 presets
│   │   ├── template-engine.js  ← Variable extraction + fill + create
│   │   ├── seed-templates.js   ← 8 preset templates (auto-seed on first run)
│   │   └── rag-worker.js       ← vector-scan worker_thread (offloads event loop)
│   ├── integrations/           ← External service clients
│   │   ├── fusion-mlx.js       ← OpenAI-compatible (chat/embed/rerank/SSE)
│   │   └── office-api.js       ← fusion-office office-api client (xlsx parse + docx fill)
│   └── ...
├── gateway/public/              ← Built frontend (from `npm run build`)
├── scripts/
│   ├── start.sh                ← One-click start
│   ├── setup.sh                ← Installation
│   └── test.sh                 ← Validation tests
└── .env                        ← Environment config

API Overview

Method Path Description
GET /api/health Health check
POST /api/auth/login Login
GET/POST /api/books Book CRUD
GET/POST/PUT/DELETE /api/pages Page CRUD
GET /api/search?q= Full-text search
GET /api/graph Knowledge graph data
GET /api/graph/search?q= Semantic graph search
GET /api/graph/node/:id Node detail + neighbors
POST /api/copilot/complete AI inline completion
POST /api/copilot/rewrite AI rewrite selection
POST /api/copilot/translate AI translate selection
POST /api/copilot/summarize AI summarize selection
POST /api/copilot/expand AI expand selection
POST /api/copilot/command AI custom command
GET /api/copilot/context/:id Page context for AI
GET /api/office/status office-api availability + capability map
POST /api/office/create Create Office document (422 — pending upstream write endpoint)
POST /api/office/import Import .xlsx/.docx → HTML page (.pptx → 422 pending upstream)
POST /api/office/export/:id Export page to .docx via office-api /v1/docx/write (xlsx/pptx → 422 pending upstream)
POST /api/office/preview/:id Preview Office document (422 — pending upstream)
POST /api/office/merge Docx template merge via /v1/docx/fill
GET/POST /api/templates Template CRUD
POST /api/templates/:id/instantiate Create page from template
GET /api/templates/:id/variables Extract template variables
GET/POST /api/workflows Workflow CRUD
POST /api/workflows/:id/run Execute workflow
GET /api/workflows/:id/runs Execution history
POST /api/workflows/seed Seed 5 preset workflows
GET /api/workflow/:id Page workflow status
POST /api/workflow/:id/transition State transition
POST /api/rag/enhanced-query Hybrid RAG query (embedded engine, non-UI API)
POST /api/rag/reindex/:id Reindex page chunks (embedded engine, non-UI API)
GET /api/rag/chunks/:pageId Get page chunks (embedded engine, non-UI API)
WS /ws/collab/:pageId Not released; closes upgraded connections with WebSocket close code 4011

Fusion Ecosystem

Project Description Integration
Fusion-MLX Local MLX inference engine AI chat, embeddings, RAG, copilot
Fusion-Coder AI coding assistant Code generation & review
Fusion-KB Knowledge base Document knowledge graph
Fusion-Doc Document OS (this) Central document platform

Union Web Shell Integration (issue #51)

Fusion-Doc registers itself as a remote module of the Union Web shell (fusion-gateway :11432, PRD R-6). On startup the server POSTs client/manifest.json (id fusion-doc, category infra) to the gateway manifest registry, then sends a heartbeat. The gateway serves the module at /shell/fusion-doc/ via a same-origin iframe proxy and injects the module service credential upstream — the caller's shell session never reaches fusion-doc.

  • Dual mode: standalone (http://localhost:11449) and embedded (?embedded=1 or mounted under /shell/fusion-doc/). Embedded mode hides the sidebar/status bar chrome (R-8) and skips the local login gate — auth belongs to the shell host
  • Service credential: FUSION_DOC_SHELL_API_KEY env, or auto-generated and persisted to data/shell-api-key.json (0600). Requests carrying it authenticate as the shell tenant with role operator (configurable via FUSION_DOC_SHELL_TENANT/FUSION_DOC_SHELL_ROLE); admin endpoints remain admin-only
  • Registration env: FUSION_GATEWAY_URL (default http://127.0.0.1:11432) and FUSION_ADMIN_KEY — without the admin key registration is skipped with a warning (standalone operation unaffected)
  • Dev HMR: client dev server runs on port 11477 (registered in architecture/port-registry.yaml; 5173 is a reserved port). Point the shell at it via FUSION_DEV_MODULES=fusion-doc:11477
  • The build uses a relative base (base: './') so one bundle serves both the root path and the /shell/fusion-doc/ sub-path
  • Host sync (issues #58/#62): when embedded, theme and language follow the host. The bridge is the vendored @fusion/web-sdk v0.1.2 (client/src/vendor/fusion-web-sdk.js, from fusion-web-shell tag v0.1.2) — theme.subscribe() is the source of truth (cached-sync get() seeds from a background host pull), lang events flow through sdk.i18n, and the heartbeat ping is answered SDK-internally

Development

# Client dev (hot reload, port 11477)
cd client && npm run dev

# Build frontend
cd client && npm run build

# Validate all server modules
bash scripts/test.sh

# Start server
bash scripts/start.sh

Production Deployment

Commercial deployment requires the env vars below and a reverse proxy + TLS up front; see SECURITY.md.

# Required
export JWT_SECRET="$(openssl rand -hex 32)"   # JWT signing secret (production fails fast if missing)
export FUSION_CLIENT_KEY="..."               # Fusion-MLX API key
export FUSION_IDENTITY_SERVICE_TOKEN="..."    # fusion-identity service token (required; fail-closed if missing)
export NODE_ENV="production"                  # production mode (binds 127.0.0.1 by default)

# Behind a reverse proxy
export FUSION_DOC_HOST="0.0.0.0"              # expose to proxy; TLS termination still needed
export CORS_ORIGINS="https://your-domain.com" # CORS allowlist

# Scheduled backup (crontab)
0 2 * * * cd /path/to/fusion-doc && bash scripts/backup.sh 30

# Built-in auto backup (in-process scheduler, env AUTO_BACKUP_HOURS, default 24h, <=0 disables)
export AUTO_BACKUP_HOURS="24"

# Structured logging (ELK ingestion)
export LOG_FORMAT="json"

Built-in TLS (bare exposure)

Native Node tls implements HTTPS with zero new dependencies. Setting cert paths enables it, no reverse proxy needed to terminate TLS.

# Provide cert + private key to enable HTTPS (either missing or unreadable -> fails visibly, never silently falls back to HTTP)
export FUSION_DOC_TLS_CERT="/etc/letsencrypt/live/your-domain.com/fullchain.pem"
export FUSION_DOC_TLS_KEY="/etc/letsencrypt/live/your-domain.com/privkey.pem"
# Optional: client-cert CA (mTLS mutual auth)
export FUSION_DOC_TLS_CA="/etc/fusion-doc/ca.pem"
# HTTP->HTTPS redirect (default on; separate port FUSION_DOC_HTTP_PORT default 11448, set 0 to disable)
export FUSION_DOC_TLS_REDIRECT="1"
export FUSION_DOC_HTTP_PORT="11448"

# Quick self-signed cert (intranet/test)
openssl req -x509 -newkey rsa:2048 -nodes -keyout /tmp/key.pem -out /tmp/cert.pem -days 365 -subj "/CN=localhost"

Once enabled: HSTS header forces subsequent connections over TLS; :11449 serves HTTPS, :11448 returns HTTP 301 redirect. Without TLS but bound to 0.0.0.0, a warning still requires a reverse proxy.

Authentication & tenant isolation (fusion-identity)

Since v1.0.7, fusion-doc delegates JWT issuance and tenant registry to the sibling fusion-identity service (:11470), the sole identity provider for the Fusion ecosystem. fusion-doc no longer self-issues tokens or maintains its own user registry in production.

  • Token verification: every non-public API request must carry Authorization: Bearer <jwt> (issued by fusion-identity) + X-Tenant-Id: <tid> header. The auth middleware verifies the token against POST /api/v1/auth/verify and rejects on mismatch (fail-closed — no default-tenant degradation).
  • Tenant-scoped data: workspaces/pages/books/chapters carry a tenant_id column; all queries filter by tid from the verified context. Cross-tenant access returns 404 (no existence leakage).
  • Roles: 4 unified roles (tenant_admin / operator / member / viewer); admin-gated endpoints accept tenant_admin.
  • AI usage: token consumption is reported fire-and-forget to POST /api/v1/tenants/{tid}/usage.
  • Local single-user dev bypass: set FUSION_DOC_LOCAL_AUTH=1 to restore the built-in HS256 issuer + users table (off by default; production-forbidden). Backfill defaults existing data to tenant_id=local-tenant so it stays accessible in bypass mode.
export FUSION_IDENTITY_URL="http://127.0.0.1:11470"
export FUSION_IDENTITY_SERVICE_TOKEN="..."   # required in production (fail-closed if missing)
# FUSION_DOC_LOCAL_AUTH=1                    # opt-in local bypass (dev only)

Multi-instance horizontal scaling (same-machine multi-process)

SQLite WAL mode supports multi-process concurrent read/write on the same DB (horizontal scaling within one machine). FUSION_DOC_ROLE distinguishes roles, avoiding duplicate execution of ops singletons (thundering herd):

# primary (default): owns E8 zombie-workflow sweep + auto backup
FUSION_DOC_ROLE="primary" FUSION_DOC_PORT="11449" bash start.sh start

# replica: serves requests only, skips single-instance duties (prevents concurrent UPDATE on same row / backup-file contention)
FUSION_DOC_ROLE="replica" FUSION_DOC_PORT="11450" bash start.sh start

The migration system uses BEGIN IMMEDIATE + busy_retry to serialize concurrent startup (only one process runs migrations when several boot at once, the rest queue), with busy_timeout=10000ms as backstop. Cross-machine / cloud-scale expansion needs an external queue + shared storage, out of scope for single-machine.

Large-scale knowledge base (sqlite-vec ANN)

Vector search defaults to linear scan (zero-dependency compatibility). When chunk count exceeds ~10k, enable the sqlite-vec extension for ANN KNN (O(logN)):

npm install sqlite-vec         # already a dependency (v1.0.6+)

# Vector dimension must match the embedding model (default 384 = bge-small-en-v1.5)
export AI_EMBEDDING_DIM="384"

Design: rag_chunks_vec (vec0, integer rowid) + rag_vec_map (rowid<->chunk_id TEXT) two-table bridge for TEXT primary keys; dual-write (rag_chunks.vector JSON fallback + vec table ANN). Missing extension / dimension mismatch -> auto fallback to linear scan (zero regression). Retrieval oversamples topK*4 to compensate for permission-filter elimination.

Container / process hosting

# Docker (multi-stage build, zero external deps)
docker build -f deploy/Dockerfile -t fusion-doc .
docker run -d -p 11449:11449 \
    -e JWT_SECRET="$(openssl rand -hex 32)" \
    -e FUSION_CLIENT_KEY="..." \
    -e FUSION_MLX_URL="http://host.docker.internal:11434" \
    --add-host=host.docker.internal:host-gateway \
    -v fusion-doc-data:/app/data fusion-doc

# systemd (auto-restart + log capture)
sudo cp deploy/fusion-doc.service /etc/systemd/system/
sudo systemctl daemon-reload && sudo systemctl enable --now fusion-doc

Ops endpoints

  • GET /api/health/live — liveness (process alive, always 200)
  • GET /api/health — readiness (DB + MLX + disk usage, returns 503 if DB down)
  • GET /api/metrics — Prometheus text metrics (uptime/memory/request counts/business counts/load)
  • POST /api/system/backup — trigger backup (admin)
  • GET /api/system/backups — backup list (admin)
  • POST /api/system/restore — restore from backup (admin, filename allowlist + path-traversal guard)
  • GET /api/system/backup-schedule — auto-backup schedule status (admin)
  • /settings / /admin — SPA settings page + admin console (backup/restore UI)

Security features: scrypt password hashing / auth endpoint rate-limit / enforced JWT secret / default localhost bind / online hot backup / parameterized SQL / request body size cap / Webhook SSRF guard / data-endpoint ownership check / file path-traversal guard / MIME allowlist / CORS origin allowlist / log redaction / built-in TLS / HSTS / HTTP->HTTPS redirect. Changelog at CHANGELOG.md. Full adversarial security audit: audit/fusion-doc-audit-0830.md in the Fusion monorepo workspace root (not part of this repository).

License

Apache-2.0

About

Fusion-Doc — local-first AI document platform: writing, editing, and knowledge-aware document workflows powered by fusion-mlx

Resources

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages