# Chat History Persistence & Cross-Device Sync ## New File: `src/chat-history.ts` - Added `PersistedMessage` and `ChatHistoryData` interfaces for typed storage - `loadChatHistory()` — reads from `chat-history.json` in the plugin folder via `vault.adapter` - `saveChatHistory()` — writes user/assistant messages to disk (strips system/tool messages) - `clearChatHistory()` — writes an empty history file (not deletion) for reliable Obsidian Sync propagation - `toPersistableMessages()` / `toRuntimeMessages()` — conversion between runtime `ChatMessage[]` and storage format - `isValidChatHistory()` — strict type guard for safe JSON parsing with version check ## Modified: `src/chat-view.ts` - On **open**: restores persisted chat history, renders user messages as plain text and assistant messages as markdown (with wiki-link navigation) - On **message send**: debounced save (500ms) after user message and after assistant response completes - On **close**: flushes pending save and cleans up debounce timer - On **clear chat**: writes empty history file and updates sync snapshot - Added `reloadChatHistory()` public method for external sync triggers; skips reload if streaming is active to avoid UI disruption - Added `saveChatHistoryDebounced()` with snapshot update to prevent false sync reloads from local writes ## Modified: `src/main.ts` - Added `onExternalSettingsChange()` — reloads settings and checks for chat history changes when Obsidian Sync updates `data.json` - Added `visibilitychange` DOM event listener — checks for synced changes when the app regains focus (covers device switching) - Added `checkChatHistorySync()` — snapshot-based change detection that reloads the chat view only when the persisted file differs from the known state - Added `updateChatSnapshot()` — called after local saves and restores to prevent false sync triggers - Added `buildChatSnapshot()` helper — lightweight string comparison using message count and last message content