diff --git a/AGENTS.md b/AGENTS.md
index 548e869..09a9f24 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -38,9 +38,11 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useNWC`: Nostr Wallet Connect connection management
- `useNWCContext`: Access NWC context provider
- `useShakespeare`: AI chat completions with Shakespeare AI API
+ - `useDMContext`: Direct messaging system (NIP-04 & NIP-17)
+ - `useConversationMessages`: Paginated messages for specific conversations
- `/src/pages/`: Page components used by React Router (Index, NotFound)
- `/src/lib/`: Utility functions and shared logic
-- `/src/contexts/`: React context providers (AppContext, NWCContext)
+- `/src/contexts/`: React context providers (AppContext, NWCContext, DMContext)
- `/src/test/`: Testing utilities including TestApp component
- `/public/`: Static assets
- `App.tsx`: Main app component with provider setup
@@ -109,6 +111,8 @@ The project includes a **`docs/`** directory containing specialized documentatio
- **`docs/NOSTR_INFINITE_SCROLL.md`**: Read when building feed interfaces, implementing pagination for Nostr events, or creating social media-style infinite scroll experiences.
+- **`docs/NOSTR_DIRECT_MESSAGES.md`**: Read when implementing direct messaging features, building chat interfaces, or working with encrypted peer-to-peer communication (NIP-04 and NIP-17).
+
## System Prompt Management
The AI assistant's behavior and knowledge is defined by the AGENTS.md file, which serves as the system prompt. To modify the assistant's instructions or add new project-specific guidelines:
@@ -744,6 +748,74 @@ function EditProfilePage() {
The `EditProfileForm` component displays just the form. It requires no props, and will "just work" automatically.
+### Direct Messaging (NIP-04 & NIP-17)
+
+The project includes a complete direct messaging system with real-time updates, encrypted storage, and support for both NIP-04 (legacy) and NIP-17 (modern private messaging) protocols.
+
+**Quick Setup:**
+
+```tsx
+import { DMProvider } from '@/contexts/DMContext';
+import { PROTOCOL_MODE } from '@/lib/dmConstants';
+
+// Wrap your app with DMProvider
+
+ {children}
+
+```
+
+**Send Messages:**
+
+```tsx
+import { useDMContext } from '@/contexts/DMContext';
+import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
+
+function MyComponent() {
+ const { sendMessage } = useDMContext();
+
+ await sendMessage({
+ recipientPubkey: 'hex-pubkey',
+ content: 'Hello!',
+ protocol: MESSAGE_PROTOCOL.NIP17 // or NIP04
+ });
+}
+```
+
+**Display Conversations:**
+
+```tsx
+const { conversations, isLoading } = useDMContext();
+
+// conversations = Array of conversation summaries with:
+// - pubkey: The other participant
+// - lastMessage: Most recent message
+// - lastActivity: Unix timestamp
+// - isKnown: User has sent messages
+// - isRequest: Only received messages
+```
+
+**Display Messages:**
+
+```tsx
+import { useConversationMessages } from '@/contexts/DMContext';
+
+const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(pubkey);
+
+// messages = Paginated array of messages (25/page)
+// hasMoreMessages = true if earlier messages available
+// loadEarlierMessages() = Load next 25 messages
+```
+
+**Features:**
+- **Dual Protocol Support**: NIP-04 (legacy) and NIP-17 (private with gift wrapping)
+- **Real-time Updates**: WebSocket subscriptions for live messages
+- **Encrypted Storage**: IndexedDB with NIP-44 encryption
+- **Optimistic UI**: Instant message display with background confirmation
+- **File Attachments**: Full support with `attachments` parameter
+- **Cache-First Loading**: Instant UI with background sync
+
+For complete implementation details, file attachments, and advanced features, see **`docs/NOSTR_DIRECT_MESSAGES.md`**.
+
### Uploading Files on Nostr
Use the `useUploadFile` hook to upload files. This hook uses Blossom servers for file storage and returns NIP-94 compatible tags.
diff --git a/docs/NOSTR_DIRECT_MESSAGES.md b/docs/NOSTR_DIRECT_MESSAGES.md
new file mode 100644
index 0000000..a75092c
--- /dev/null
+++ b/docs/NOSTR_DIRECT_MESSAGES.md
@@ -0,0 +1,330 @@
+### Direct Messaging on Nostr
+
+This project includes a complete direct messaging system supporting both NIP-04 (legacy) and NIP-17 (modern, - more - private) encrypted messages with real-time subscriptions, optimistic updates, and a persistent - cache first - local storage.
+
+## Quick Start
+
+### 1. Wrap Your App with DMProvider
+
+```tsx
+import { DMProvider } from '@/contexts/DMContext';
+import { PROTOCOL_MODE } from '@/lib/dmConstants';
+
+function App() {
+ return (
+
+ {/* Your app components */}
+
+ );
+}
+```
+
+**Protocol Modes:**
+- `PROTOCOL_MODE.NIP04_ONLY` - Legacy encryption only
+- `PROTOCOL_MODE.NIP17_ONLY` - Modern private messages (recommended)
+- `PROTOCOL_MODE.BOTH` - Support both protocols
+
+### 2. Send Messages
+
+```tsx
+import { useDMContext } from '@/contexts/DMContext';
+import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
+
+function ComposeMessage({ recipientPubkey }: { recipientPubkey: string }) {
+ const { sendMessage } = useDMContext();
+ const [content, setContent] = useState('');
+
+ const handleSend = async () => {
+ await sendMessage({
+ recipientPubkey,
+ content,
+ protocol: MESSAGE_PROTOCOL.NIP17, // Uses NIP-44 encryption + gift wrapping
+ });
+ setContent('');
+ };
+
+ return (
+
+ );
+}
+```
+
+### 3. Display Conversations
+
+```tsx
+import { useDMContext } from '@/contexts/DMContext';
+import { useAuthor } from '@/hooks/useAuthor';
+import { genUserName } from '@/lib/genUserName';
+
+function ConversationList({ onSelectConversation }: { onSelectConversation: (pubkey: string) => void }) {
+ const { conversations, isLoading } = useDMContext();
+
+ if (isLoading) {
+ return Loading conversations...
;
+ }
+
+ return (
+
+ {conversations.map((conversation) => (
+ onSelectConversation(conversation.pubkey)}
+ />
+ ))}
+
+ );
+}
+
+function ConversationItem({ conversation, onClick }: {
+ conversation: ConversationSummary;
+ onClick: () => void;
+}) {
+ const author = useAuthor(conversation.pubkey);
+ const displayName = author.data?.metadata?.name || genUserName(conversation.pubkey);
+ const avatarUrl = author.data?.metadata?.picture;
+
+ return (
+
+ );
+}
+```
+
+### 4. Display Messages in a Conversation
+
+```tsx
+import { useConversationMessages } from '@/contexts/DMContext';
+import { useCurrentUser } from '@/hooks/useCurrentUser';
+
+function MessageThread({ conversationPubkey }: { conversationPubkey: string }) {
+ const { user } = useCurrentUser();
+ const { messages, hasMoreMessages, loadEarlierMessages } = useConversationMessages(conversationPubkey);
+
+ return (
+
+ {hasMoreMessages && (
+
+ )}
+
+ {messages.map((message) => {
+ const isFromMe = message.pubkey === user?.pubkey;
+
+ return (
+
+
+ {message.error ? (
+
🔒 {message.error}
+ ) : (
+
+ {message.decryptedContent}
+
+ )}
+ {message.isSending && (
+
Sending...
+ )}
+
+
+ );
+ })}
+
+ );
+}
+```
+
+## Sending Files with Messages
+
+```tsx
+import { useDMContext, type FileAttachment } from '@/contexts/DMContext';
+import { useUploadFile } from '@/hooks/useUploadFile';
+import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
+
+function ComposeWithFiles({ recipientPubkey }: { recipientPubkey: string }) {
+ const { sendMessage } = useDMContext();
+ const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
+ const [content, setContent] = useState('');
+ const [selectedFile, setSelectedFile] = useState(null);
+
+ const handleSend = async () => {
+ let attachments: FileAttachment[] | undefined;
+
+ // Upload file if one is selected
+ if (selectedFile) {
+ const tags = await uploadFile(selectedFile);
+
+ attachments = [{
+ url: tags[0][1], // URL from first tag
+ mimeType: selectedFile.type,
+ size: selectedFile.size,
+ name: selectedFile.name,
+ tags: tags
+ }];
+ }
+
+ await sendMessage({
+ recipientPubkey,
+ content,
+ protocol: MESSAGE_PROTOCOL.NIP17,
+ attachments,
+ });
+
+ setContent('');
+ setSelectedFile(null);
+ };
+
+ return (
+
+ );
+}
+```
+
+## Protocol Comparison
+
+### NIP-04 (Legacy)
+- **Encryption**: NIP-04 (simpler, older)
+- **Metadata**: Sender and recipient visible to relays
+- **Event Kind**: Kind 4
+- **Use When**: Compatibility with older clients
+
+### NIP-17 (Modern & Private)
+- **Encryption**: NIP-44 (stronger)
+- **Metadata**: Hidden via gift wrapping (NIP-59)
+- **Event Kinds**: Kind 14 (text), Kind 15 (files)
+- **Wrapped In**: Kind 1059 (Gift Wrap) with ephemeral keys
+- **Use When**: Maximum privacy (recommended)
+
+**Key Privacy Features of NIP-17:**
+- Sender identity hidden (uses random ephemeral keys)
+- Timestamps randomized (±2 days) to hide send time
+- Dual gift wraps (recipient + sender) for message history
+
+## Advanced Features
+
+### Conversation Categorization
+
+The system automatically categorizes conversations:
+
+```tsx
+const { conversations } = useDMContext();
+
+// Filter by category
+const knownConversations = conversations.filter(c => c.isKnown);
+const requestConversations = conversations.filter(c => c.isRequest);
+
+// isKnown = true if user has sent at least one message
+// isRequest = true if only received messages, never replied
+```
+
+### Loading States
+
+```tsx
+const { isLoading, loadingPhase, scanProgress } = useDMContext();
+
+// Check overall loading state
+if (isLoading) {
+ console.log('Current phase:', loadingPhase);
+ // LOADING_PHASES.CACHE - Loading from local cache
+ // LOADING_PHASES.RELAYS - Querying relays
+ // LOADING_PHASES.SUBSCRIPTIONS - Setting up real-time updates
+ // LOADING_PHASES.READY - Fully loaded
+}
+
+// Display scan progress for large message histories
+if (scanProgress.nip17) {
+ console.log(`NIP-17: ${scanProgress.nip17.current} messages - ${scanProgress.nip17.status}`);
+}
+```
+
+### Clear Cache and Refresh
+
+```tsx
+import { useDMContext } from '@/contexts/DMContext';
+
+function SettingsButton() {
+ const { clearCacheAndRefetch } = useDMContext();
+
+ const handleClearCache = async () => {
+ await clearCacheAndRefetch();
+ // Clears IndexedDB cache and reloads all messages from relays
+ };
+
+ return (
+
+ );
+}
+```
+
+## Architecture Notes
+
+### Data Flow
+1. **Cache First**: Messages load instantly from encrypted IndexedDB cache
+2. **Background Sync**: New messages fetched from relays in parallel
+3. **Real-time Updates**: WebSocket subscriptions for live messages
+4. **Optimistic UI**: Sent messages appear immediately, confirmed on relay response
+
+### Storage
+- **IndexedDB**: All messages stored locally with NIP-44 encryption
+- **Per-User Storage**: Separate encrypted store for each logged-in user
+- **Automatic Sync**: Debounced writes (15s) + immediate on new messages
+
+### Performance
+- **Parallel Queries**: NIP-04 and NIP-17 messages fetched simultaneously
+- **Batched Loading**: Messages loaded in batches (1000/batch, 20k limit)
+- **Pagination**: Conversation messages paginated (25/page)
+- **Deduplication**: Automatic filtering of duplicate messages by ID
+
+### Security
+- **NIP-44 Encryption**: Modern authenticated encryption for all NIP-17 messages
+- **Local Encryption**: IndexedDB storage encrypted with user's NIP-44 key
+- **Ephemeral Keys**: Random keys for NIP-17 gift wraps (sender anonymity)
+- **No Plaintext**: Decrypted content never persisted unencrypted
+
diff --git a/src/contexts/DMContext.tsx b/src/contexts/DMContext.tsx
index 14836ca..6027fde 100644
--- a/src/contexts/DMContext.tsx
+++ b/src/contexts/DMContext.tsx
@@ -116,6 +116,21 @@ const createErrorLogger = (name: string) => {
const nip17ErrorLogger = createErrorLogger('NIP-17');
+/**
+ * Direct Messaging context interface providing access to all DM functionality.
+ *
+ * @property messages - Raw message state (Map of pubkey -> participant data)
+ * @property isLoading - True during initial load phases
+ * @property loadingPhase - Current loading phase (CACHE, RELAYS, SUBSCRIPTIONS, READY, IDLE)
+ * @property isDoingInitialLoad - True only during cache/relay loading (not subscriptions)
+ * @property lastSync - Unix timestamps of last successful sync for each protocol
+ * @property subscriptions - Connection status for real-time message subscriptions
+ * @property conversations - Array of conversation summaries sorted by last activity
+ * @property sendMessage - Send an encrypted direct message (NIP-04 or NIP-17)
+ * @property protocolMode - Current protocol mode (NIP04_ONLY, NIP17_ONLY, or BOTH)
+ * @property scanProgress - Progress info for large message history scans
+ * @property clearCacheAndRefetch - Clear IndexedDB cache and reload all messages from relays
+ */
interface DMContextType {
messages: MessagesState;
isLoading: boolean;
@@ -137,6 +152,41 @@ interface DMContextType {
const DMContext = createContext(null);
+/**
+ * Hook to access the direct messaging system.
+ *
+ * Provides access to conversations, message sending, loading states, and cache management.
+ * Must be used within a DMProvider.
+ *
+ * @example
+ * ```tsx
+ * import { useDMContext } from '@/contexts/DMContext';
+ * import { MESSAGE_PROTOCOL } from '@/lib/dmConstants';
+ *
+ * function MyComponent() {
+ * const { conversations, sendMessage, isLoading } = useDMContext();
+ *
+ * // Send a message
+ * await sendMessage({
+ * recipientPubkey: 'hex-pubkey',
+ * content: 'Hello!',
+ * protocol: MESSAGE_PROTOCOL.NIP17
+ * });
+ *
+ * // Display conversations
+ * return (
+ *
+ * {isLoading ? 'Loading...' : conversations.map(c => (
+ *
{c.lastMessage?.decryptedContent}
+ * ))}
+ *
+ * );
+ * }
+ * ```
+ *
+ * @returns DMContextType - The direct messaging context
+ * @throws Error if used outside DMProvider
+ */
export function useDMContext(): DMContextType {
const context = useContext(DMContext);
if (!context) {
@@ -147,6 +197,42 @@ export function useDMContext(): DMContextType {
const MESSAGES_PER_PAGE = 25;
+/**
+ * Hook to access paginated messages for a specific conversation.
+ *
+ * Returns the most recent messages (default 25) with the ability to load earlier messages.
+ * Automatically resets to default page size when switching conversations.
+ *
+ * @example
+ * ```tsx
+ * import { useConversationMessages } from '@/contexts/DMContext';
+ *
+ * function MessageThread({ recipientPubkey }: { recipientPubkey: string }) {
+ * const {
+ * messages,
+ * hasMoreMessages,
+ * loadEarlierMessages,
+ * totalCount
+ * } = useConversationMessages(recipientPubkey);
+ *
+ * return (
+ *
+ * {hasMoreMessages && (
+ *
+ * )}
+ * {messages.map(msg => (
+ *
{msg.decryptedContent}
+ * ))}
+ *
+ * );
+ * }
+ * ```
+ *
+ * @param conversationId - The pubkey of the conversation participant
+ * @returns Paginated message data with loading function
+ */
export function useConversationMessages(conversationId: string) {
const { messages: allMessages } = useDMContext();
const [visibleCount, setVisibleCount] = useState(MESSAGES_PER_PAGE);
@@ -208,6 +294,41 @@ interface DMProviderProps {
// Message Sending Types and Helpers (Internal)
// ============================================================================
+/**
+ * File attachment for direct messages (NIP-92 compatible).
+ *
+ * All fields are required. Use with `useUploadFile` hook to upload files
+ * and generate the proper tags format.
+ *
+ * @example
+ * ```tsx
+ * import { useUploadFile } from '@/hooks/useUploadFile';
+ * import type { FileAttachment } from '@/contexts/DMContext';
+ *
+ * const { mutateAsync: uploadFile } = useUploadFile();
+ *
+ * const tags = await uploadFile(file);
+ * const attachment: FileAttachment = {
+ * url: tags[0][1],
+ * mimeType: file.type,
+ * size: file.size,
+ * name: file.name,
+ * tags: tags
+ * };
+ *
+ * await sendMessage({
+ * recipientPubkey: 'hex-pubkey',
+ * content: 'Check out this file!',
+ * attachments: [attachment]
+ * });
+ * ```
+ *
+ * @property url - Blossom server URL where file is hosted
+ * @property mimeType - MIME type of the file (e.g., 'image/png')
+ * @property size - File size in bytes
+ * @property name - Original filename
+ * @property tags - NIP-94 file metadata tags (includes hashes)
+ */
export interface FileAttachment {
url: string;
mimeType: string;