Skip to content

Commit 48f753b

Browse files
committed
refactor: simplify worker and persistence architecture
1 parent ef1d427 commit 48f753b

20 files changed

Lines changed: 1752 additions & 949 deletions

AGENTS.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,40 @@
33
This file provides comprehensive context for AI coding assistants (like Antigravity) to understand and work with the **Browser LLM Chat** codebase.
44

55
## 🚀 Project Overview
6+
67
- **Name**: Browser LLM Chat
78
- **Primary Goal**: Fully local, privacy-first AI chat application running models via WebGPU.
89
- **Tech Stack**: React 19, Vite, TypeScript, Vanilla CSS.
910
- **Core Library**: `@huggingface/transformers` (v4.0.0-next.x).
1011

1112
## 🏗️ Architecture Summary
13+
1214
- **No Backend**: Zero server-side inference. All models run in the browser's shared GPU memory.
1315
- **Offloading**: Heavy computation is strictly handled in `src/model.worker.ts` to prevent UI thread blocking.
1416
- **Data Flow**:
1517
1. `App.tsx` sends messages/images as a `WorkerRequest`.
1618
2. `model.worker.ts` processes inference using Transformers.js.
1719
3. `model.worker.ts` sends tokens back as `WorkerResponse`.
18-
4. `App.tsx` updates React state for real-time streaming.
20+
4. `App.tsx` updates the Zustand app store for real-time streaming.
1921

2022
## 📁 Critical Files
23+
2124
- `src/App.tsx`: Main UI logic, message orchestration, and worker management.
25+
- `src/store/app-store.ts`: Shared app state and state transitions.
2226
- `src/model.worker.ts`: Worker entry point for Transformers.js inference.
2327
- `src/models.ts`: Configuration for all supported models and quantization settings.
2428
- `src/styles.css`: Custom "glassmorphic" theme.
2529
- `src/types.ts`: Common TypeScript interfaces and enums.
2630

2731
## ⚠️ Architectural Constraints
32+
2833
- **Local-First**: Do NOT attempt to add backend API calls for inference.
2934
- **Web Workers**: Expensive logic (image processing, token generation) MUST stay in the worker.
3035
- **WebGPU Only**: The app target is WebGPU-enabled browsers. Fallback logic is minimal.
3136
- **VRAM Sensitivity**: Be cautious with large models. Use `q4f16` quantization by default.
3237

3338
## 🤝 Contribution Workflow
39+
3440
- Ensure all new logic is fully typed.
3541
- Follow the existing aesthetic: Glassmorphism, CSS variables for colors, and responsive layouts.
3642
- Maintain the single-page, local-only architecture.

CONTRIBUTING.md

Lines changed: 52 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,61 @@
1-
# 🤝 Contributing to Browser LLM Chat
1+
# Contributing to Browser LLM Chat
22

3-
We're delighted you're interested in contributing to **Browser LLM Chat**! This project aims to make high-quality AI accessible to everyone via the browser.
3+
## Setup
44

5-
## How to Help
5+
Use Node `22.x`, then install dependencies:
66

7-
### 🐛 Bug Reports
8-
If you find a bug, please open an issue with:
9-
- A clear description of the problem.
10-
- Your browser and OS version.
11-
- Steps to reproduce.
7+
```bash
8+
npm install
9+
```
1210

13-
### ✨ Feature Requests
14-
We'd love to hear your ideas! If you have a feature in mind, feel free to open a discussion or a pull request.
11+
Run the app locally with:
1512

16-
### 💻 Code Contributions
17-
1. **Fork** the repository and create your branch from `main`.
18-
2. **Install** dependencies: `npm install`.
19-
3. **Run** the development server: `npm run dev`.
20-
4. **Build** to check for errors: `npm run build`.
21-
5. **Commit** your changes with clear, descriptive messages.
22-
6. **Submit** a pull request!
13+
```bash
14+
npm run dev
15+
```
2316

24-
---
17+
## Required Checks
2518

26-
## Technical Standards
27-
- **Local-First**: We never send user data to a backend.
28-
- **Modern UI**: Keep changes consistent with our **glassmorphic** theme.
29-
- **Web Workers**: Always perform expensive tasks in a worker context.
30-
- **TypeScript**: New code must be fully typed.
19+
Before opening a pull request, run:
3120

32-
---
21+
```bash
22+
npm run check
23+
```
3324

34-
Happy contributing! ❤️
25+
That command validates linting, type safety, tests, and the production build.
26+
27+
## Working Rules
28+
29+
- Keep the app local-first. Do not add backend inference calls.
30+
- Keep expensive inference, summarization, and model work inside the worker layer.
31+
- Preserve the current SPA structure. Do not add router-driven page navigation unless explicitly scoped.
32+
- Keep new code fully typed.
33+
- Prefer small focused modules and hooks over growing monolith files.
34+
- Reuse shared helpers for storage, dialog behavior, and model logic instead of duplicating patterns.
35+
36+
## Coding Standards
37+
38+
- ESLint is the source of truth for lint rules.
39+
- Prettier is the source of truth for formatting.
40+
- Prefer type-only imports where possible.
41+
- Add tests for extracted pure logic and regressions when refactoring behavior-heavy code.
42+
43+
## Suggested Workflow
44+
45+
1. Create a branch from `main`.
46+
2. Make focused changes with clear commit scope.
47+
3. Run `npm run check`.
48+
4. Update docs when contributor behavior, scripts, or architecture expectations change.
49+
5. Open a pull request with a concise summary and validation notes.
50+
51+
## Architecture Boundaries
52+
53+
- `src/App.tsx`: app composition and screen orchestration
54+
- `src/store/`: shared app state
55+
- `src/components/`: presentational UI
56+
- `src/hooks/`: reusable React behavior
57+
- `src/worker/`: model runtime domains
58+
- `src/chat-store.ts` and `src/storage.ts`: persistence concerns
59+
- `src/test/`: shared test coverage for app and worker logic
60+
61+
Keep responsibilities aligned with those boundaries when adding new code.

README.md

Lines changed: 63 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1,95 +1,87 @@
1-
# 🌐 Browser LLM Chat
1+
# Browser LLM Chat
22

3-
A high-performance, **100% local-first** React application designed to run Large Language Models directly in your browser. Leveraging **WebGPU** via `@huggingface/transformers`, this experiment brings powerful inference to the client-side with no backend required.
3+
Browser LLM Chat is a fully local-first React application that runs language and vision models directly in the browser with WebGPU. There is no backend inference layer, no API key requirement, and no server-side chat state.
44

5-
![Browser LLM Chat Interface](https://img.shields.io/badge/Status-Experimental-orange)
6-
![WebGPU-Powered](https://img.shields.io/badge/Powered%20By-WebGPU-blue)
7-
![Local-First](https://img.shields.io/badge/Privacy-Local--First-green)
5+
## Highlights
86

9-
---
7+
- Local-first inference with `@huggingface/transformers`
8+
- Web Worker based model loading and token streaming
9+
- Shared app state managed with Zustand
10+
- Chat history persisted locally with IndexedDB and localStorage fallback
11+
- Curated browser-ready models plus searchable Hugging Face discovery
12+
- Built-in settings for generation controls and downloaded-model cleanup
1013

11-
## ✨ Key Features
14+
## Stack
1215

13-
- **🚀 100% Local Inference**: Your prompts, images, and model outputs never leave your browser. Privacy is built-in by design.
14-
- **⚡ WebGPU Accelerated**: Utilizes your GPU's power for near-native performance on compatible browsers (Chrome/Edge Desktop).
15-
- **🧠 Advanced Model Support**: Access to specialized browser-friendly models, including:
16-
- **Balanced (Gemma 3 1B)**: A balanced desktop default for everyday browser chat.
17-
- **Reasoning (DeepSeek R1 1.5B)**: Built-in reasoning capabilities for complex logic via distillation.
18-
- **Coding (Qwen 2.5 Coder)**: Compact coding helpers for quick edits and code explanations.
19-
- **Vision (Qwen 3.5 Vision)**: Fully multimodal support for image-to-text tasks.
20-
- **Fast / Mobile-Safe**: SmolLM2 (360M) and Qwen 2.5 (0.5B) for ultra-quick response times.
21-
- **⚙️ Generation Parameter Controls**: Fine-grained control over model temperature, top-p, and token limits via an intuitive settings dialog.
22-
- **💾 Storage & Chat Management**: Automatic Hugging Face caching, clear chat history, and robust data management to delete offline model files directly from the UI.
23-
- **🧵 Worker-Based Architecture**: Heavy computation happens in a dedicated Web Worker to keep the UI smooth and responsive.
16+
- React 19
17+
- Vite
18+
- TypeScript
19+
- Vanilla CSS
20+
- `@huggingface/transformers` `4.0.0-next.x`
2421

25-
---
22+
## Prerequisites
2623

27-
## 🛠 Tech Stack
24+
- Node.js `22.x`
25+
- A WebGPU-capable browser
26+
Recommended: recent Chrome or Edge desktop builds
2827

29-
- **Core**: [React 19](https://react.dev/), Vite, TypeScript
30-
- **Inference**: [@huggingface/transformers (v4.0.0-next)](https://github.com/huggingface/transformers.js)
31-
- **Styling**: Vanilla CSS (Custom UI with glassmorphism and modern aesthetics)
32-
- **Formatting**: `react-markdown` with `remark-gfm` for rich text and reasoning blocks.
28+
## Getting Started
3329

34-
---
30+
```bash
31+
npm install
32+
npm run dev
33+
```
3534

36-
## 🚀 Getting Started
35+
Open [http://localhost:5173](http://localhost:5173).
3736

38-
### Prerequisites
37+
## Scripts
3938

40-
- A browser with **WebGPU support** (Recommended: Chrome 113+ or Edge 113+ on Desktop).
41-
- [Node.js](https://nodejs.org/) installed.
39+
- `npm run dev`: start the Vite dev server
40+
- `npm run build`: typecheck and build the production bundle
41+
- `npm run preview`: preview the production build locally
42+
- `npm run lint`: run ESLint with zero warnings allowed
43+
- `npm run lint:fix`: apply safe ESLint autofixes
44+
- `npm run format`: format the repo with Prettier
45+
- `npm run format:check`: verify formatting without rewriting files
46+
- `npm run typecheck`: run TypeScript without emitting
47+
- `npm run test`: run the Vitest suite
48+
- `npm run test:watch`: run Vitest in watch mode
49+
- `npm run check`: run lint, typecheck, tests, and build
4250

43-
### Installation
51+
## Architecture Notes
4452

45-
1. **Clone the repository**:
46-
```bash
47-
git clone <repository-url>
48-
cd web-llm
49-
```
53+
- `src/App.tsx` is the top-level composition layer for the SPA shell.
54+
- Shared cross-screen UI, chat, and model state lives in `src/store/app-store.ts`.
55+
- Heavy inference work stays in `src/model.worker.ts` plus the focused worker helpers in `src/worker/`.
56+
- Chat persistence is handled locally through `src/chat-store.ts`.
57+
- Lightweight preferences, storage helpers, and storage feedback live in `src/storage.ts`.
58+
- Tests live in `src/test/` so contributors have one place to look for coverage.
59+
- There is intentionally no router or backend inference path.
5060

51-
2. **Install dependencies**:
52-
```bash
53-
npm install
54-
```
61+
## Quality Gates
5562

56-
3. **Run the development server**:
57-
```bash
58-
npm run dev
59-
```
63+
Pull requests are expected to pass:
6064

61-
4. **Open in Browser**: Navigate to `http://localhost:5173`.
65+
- `npm run lint`
66+
- `npm run typecheck`
67+
- `npm run test`
68+
- `npm run build`
6269

63-
---
70+
GitHub Actions runs the same checks automatically.
6471

65-
## 📝 Notes & Limitations
72+
## Documentation
6673

67-
- **First Load**: The initial model download (200MB - 900MB depending on the model) may take some time depending on your connection.
68-
- **VRAM**: Older GPUs with limited VRAM may struggle with the Vision/Thinking models.
69-
- **Environment**: This is an experimental proof-of-concept.
74+
- [Architecture overview](docs/architecture.md)
75+
- [Model details](docs/models.md)
76+
- [Contributor guide](CONTRIBUTING.md)
77+
- [Agent context](AGENTS.md)
7078

71-
---
79+
## Limitations
7280

73-
## 🤝 Credits
81+
- First-time model downloads can be large and slow on constrained networks.
82+
- Larger models remain sensitive to browser, VRAM, and device class.
83+
- WebGPU support is required for the supported experience.
7484

75-
Special thanks to the **Hugging Face** team for the amazing [transformers.js](https://huggingface.co/docs/transformers.js/index) library and the open-source community for the quantized ONNX models.
85+
## License
7686

77-
---
78-
79-
Built with ❤️ for the future of free, private AI.
80-
81-
---
82-
83-
## 📚 Documentation
84-
85-
- [**🏗️ Architecture & Privacy**](docs/architecture.md): Deep dive into our local-first, WebGPU-powered engine.
86-
- [**🧠 Model Details**](docs/models.md): Understanding the SmolLM and Qwen configurations.
87-
- [**🤖 AI Agent Context**](AGENTS.md): Contextual information for AI coding assistants.
88-
89-
---
90-
91-
## 🤝 Community & Support
92-
93-
- [**Contributing Guidelines**](CONTRIBUTING.md): How to help improve Browser LLM Chat.
94-
- [**Code of Conduct**](CODE_OF_CONDUCT.md): Our commitment to a welcoming environment.
95-
- [**License**](LICENSE): This project is released under the MIT License.
87+
MIT

docs/architecture.md

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,21 @@
55
## Core Components
66

77
### 1. **React UI (Vite + TypeScript)**
8-
The user interface is built with **React 19** and **Vite**, focusing on a clean, responsive, and "glassmorphic" aesthetic. It manages state, chat history, and model selection.
8+
9+
The user interface is built with **React 19** and **Vite**, focusing on a clean, responsive, and "glassmorphic" aesthetic. Shared app state is centralized in a lightweight **Zustand** store, while local component-only draft state remains local to the components that own it.
910

1011
### 2. **WebGPU Acceleration**
12+
1113
The application uses the **WebGPU API** to leverage the user's graphics hardware for model inference. This provides near-native performance for transformer-based models by utilizing the parallel processing power of modern GPUs.
1214

1315
### 3. **Web Worker Threading**
14-
To ensure a smooth UI experience, all heavy lifting (model loading, processing, and inference) is offloaded to a **dedicated Web Worker** (`model.worker.ts`). Communication between the UI and the worker happens asynchronously via the `postMessage` API.
16+
17+
To ensure a smooth UI experience, all heavy lifting (model loading, processing, summarization, and inference) is offloaded to a **dedicated Web Worker** (`model.worker.ts`). Communication between the UI and the worker happens asynchronously via the `postMessage` API. The worker is kept intentionally coarse-grained: the entry file handles message routing, while a small `src/worker/` set owns model session state, conversation budgeting, and generation logic.
1518

1619
### 4. **Transformers.js (v4.0.0-next)**
20+
1721
We use the `@huggingface/transformers` library to handle:
22+
1823
- **ONNX Model Loading**: Loading quantized model weights.
1924
- **Tokenization**: Converting text to numerical input.
2025
- **Inference**: Running the model and streaming output tokens.
@@ -24,18 +29,35 @@ We use the `@huggingface/transformers` library to handle:
2429
## 🔒 Security & Privacy
2530

2631
### **100% Local-First**
32+
2733
- **No Data Leakage**: Your prompts, images, and model outputs never leave your machine. There is no backend telemetry or logging of your conversations.
2834
- **Offline Capable**: Once the model weights are downloaded into the browser cache, the application can run fully offline.
2935

3036
### **Model Provenance**
37+
3138
- Models are fetched directly from the [Hugging Face Hub](https://huggingface.co/models). We use official and community-quantized versions of reputable models (SmolLM, Qwen).
3239

3340
### **Safe Model Execution**
41+
3442
- The models run within the browser's sandboxed environment. They cannot access your local file system (except through explicit user-provided file uploads) or other browser data.
3543

3644
---
3745

3846
## 💡 Local Inference Benefits
47+
3948
- **Zero Latency**: No network round-trips for inference.
4049
- **Privacy By Design**: Ideal for sensitive or personal queries.
4150
- **Cost Effective**: No expensive GPU server hosting required.
51+
52+
---
53+
54+
## 📁 Project Layout
55+
56+
- `src/App.tsx`: SPA shell composition and screen orchestration
57+
- `src/store/app-store.ts`: shared app state and actions
58+
- `src/components/`: visible UI sections and dialogs
59+
- `src/hooks/`: reusable React behaviors that are shared across screens
60+
- `src/chat-store.ts`: durable chat persistence and legacy thread migration
61+
- `src/storage.ts`: lightweight browser state and storage feedback helpers
62+
- `src/model.worker.ts` + `src/worker/`: inference runtime
63+
- `src/test/`: centralized app and worker tests

0 commit comments

Comments
 (0)