Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: digital twin voice drafting for email replies (M50 P8)
Adam Eivy444185cf7881
diff --git a/client/src/components/messages/ConfigTab.jsx b/client/src/components/messages/ConfigTab.jsxindex 668e2abf12..09fdd298ad 100644--- a/client/src/components/messages/ConfigTab.jsx+++ b/client/src/components/messages/ConfigTab.jsx@@ -1,5 +1,5 @@import { useState, useEffect, useCallback } from 'react';-import { Plus, Trash2, RefreshCw, Mail, Globe, MessageSquare, Save, ExternalLink } from 'lucide-react';+import { Plus, Trash2, RefreshCw, Mail, Globe, MessageSquare, Save, ExternalLink, User } from 'lucide-react';import toast from 'react-hot-toast';import * as api from '../../services/api';import ProviderModelSelector from '../ProviderModelSelector';@@ -74,7 +74,8 @@ export default function ConfigTab({ accounts, setAccounts }) {const replyConfig = msgConfig.reply || {};setConfig({replyTemplate: msgConfig.replyTemplate || DEFAULT_REPLY_TEMPLATE,- forwardTemplate: msgConfig.forwardTemplate || DEFAULT_FORWARD_TEMPLATE+ forwardTemplate: msgConfig.forwardTemplate || DEFAULT_FORWARD_TEMPLATE,+ voiceMode: msgConfig.voiceMode ?? false});// Restore saved provider/model - per-action configs with legacy fallbackconst triageProviderId = triageConfig.providerId || msgConfig.providerId;@@ -124,7 +125,8 @@ export default function ConfigTab({ accounts, setAccounts }) {model: replySelectedModel},replyTemplate: config.replyTemplate,- forwardTemplate: config.forwardTemplate+ forwardTemplate: config.forwardTemplate,+ voiceMode: config.voiceMode}};const result = await api.updateSettings(patch).catch(() => null);@@ -412,6 +414,33 @@ export default function ConfigTab({ accounts, setAccounts }) {</div></section>+ <section>+ <h2 className="text-lg font-semibold text-white mb-3">Digital Twin Voice</h2>+ <div className="p-4 bg-port-card rounded-lg border border-port-border">+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-3">+ <User size={20} className={config?.voiceMode ? 'text-purple-400' : 'text-gray-600'} />+ <div>+ <div className="text-sm font-medium text-white">Voice Mode</div>+ <div className="text-xs text-gray-500">+ Draft replies in your voice using Digital Twin personality documents (Soul, Communication, Personality, Values, Social)+ </div>+ </div>+ </div>+ <button+ onClick={() => { setConfig(prev => ({ ...prev, voiceMode: !prev.voiceMode })); setConfigDirty(true); }}+ className={`px-3 py-1.5 rounded text-xs font-medium transition-colors ${+ config?.voiceMode+ ? 'bg-purple-500/20 text-purple-400'+ : 'bg-gray-700 text-gray-400'+ }`}+ >+ {config?.voiceMode ? 'Enabled' : 'Disabled'}+ </button>+ </div>+ </div>+ </section>+{/* Prompt Templates */}<section><h2 className="text-lg font-semibold text-white mb-3">Prompt Templates</h2>diff --git a/client/src/components/messages/MessageDetail.jsx b/client/src/components/messages/MessageDetail.jsxindex bcd2b73ae5..fec7f7e38f 100644--- a/client/src/components/messages/MessageDetail.jsx+++ b/client/src/components/messages/MessageDetail.jsx@@ -1,5 +1,5 @@import { useState, useEffect, useRef, useCallback } from 'react';-import { ArrowLeft, Reply, Sparkles, Send, RefreshCw, Archive, Trash2 } from 'lucide-react';+import { ArrowLeft, Reply, Sparkles, Send, RefreshCw, Archive, Trash2, User } from 'lucide-react';import toast from 'react-hot-toast';import * as api from '../../services/api';@@ -67,12 +67,20 @@ export default function MessageDetail({ message, accounts, onBack }) {const [refreshing, setRefreshing] = useState(false);const [displayedMessage, setDisplayedMessage] = useState(message);const [actioning, setActioning] = useState(null);+ const [useVoice, setUseVoice] = useState(false);// Sync displayedMessage when the message prop changes (e.g., selecting a different message)useEffect(() => {setDisplayedMessage(message);}, [message]);+ // Load voice mode default from settings+ useEffect(() => {+ api.getSettings()+ .then(s => setUseVoice(s?.messages?.voiceMode ?? false))+ .catch(() => {});+ }, []);+const account = accounts.find(a => a.id === displayedMessage.accountId) || accounts[0];// Load thread messages if this message is part of a thread@@ -107,14 +115,15 @@ export default function MessageDetail({ message, accounts, onBack }) {replyToMessageId: displayedMessage.id,threadId: displayedMessage.threadId,context: `Replying to: "${displayedMessage.subject}" from ${displayedMessage.from?.name || displayedMessage.from?.email}`,- instructions: ''+ instructions: '',+ useVoice: useVoice ?? undefined}).catch(() => null);setGenerating(false);if (draft) {setReplyBody(draft.body);setGeneratedDraftId(draft.id);setShowReply(true);- toast.success('AI draft generated');+ toast.success(useVoice ? 'AI draft generated with your voice' : 'AI draft generated');}};@@ -169,6 +178,7 @@ export default function MessageDetail({ message, accounts, onBack }) {</div><div className="flex items-center gap-1 shrink-0"><button onClick={() => setShowReply(!showReply)} className="p-1.5 text-port-accent hover:bg-port-accent/10 rounded transition-colors" title="Reply"><Reply size={14} /></button>+ <button onClick={() => setUseVoice(v => !v)} className={`p-1.5 rounded transition-colors ${useVoice ? 'text-purple-400 bg-purple-500/10' : 'text-gray-500 hover:text-gray-300'}`} title={useVoice ? 'Voice mode ON — replies use your Digital Twin voice' : 'Voice mode OFF — replies use generic tone'}><User size={14} /></button><button onClick={handleGenerateReply} disabled={generating} className="p-1.5 text-purple-400 hover:bg-purple-500/10 rounded transition-colors disabled:opacity-50" title="AI Reply"><Sparkles size={14} className={generating ? 'animate-pulse' : ''} /></button><button onClick={handleRefresh} disabled={refreshing} className="p-1.5 text-port-accent hover:bg-port-accent/10 rounded transition-colors disabled:opacity-50" title="Refresh"><RefreshCw size={14} className={refreshing ? 'animate-spin' : ''} /></button><span className="w-px h-4 bg-port-border mx-0.5" />diff --git a/server/routes/messages.js b/server/routes/messages.jsindex 22dff5e6fb..b3063a2ea5 100644--- a/server/routes/messages.js+++ b/server/routes/messages.js@@ -62,7 +62,8 @@ const generateDraftSchema = z.object({replyToMessageId: z.string().nullish(),threadId: z.string().nullish(),context: z.string().optional().default(''),- instructions: z.string().optional().default('')+ instructions: z.string().optional().default(''),+ useVoice: z.boolean().optional()});const updateSelectorsSchema = z.object({@@ -219,7 +220,15 @@ router.post('/drafts/generate', asyncHandler(async (req, res) => {if (data.replyToMessageId) {const originalMsg = await messageSync.getMessage(data.accountId, data.replyToMessageId);if (originalMsg) {- const aiResult = await generateReplyBody(originalMsg, data.instructions).catch(err => {+ // Load thread context if available+ let threadMessages = null;+ if (data.threadId) {+ threadMessages = await messageSync.getThread(data.accountId, data.threadId).catch(() => null);+ }+ const aiResult = await generateReplyBody(originalMsg, data.instructions, {+ useVoice: data.useVoice,+ threadMessages+ }).catch(err => {console.log(`📧 AI reply generation failed, using placeholder: ${err.message}`);return null;});diff --git a/server/services/messageEvaluator.js b/server/services/messageEvaluator.jsindex 090aa4a279..f70b1b73f3 100644--- a/server/services/messageEvaluator.js+++ b/server/services/messageEvaluator.js@@ -1,7 +1,10 @@+import { readFile } from 'fs/promises';+import { join } from 'path';import { getSettings } from './settings.js';import { getProviderById, getAllProviders } from './providers.js';import { createRun, executeApiRun, executeCliRun } from './runner.js';import { buildRulesPromptSection } from './messageTriageRules.js';+import { PATHS } from '../lib/fileUtils.js';const EVAL_PROMPT = `You are an email triage assistant. For each email below, recommend ONE action and a brief reason.@@ -138,15 +141,66 @@ export async function evaluateMessages(messages) {return { evaluations };}+// Voice document filenames ordered by relevance for email drafting+const VOICE_DOCS = ['SOUL.md', 'COMMUNICATION.md', 'PERSONALITY.md', 'VALUES.md', 'SOCIAL.md'];++/**+ * Load digital twin voice context documents for email drafting.+ * Returns a formatted prompt section with the user's communication style and personality.+ */+async function loadVoiceContext() {+ const contents = await Promise.all(+ VOICE_DOCS.map(filename =>+ readFile(join(PATHS.digitalTwin, filename), 'utf-8').catch(() => null)+ )+ );+ const sections = contents+ .map((content, i) => content?.trim() ? `### ${VOICE_DOCS[i].replace('.md', '')}\n${content.trim()}` : null)+ .filter(Boolean);+ if (!sections.length) {+ console.log('📧 Voice mode enabled but no digital twin documents found');+ return '';+ }+ return `\n<voice_context>+The following documents describe the user's identity, communication style, and values.+Write the reply in their authentic voice — match their tone, directness, and personality.+Do NOT mention these documents or that you are an AI.++${sections.join('\n\n')}+</voice_context>\n`;+}++/**+ * Format thread messages into conversation context for the AI.+ */+function buildThreadContext(threadMessages) {+ if (!threadMessages?.length) return '';+ const formatted = threadMessages.map(m => {+ const from = m.from?.name || m.from?.email || 'Unknown';+ const date = m.date ? new Date(m.date).toLocaleString() : '';+ const body = sanitize((m.bodyText || '').slice(0, 500));+ return `[${date}] ${sanitize(from)}:\n${body}`;+ }).join('\n---\n');+ return `\n<thread_context>+Previous messages in this conversation:+${formatted}+</thread_context>\n`;+}+/*** Generate an AI reply draft for a message.* @param {object} message - The message to reply to* @param {string} instructions - Additional instructions+ * @param {object} options - { useVoice, threadMessages }* @returns {{ body: string }}*/-export async function generateReplyBody(message, instructions = '') {+export async function generateReplyBody(message, instructions = '', options = {}) {+ const { useVoice, threadMessages } = options;const { provider, model, msgConfig } = await resolveProviderConfig('reply');+ // Determine if voice mode is active (explicit param > settings default)+ const shouldUseVoice = useVoice ?? msgConfig.voiceMode ?? false;+// Build prompt from templatelet template = msgConfig.replyTemplate || 'Write a professional reply to this email.\n\nFrom: {{from}}\nSubject: {{subject}}\nBody:\n{{body}}';// Sanitize untrusted email content to prevent prompt injection@@ -165,7 +219,18 @@ export async function generateReplyBody(message, instructions = '') {return vars[key] ? block.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), vars[key]) : '';});- console.log(`📧 Generating AI reply with ${provider.name}/${model || provider.defaultModel}`);+ // Prepend voice context if enabled+ if (shouldUseVoice) {+ const voiceContext = await loadVoiceContext();+ if (voiceContext) template = voiceContext + template;+ }++ // Append thread context if available+ const threadContext = buildThreadContext(threadMessages);+ if (threadContext) template += threadContext;++ const voiceLabel = shouldUseVoice ? ' with voice' : '';+ console.log(`📧 Generating AI reply${voiceLabel} with ${provider.name}/${model || provider.defaultModel}`);const response = await runPrompt(provider, model, template, 'messages-reply');return { body: response.trim() };}