Convex API Queries & Mutations
Relevant source files
The following files were used as context for generating this wiki page:
The Convex backend architecture in OpenChat serves as a real-time data layer, managing the core state for chat sessions, user profiles, and security configurations. It utilizes a serverless function model categorized into public Queries (read-only), Mutations (read-write), and Actions (side-effect heavy operations). This system ensures data consistency through ACID transactions within mutations and provides real-time reactivity for the frontend.
The API is structured to handle high-level entities such as users, chats, and messages while maintaining secure access through authentication helpers and internal functions. It also manages complex tasks like encrypted API key storage and automated email notifications for scheduled AI tasks.
Sources: CLAUDE.md:85-100, agent_rules/convex_rules.md:1-15
Core Data Architecture
The system utilizes a modular schema where each major feature has a dedicated table definition. These tables are indexed to support efficient querying, particularly for user-specific data and time-ordered message history.
Database Schema Overview
| Table | Primary Indices | Purpose |
|---|---|---|
users | email | Stores user profiles and preferences. |
chats | by_user | Manages individual chat sessions. |
messages | by_chat_and_created, by_user | Stores conversation history with search capabilities. |
user_api_keys | by_user_provider | Stores encrypted external AI provider keys. |
scheduled_tasks | by_user, by_next_execution | Manages background AI agents. |
Sources: convex/schema.ts:14-43
Entity Relationship Diagram
This diagram illustrates how core entities are related within the Convex database, primarily centered around the users table.
Sources: convex/schema.ts:14-43
Query Implementation
Queries are deterministic, read-only functions used to fetch state for the frontend. OpenChat utilizes indices (via withIndex) and full-text search (via searchIndex) to ensure performance at scale.
Chat and Message Retrieval
Queries like getApiKeys demonstrate the pattern of fetching data scoped to the currently authenticated user. In the context of messages, queries are often ordered by _creationTime to maintain conversation flow.
Key Query Functions
getApiKeys: Retrieves metadata for stored provider keys (e.g., OpenAI, Anthropic) without exposing the secret keys directly. Sources: convex/api_keys.ts:133-157getDecryptedKey: An internal-facing query that retrieves and decrypts a specific provider key for use in AI Actions. Sources: convex/api_keys.ts:241-267
Mutation Implementation
Mutations are the only functions allowed to modify the database state. They are transactional, meaning if any part of the function fails, the entire transaction is rolled back.
Secure API Key Management
The saveApiKey mutation illustrates the system's security focus. It encrypts the user's provided key using AES-GCM 256-bit encryption before storing it in the user_api_keys table.
// Example of a secure mutation pattern
export const saveApiKey = mutation({
args: { provider: v.string(), key: v.string(), mode: v.optional(v.string()) },
handler: async (ctx, { provider, key, mode }) => {
const userId = await getAuthUserId(ctx);
if (!userId) throw new ConvexError("NOT_AUTHENTICATED");
const encrypted = await encrypt(key, userId);
// ... check existing and patch or insert
},
});
Sources: convex/api_keys.ts:169-204
Data Modification Operations
patch: Used for shallow merging updates, such as updating a key'susageCountormode. Sources: convex/api_keys.ts:194, convex/api_keys.ts:300insert: Used to create new records, such as adding a new chat or message. Sources: convex/api_keys.ts:200delete: Used for removal, such as clearing a provider key. Sources: convex/api_keys.ts:228
Side-Effects and Actions
Actions are used for non-deterministic code, such as calling external AI APIs or sending emails. They cannot directly modify the database and must call mutations to persist results.
Email Notification System
The sendTaskSummaryEmail internal mutation (which triggers a Resend action) handles the conversion of markdown task outputs into sanitized HTML for user notifications.
Sources: convex/email.ts:70-120
Security Constraints in Actions
Actions often use "node" runtimes (via "use node") to access specific libraries like crypto or Resend. They interact with the database indirectly through ctx.runQuery and ctx.runMutation. Sources: agent_rules/convex_rules.md:230-245
Summary
The Convex API in OpenChat provides a robust, type-safe backend that prioritizes security and real-time performance. By separating concerns into Queries for reading, Mutations for atomic writes, and Actions for external integrations, the system maintains a clean data flow. The use of AES-GCM encryption for API keys and a centralized schema with optimized indices ensures that the application remains both secure and responsive as the volume of chat data grows.