import React, { useState, useEffect, useRef } from 'react'; import FormbricksTranslator from './components/FormbricksTranslator'; import { Settings, Plus, Trash2, ChevronDown, ChevronUp, Play, Copy, Download, Eye, Check, AlertCircle, FileJson, FileText, Upload, Layers, Sparkles, HelpCircle, CheckCircle, Loader2, Lock, Globe, Sun, Moon, FileSpreadsheet, Zap, Archive, ArchiveRestore, Inbox, Square, Octagon, RotateCw, RefreshCw, DollarSign, Coins, Info, PieChart } from 'lucide-react'; import confetti from 'canvas-confetti'; import * as XLSX from 'xlsx'; import { extractTranslatableSegments, reconstructJson, runPipelineForSegment, calculateLevenshteinDistance } from './utils/pipeline'; import { SAMPLE_EMAIL_TEMPLATE, SAMPLE_WEBSITE_I18N_TEMPLATE, SAMPLE_PRODUCT_CATALOG_TEMPLATE, SAMPLE_MARKDOWN_FAQ_TEMPLATE } from './utils/sampleTemplate'; import { parseMarkdownToSegments, extractSmartMarkdownContext, compactUserContext, reconstructMarkdown } from './utils/markdownParser'; import { API_PRICING, calculateSegmentCost, calculateOutputCost, calculateTaskCost, calculateTotalAllTasksCost, formatCurrency } from './utils/costCalculator'; const GEMINI_MODEL = import.meta.env.VITE_GEMINI_MODEL || 'gemini-3.5-flash'; const OPENAI_MODEL = import.meta.env.VITE_OPENAI_MODEL || 'gpt-4o'; const CLAUDE_MODEL = import.meta.env.VITE_CLAUDE_MODEL || 'claude-opus-4.8'; const CONTENT_TYPES = [ { id: 'WEBSITE', name: '🌐 Website / App i18n', label: 'Website UI & App Localized Strings' }, { id: 'EMAIL', name: '✉️ Email Campaign', label: 'Marketing Email Content' }, { id: 'MARKDOWN', name: '📄 FAQ & Markdown (.md)', label: 'Markdown Knowledge Base & FAQ Article' }, { id: 'ECOMMERCE', name: '🛒 E-Commerce & Products', label: 'E-Commerce Product Catalog Content' }, { id: 'CMS', name: '📝 CMS & Blog Articles', label: 'CMS Article & Blog Content' }, { id: 'GENERAL', name: '🧩 General JSON Content', label: 'General JSON Content' } ]; const LANGUAGES = [ { code: 'FR', name: 'French (Français)' }, { code: 'NL', name: 'Dutch (Nederlands)' }, { code: 'DE', name: 'German (Deutsch)' }, { code: 'ES', name: 'Spanish (Español)' }, { code: 'PT', name: 'Portuguese (Português)' }, { code: 'BR', name: 'Portuguese (Brazil)' }, { code: 'HU', name: 'Hungarian (Magyar)' }, { code: 'CS', name: 'Czech (Čeština)' }, { code: 'PL', name: 'Polish (Polski)' }, { code: 'IT', name: 'Italian (Italiano)' }, { code: 'EL', name: 'Greek (Ελληνικά)' } ]; export default function App() { // API keys are securely managed via backend environment variables const getDefaultPresetTasks = () => [ { id: '1', campaignName: 'Payment Failed Email', contentType: 'EMAIL', originalJsonText: JSON.stringify(SAMPLE_EMAIL_TEMPLATE, null, 2), targetLangs: ['FR', 'DE'], expanded: true, outputs: { FR: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }, DE: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] } } }, { id: '2', campaignName: 'FAQ & Markdown (.md) Document', contentType: 'MARKDOWN', originalJsonText: SAMPLE_MARKDOWN_FAQ_TEMPLATE, targetLangs: ['FR', 'DE'], expanded: true, outputs: { FR: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }, DE: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] } } }, { id: '3', campaignName: 'Website & App i18n Localization', contentType: 'WEBSITE', originalJsonText: JSON.stringify(SAMPLE_WEBSITE_I18N_TEMPLATE, null, 2), targetLangs: ['FR', 'NL', 'DE'], expanded: true, outputs: { FR: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }, NL: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }, DE: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] } } }, { id: '4', campaignName: 'Product Catalog (E-Commerce)', contentType: 'ECOMMERCE', originalJsonText: JSON.stringify(SAMPLE_PRODUCT_CATALOG_TEMPLATE, null, 2), targetLangs: ['FR', 'DE', 'ES'], expanded: true, outputs: { FR: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }, DE: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }, ES: { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] } } } ]; // Translation tasks list const [tasks, setTasks] = useState(() => { const saved = localStorage.getItem('consensus_ai_tasks_v4'); if (saved !== null) { try { const parsed = JSON.parse(saved); if (Array.isArray(parsed)) return parsed; } catch (e) { console.error("Failed to load tasks:", e); } } return getDefaultPresetTasks(); }); const resetAllDefaultTasks = () => { if (window.confirm("Do you want to reset and restore the 4 default template projects (FAQ Markdown, Email, Website, E-Commerce)?")) { const defaultTasks = getDefaultPresetTasks(); setTasks(defaultTasks); localStorage.setItem('consensus_ai_tasks_v4', JSON.stringify(defaultTasks)); } }; // UI state variables const [isSettingsOpen, setIsSettingsOpen] = useState(false); const [activeDetails, setActiveDetails] = useState(null); // { taskId, langCode } const [selectedSegmentIndex, setSelectedSegmentIndex] = useState(0); const [activeLangDropdown, setActiveLangDropdown] = useState(null); // taskId const [copiedTextId, setCopiedTextId] = useState(null); // 'taskId_langCode' or similar const [activeNotesModal, setActiveNotesModal] = useState(null); // { taskId, langCode } const [activeJsonViewer, setActiveJsonViewer] = useState(null); // { title, jsonText } const [isPricingModalOpen, setIsPricingModalOpen] = useState(false); const [activeCostPopoverId, setActiveCostPopoverId] = useState(null); // 'global' | taskId | 'sub_taskId_langCode' const dropdownRef = useRef(null); const popoverRef = useRef(null); // Auto Queue Mode state const [isAutoQueueActive, setIsAutoQueueActive] = useState(false); const [isProcessingQueue, setIsProcessingQueue] = useState(false); // Archive vs Active view tab state const [activeTab, setActiveTab] = useState('active'); // 'active' | 'archive' // App Mode state const [appMode, setAppMode] = useState('translator'); // 'translator' | 'formbricks' // Panel mode switcher: 'JSON' vs 'MARKDOWN' const [translationMode, setTranslationMode] = useState('MARKDOWN'); // 'JSON' | 'MARKDOWN' // Cancel / Stop Translation Ref const isCancelRequestedRef = useRef(false); // Per-step Granular Retry state const [retryingStepKey, setRetryingStepKey] = useState(null); // Instruction Manual Modal state const [isGuideModalOpen, setIsGuideModalOpen] = useState(false); // Theme support: default is dark mode (behbudlu.com) const [isDarkMode, setIsDarkMode] = useState(() => { const saved = localStorage.getItem('et_dark_mode'); return saved ? JSON.parse(saved) : true; }); useEffect(() => { localStorage.setItem('et_dark_mode', JSON.stringify(isDarkMode)); if (isDarkMode) { document.documentElement.classList.add('dark'); } else { document.documentElement.classList.remove('dark'); } }, [isDarkMode]); // Sync initial load with Central Backend Storage (/api/tasks) useEffect(() => { fetch('/api/tasks') .then(res => res.json()) .then(data => { if (Array.isArray(data)) { setTasks(data); localStorage.setItem('consensus_ai_tasks_v4', JSON.stringify(data)); } else if (data === null) { // Initialize server with current default tasks const defaultTasks = getDefaultPresetTasks(); fetch('/api/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tasks: defaultTasks }) }).catch(e => {}); } }) .catch(err => console.warn("Backend tasks fetch notice:", err)); }, []); useEffect(() => { localStorage.setItem('consensus_ai_tasks_v4', JSON.stringify(tasks)); const timer = setTimeout(() => { fetch('/api/tasks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tasks }) }).catch(err => {}); }, 400); return () => clearTimeout(timer); }, [tasks]); // --- Fail-proof Excel Exporter & File Saver --- const saveExcelFile = (rowsData, fileName, sheetName = 'Translations') => { try { // Excel Hard Limit Safety: Max 32,767 characters per single cell const safeRows = rowsData.map(row => { const cleanRow = {}; Object.keys(row).forEach(key => { let val = row[key]; if (typeof val === 'string' && val.length > 32000) { val = val.slice(0, 32000) + '\n\n... [NOTE: Text truncated to fit Excel 32,767 character cell limit. Download the full document via .md / .json button.]'; } cleanRow[key] = val; }); return cleanRow; }); const worksheet = XLSX.utils.json_to_sheet(safeRows); worksheet['!cols'] = [ { wch: 22 }, { wch: 18 }, { wch: 14 }, { wch: 70 }, { wch: 14 }, { wch: 50 }, { wch: 60 } ]; const workbook = XLSX.utils.book_new(); const safeSheetName = sheetName.replace(/[/\\?%*:|[\]]/g, '_').slice(0, 30); XLSX.utils.book_append_sheet(workbook, worksheet, safeSheetName); const safeFileName = (fileName || 'Tercume_Eksport').replace(/[/\\?%*:|"<>#]/g, '_') + '.xlsx'; try { XLSX.writeFile(workbook, safeFileName); } catch (err) { console.warn("XLSX.writeFile fallback triggered:", err); const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' }); const blob = new Blob([wbout], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = safeFileName; document.body.appendChild(a); a.click(); setTimeout(() => { document.body.removeChild(a); URL.revokeObjectURL(url); }, 100); } } catch (globalErr) { console.error("Excel generation error:", globalErr); alert("Error: Failed to create Excel file: " + globalErr.message); } }; const exportAllToExcel = () => { const rows = []; tasks.forEach(task => { const campaign = task.campaignName?.trim() || `Kontent #${task.id}`; Object.keys(task.outputs).forEach(langCode => { const out = task.outputs[langCode]; if (out && (out.status === 'Success' || out.status === 'Completed')) { const langObj = LANGUAGES.find(l => l.code === langCode); const langLabel = langObj ? `${langObj.name} (${langCode})` : langCode; let cleanText = ''; if (out.translatedMd) { cleanText = out.translatedMd; } else if (out.segments && out.segments.length > 0) { cleanText = out.segments.map(s => s.claude).join('\n\n'); } else if (out.translatedJson) { cleanText = typeof out.translatedJson === 'string' ? out.translatedJson : JSON.stringify(out.translatedJson, null, 2); } rows.push({ 'Campaign / Document Title': campaign, 'Target Language': langLabel, 'Status': 'Completed', 'Translated Text (Clean)': cleanText, 'Divergence Percentage': out.conflictPct ? `${out.conflictPct}%` : '0%', 'Consensus Agent Notes': out.agentNotes || '', 'Translated Output (JSON / MD)': out.translatedJson ? (typeof out.translatedJson === 'string' ? out.translatedJson : JSON.stringify(out.translatedJson, null, 2)) : '' }); } }); }); if (rows.length === 0) { alert("No completed translations found to export."); return; } const dateStr = new Date().toISOString().slice(0, 10); saveExcelFile(rows, `Topdan_Tercumeler_${dateStr}`, "All Translations"); }; const exportSingleToExcel = (task, langCode) => { const out = task.outputs?.[langCode]; if (!out) { alert("Error: No translation data found for this language."); return; } const campaign = task.campaignName?.trim() || `Tercume_${task.id}`; const langObj = LANGUAGES.find(l => l.code === langCode); const langLabel = langObj ? `${langObj.name} (${langCode})` : langCode; let cleanText = ''; if (out.translatedMd) { cleanText = out.translatedMd; } else if (out.segments && out.segments.length > 0) { cleanText = out.segments.map(s => s.claude).join('\n\n'); } else if (out.translatedJson) { cleanText = typeof out.translatedJson === 'string' ? out.translatedJson : JSON.stringify(out.translatedJson, null, 2); } const rows = [{ 'Campaign / Document Title': campaign, 'Target Language': langLabel, 'Status': (out.status === 'Success' || out.status === 'Completed') ? 'Completed' : out.status, 'Translated Text (Clean)': cleanText, 'Divergence Percentage': out.conflictPct ? `${out.conflictPct}%` : '0%', 'Consensus Agent Notes': out.agentNotes || '', 'Translated Output (JSON / MD)': out.translatedJson ? (typeof out.translatedJson === 'string' ? out.translatedJson : JSON.stringify(out.translatedJson, null, 2)) : '' }]; saveExcelFile(rows, `${campaign}_${langCode}`, langCode); }; // Click outside listener for language dropdown and cost popovers useEffect(() => { function handleClickOutside(event) { if (dropdownRef.current && !dropdownRef.current.contains(event.target)) { setActiveLangDropdown(null); } if (popoverRef.current && !popoverRef.current.contains(event.target)) { setActiveCostPopoverId(null); } } document.addEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside); }, []); // --- Auto Queue Worker Engine --- useEffect(() => { if (!isAutoQueueActive || isProcessingQueue) return; if (isCancelRequestedRef.current) { setIsAutoQueueActive(false); setIsProcessingQueue(false); return; } // Scan all tasks for the next language needing translation (Draft or Error) let nextJob = null; for (const task of tasks) { if (!task.originalJsonText || !task.targetLangs || task.targetLangs.length === 0) continue; for (const lang of task.targetLangs) { const out = task.outputs?.[lang]; const status = out?.status || 'Draft'; // Target tasks that are Draft or Error or failed status if (status === 'Draft' || status === 'Error' || status.toLowerCase().includes('error') || status === 'Xəta') { nextJob = { taskId: task.id, langCode: lang }; break; } } if (nextJob) break; } if (!nextJob) { // All tasks/languages are completed! return; } setIsProcessingQueue(true); (async () => { try { await runTranslationPipeline(nextJob.taskId, nextJob.langCode); } catch (err) { console.error("Auto queue job error:", err); } finally { // Breather pause (1.2s) before taking the next queue item await new Promise(r => setTimeout(r, 1200)); setIsProcessingQueue(false); } })(); }, [isAutoQueueActive, isProcessingQueue, tasks]); // --- Task management --- const addTask = () => { const nextNum = tasks.length > 0 ? Math.max(...tasks.map(t => parseInt(t.id) || 0)) + 1 : 1; const newTask = { id: Date.now().toString(), campaignName: '', contentType: translationMode === 'MARKDOWN' ? 'MARKDOWN' : 'WEBSITE', originalJsonText: '', customContext: '', targetLangs: [], expanded: true, outputs: {} }; setTasks([...tasks, newTask]); }; const updateTaskField = (taskId, field, value) => { setTasks(tasks.map(t => { if (t.id === taskId) { const updated = { ...t, [field]: value }; // If we change target languages, we initialize output records for any new language if (field === 'targetLangs') { const newOutputs = { ...t.outputs }; value.forEach(lang => { if (!newOutputs[lang]) { newOutputs[lang] = { status: 'Draft', translatedJson: null, conflictPct: 0, agentNotes: '', error: null, segments: [] }; } }); // Clean up deleted languages from outputs Object.keys(newOutputs).forEach(lang => { if (!value.includes(lang)) { delete newOutputs[lang]; } }); updated.outputs = newOutputs; } return updated; } return t; })); }; const stopAllTranslations = () => { isCancelRequestedRef.current = true; setIsAutoQueueActive(false); setIsProcessingQueue(false); // INSTANT REACT STATE UPDATE: Stop all spinners immediately! setTasks(prevTasks => prevTasks.map(t => { const newOutputs = { ...t.outputs }; let hasChange = false; Object.keys(newOutputs).forEach(lang => { if (newOutputs[lang] && newOutputs[lang].status && (newOutputs[lang].status === 'Translating' || newOutputs[lang].status.startsWith('Translating'))) { newOutputs[lang] = { ...newOutputs[lang], status: 'Draft', error: null }; hasChange = true; } }); return hasChange ? { ...t, outputs: newOutputs } : t; })); }; const deleteTask = (taskId) => { setTasks(tasks.filter(t => t.id !== taskId)); }; const archiveTask = (taskId) => { setTasks(tasks.map(t => t.id === taskId ? { ...t, archived: true } : t)); }; const unarchiveTask = (taskId) => { setTasks(tasks.map(t => t.id === taskId ? { ...t, archived: false } : t)); }; // --- Excel Template Generator for non-JSON users --- const downloadExcelTemplate = () => { const templateRows = [ { "Section_ID": "hero_title", "Source_Text_English": "Welcome to Our Platform" }, { "Section_ID": "hero_subtitle", "Source_Text_English": "Build fast, modern, and localized websites effortlessly." }, { "Section_ID": "cta_button", "Source_Text_English": "Get Started Now" }, { "Section_ID": "feature_1_title", "Source_Text_English": "AI Multi-Agent Translation Engine" }, { "Section_ID": "footer_copyright", "Source_Text_English": "All rights reserved © 2026." } ]; const worksheet = XLSX.utils.json_to_sheet(templateRows); worksheet['!cols'] = [{ wch: 25 }, { wch: 60 }]; const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, "Translation_Template"); XLSX.writeFile(workbook, "Content_Translation_Sablon.xlsx"); }; // --- Universal File Uploader (Supports JSON, XLSX, XLS, CSV) --- const handleFileUpload = (taskId, file) => { if (!file) return; const fileName = file.name.toLowerCase(); if (fileName.endsWith('.json')) { const reader = new FileReader(); reader.onload = (e) => { try { const text = e.target.result; JSON.parse(text); updateTaskField(taskId, 'originalJsonText', text); } catch (err) { alert("Error: Selected file is not a valid JSON document."); } }; reader.readAsText(file); } else if (fileName.endsWith('.md') || fileName.endsWith('.markdown')) { const reader = new FileReader(); reader.onload = (e) => { const text = e.target.result; updateTaskField(taskId, 'contentType', 'MARKDOWN'); updateTaskField(taskId, 'originalJsonText', text); }; reader.readAsText(file); } else if (fileName.endsWith('.xlsx') || fileName.endsWith('.xls') || fileName.endsWith('.csv')) { const reader = new FileReader(); reader.onload = (e) => { try { const data = new Uint8Array(e.target.result); const workbook = XLSX.read(data, { type: 'array' }); const firstSheetName = workbook.SheetNames[0]; const worksheet = workbook.Sheets[firstSheetName]; const rawRows = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); if (!rawRows || rawRows.length === 0) { alert("Error: The selected Excel file is empty."); return; } const jsonResult = {}; let count = 0; // Check if first row is header const firstRowFirstCol = String(rawRows[0]?.[0] || '').toLowerCase(); const startIdx = ( firstRowFirstCol.includes('id') || firstRowFirstCol.includes('section') || firstRowFirstCol.includes('bölmə') || firstRowFirstCol.includes('key') || firstRowFirstCol.includes('açar') || firstRowFirstCol.includes('key') ) ? 1 : 0; for (let i = startIdx; i < rawRows.length; i++) { const row = rawRows[i]; if (!row || row.length === 0) continue; if (row.length >= 2) { const key = String(row[0] || `row_${i + 1}`).trim(); const val = String(row[1] || '').trim(); if (val) { jsonResult[key] = val; count++; } } else if (row.length === 1) { const val = String(row[0] || '').trim(); if (val) { jsonResult[`row_${i + 1}`] = val; count++; } } } if (count === 0) { alert("Error: No translatable text content found in the Excel file."); return; } updateTaskField(taskId, 'originalJsonText', JSON.stringify(jsonResult, null, 2)); } catch (err) { console.error("Excel import error:", err); alert("Error: Failed to parse Excel file."); } }; reader.readAsArrayBuffer(file); } else { alert("Error: Only .json, .xlsx, .xls, .md, or .csv files are supported."); } }; // Convert plain text lines to valid JSON structure const convertLinesToJson = (taskId, text) => { if (!text || text.trim() === '') return; try { // Check if already valid JSON JSON.parse(text); return; // Already JSON, do nothing } catch (e) { // Split by lines and build JSON const lines = text.split('\n').map(l => l.trim()).filter(l => l.length > 0); if (lines.length === 0) return; const jsonObj = {}; lines.forEach((line, index) => { jsonObj[`setir_${index + 1}`] = line; }); updateTaskField(taskId, 'originalJsonText', JSON.stringify(jsonObj, null, 2)); } }; const loadSamplePreset = (taskId, presetType = 'EMAIL') => { let templateObj = SAMPLE_EMAIL_TEMPLATE; let cType = 'EMAIL'; if (presetType === 'WEBSITE') { templateObj = SAMPLE_WEBSITE_I18N_TEMPLATE; cType = 'WEBSITE'; jsonText = JSON.stringify(templateObj, null, 2); } else if (presetType === 'ECOMMERCE') { templateObj = SAMPLE_PRODUCT_CATALOG_TEMPLATE; cType = 'ECOMMERCE'; jsonText = JSON.stringify(templateObj, null, 2); } else if (presetType === 'MARKDOWN') { cType = 'MARKDOWN'; jsonText = SAMPLE_MARKDOWN_FAQ_TEMPLATE; } else { jsonText = JSON.stringify(templateObj, null, 2); } setTasks(tasks.map(t => { if (t.id === taskId) { return { ...t, contentType: cType, originalJsonText: jsonText }; } return t; })); }; // --- Copy/Download utils --- const copyToClipboard = (text, id) => { navigator.clipboard.writeText(text).then(() => { setCopiedTextId(id); setTimeout(() => setCopiedTextId(null), 2000); }); }; const downloadJsonFile = (jsonObj, fileName) => { const content = typeof jsonObj === 'string' ? jsonObj : JSON.stringify(jsonObj, null, 2); const dataStr = "data:text/plain;charset=utf-8," + encodeURIComponent(content); const downloadAnchor = document.createElement('a'); downloadAnchor.setAttribute("href", dataStr); downloadAnchor.setAttribute("download", fileName); document.body.appendChild(downloadAnchor); downloadAnchor.click(); downloadAnchor.remove(); }; // --- Pipeline Execution --- const runTranslationPipeline = async (taskId, langCode) => { const task = tasks.find(t => t.id === taskId); if (!task) return; const isMarkdownTask = task.contentType === 'MARKDOWN' || ( typeof task.originalJsonText === 'string' && !task.originalJsonText.trim().startsWith('{') && !task.originalJsonText.trim().startsWith('[') ); let segments = []; let mdStructureMap = null; let fullContextText = ''; if (isMarkdownTask) { const parsedMd = parseMarkdownToSegments(task.originalJsonText); segments = parsedMd.segments; mdStructureMap = parsedMd.structureMap; // Pre-analyze: Full markdown document context passed to LLMs as Knowledge Base! fullContextText = `=== MARKDOWN KNOWLEDGE BASE & FULL CONTEXT ===\n${task.originalJsonText}`; } else { let parsedJson = null; try { parsedJson = JSON.parse(task.originalJsonText); } catch (e) { alert("Error: Source content field is empty or invalid."); return; } segments = extractTranslatableSegments(parsedJson); fullContextText = segments.map(s => s.original).join('\n---\n'); } // Set state to Translating setTasks(prevTasks => prevTasks.map(t => { if (t.id === taskId) { return { ...t, outputs: { ...t.outputs, [langCode]: { ...t.outputs[langCode], status: 'Translating', error: null, originalSegments: segments } } }; } return t; })); try { if (segments.length === 0) { throw new Error("No translatable segments found in this document."); } // Check existing completed segments for smart resume capability const existingSegments = task.outputs?.[langCode]?.segments || []; const processedSegments = []; let totalConflictScore = 0; let notesAccumulator = []; // 2. Process segment by segment for (let i = 0; i < segments.length; i++) { if (isCancelRequestedRef.current) { throw new Error("CANCELLED_BY_USER"); } const seg = segments[i]; const existingSeg = existingSegments[i]; // Smart Resume: If this block was already translated cleanly, skip API call and reuse it! const isAlreadyDone = existingSeg && existingSeg.claude && !existingSeg.hasError && !existingSeg.agentNotes?.includes('Xətası') && !existingSeg.agentNotes?.includes('Sintez Xətası'); if (isAlreadyDone) { processedSegments.push(existingSeg); totalConflictScore += (existingSeg.conflictPct || 0); if (existingSeg.agentNotes && existingSeg.agentNotes !== "APPROVED" && !existingSeg.agentNotes.includes("təsdiq edilib")) { notesAccumulator.push(`[Segments ${i+1}]: ${existingSeg.agentNotes}`); } continue; } // Update status for user feedback (optional granular step) setTasks(prevTasks => prevTasks.map(t => { if (t.id === taskId) { return { ...t, outputs: { ...t.outputs, [langCode]: { ...t.outputs[langCode], status: `Translating (${i + 1}/${segments.length})` } } }; } return t; })); const contentTypeObj = CONTENT_TYPES.find(c => c.id === (task.contentType || 'GENERAL')); const contentTypeLabel = contentTypeObj ? contentTypeObj.label : 'General JSON Content'; // Custom User Knowledge Base & Rules Integration (Auto-Compacted if long!) const rawUserContext = task.customContext && task.customContext.trim() ? task.customContext.trim() : ''; const compactedUserContext = rawUserContext ? compactUserContext(rawUserContext) : ''; const userKnowledgeContext = compactedUserContext ? `=== USER CUSTOM KNOWLEDGE BASE & BRAND GUIDELINES (COMPACT) ===\n${compactedUserContext}\n\n` : ''; // Token Optimization: For Markdown documents, pass targeted Smart Context (98% token savings!) const segmentContext = isMarkdownTask ? `${userKnowledgeContext}${extractSmartMarkdownContext(i, segments)}` : `${userKnowledgeContext}${fullContextText}`; const res = await runPipelineForSegment(seg, langCode, {}, false, segmentContext, contentTypeLabel); if (!res.success) { throw new Error(`Segment [${i+1}] localization error: ${res.error}`); } processedSegments.push({ id: seg.id, original: seg.original, deepl: res.deepl, gemini: res.gemini, openai: res.openai, claude: res.claude.final_translation, agentNotes: res.claude.agent_notes, conflictPct: res.claude.discrepancy_percentage }); totalConflictScore += res.claude.discrepancy_percentage; if (res.claude.agent_notes && res.claude.agent_notes !== "APPROVED" && !res.claude.agent_notes.includes("təsdiq edilib")) { notesAccumulator.push(`[Segments ${i+1}]: ${res.claude.agent_notes}`); } // --- LIVE UPDATE STATE: Allows Cost & Steps to tick up progressively --- setTasks(prevTasks => prevTasks.map(t => { if (t.id === taskId) { return { ...t, outputs: { ...t.outputs, [langCode]: { ...t.outputs[langCode], segments: [...processedSegments] } } }; } return t; })); // Breather delay (200ms) to prevent API rate-limit spikes across large documents await new Promise(r => setTimeout(r, 200)); } // Calculate final average conflict % const avgConflictPct = Math.round(totalConflictScore / segments.length); // 3. Reconstruct output (Markdown vs JSON) let finalTranslatedOutput = null; let translatedMdText = null; if (isMarkdownTask && mdStructureMap) { const mdSegmentsMap = {}; processedSegments.forEach(ps => { const segObj = segments.find(s => s.id === ps.id); mdSegmentsMap[ps.id] = { prefix: segObj?.prefix || '', claude: ps.claude, original: ps.original }; }); translatedMdText = reconstructMarkdown(mdStructureMap, mdSegmentsMap); finalTranslatedOutput = translatedMdText; } else { const parsedJson = JSON.parse(task.originalJsonText); const reconstructionMap = processedSegments.map(ps => { const segObj = segments.find(s => s.id === ps.id); return { id: ps.id, blockId: ps.id.split('_')[0], propName: ps.id.split('_')[1], path: segObj?.path, translated: ps.claude }; }); finalTranslatedOutput = reconstructJson(parsedJson, reconstructionMap); } // Create a cohesive agent note const finalNotes = notesAccumulator.length > 0 ? notesAccumulator.join('\n') : "All segments were validated with high consensus across all reviewer models."; // 4. Update task completion state setTasks(prevTasks => prevTasks.map(t => { if (t.id === taskId) { return { ...t, outputs: { ...t.outputs, [langCode]: { status: 'Success', translatedJson: finalTranslatedOutput, translatedMd: translatedMdText, conflictPct: avgConflictPct, agentNotes: finalNotes, error: null, segments: processedSegments, originalSegments: segments } } }; } return t; })); // Celebrate success! confetti({ particleCount: 80, spread: 60, origin: { y: 0.8 }, colors: ['#3b82f6', '#06b6d4', '#10b981'] }); } catch (err) { const isUserCancel = err.message === 'CANCELLED_BY_USER' || isCancelRequestedRef.current; setTasks(prevTasks => prevTasks.map(t => { if (t.id === taskId) { return { ...t, outputs: { ...t.outputs, [langCode]: { ...t.outputs[langCode], status: isUserCancel ? 'Draft' : 'Error', error: isUserCancel ? null : (err.message || "Unexpected error during localization pipeline.") } } }; } return t; })); } }; // --- Granular Per-Step Retry Engine --- const retryPipelineStep = async (taskId, langCode, segmentIndex, stepName) => { const task = tasks.find(t => String(t.id) === String(taskId)); if (!task) { console.warn("retryPipelineStep: Task not found for ID:", taskId); return; } const output = task.outputs?.[langCode]; if (!output || !output.segments || !output.segments[segmentIndex]) return; const seg = output.segments[segmentIndex]; const key = `${taskId}_${langCode}_${segmentIndex}_${stepName}`; setRetryingStepKey(key); const isMarkdownTask = task.contentType === 'MARKDOWN'; const contentTypeObj = CONTENT_TYPES.find(c => c.id === (task.contentType || 'GENERAL')); const contentTypeLabel = contentTypeObj ? contentTypeObj.label : 'General JSON Content'; const rawUserContext = task.customContext && task.customContext.trim() ? task.customContext.trim() : ''; const compactedUserContext = rawUserContext ? compactUserContext(rawUserContext) : ''; const userKnowledgeContext = compactedUserContext ? `=== USER CUSTOM KNOWLEDGE BASE & BRAND GUIDELINES (COMPACT) ===\n${compactedUserContext}\n\n` : ''; const segmentContext = isMarkdownTask ? `${userKnowledgeContext}${extractSmartMarkdownContext(segmentIndex, output.segments)}` : `${userKnowledgeContext}${output.segments.map(s => s.original).join('\n---\n')}`; try { let updatedSeg = { ...seg }; if (stepName === 'all') { const res = await runPipelineForSegment(seg, langCode, {}, false, segmentContext, contentTypeLabel); if (res && res.success) { updatedSeg = { ...updatedSeg, deepl: res.deepl, gemini: res.gemini, openai: res.openai, claude: res.claude.final_translation, agentNotes: res.claude.agent_notes, conflictPct: res.claude.discrepancy_percentage, hasError: res.claude.hasError || false }; } else { throw new Error(res?.error || "Error occurred while rerunning segment."); } } else { const res = await fetch('/api/retry-step', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ step: stepName, originalText: seg.original, deeplText: seg.deepl, geminiReview: seg.gemini, openaiReview: seg.openai, targetLang: langCode, targetLangName: LANGUAGES.find(l => l.code === langCode)?.name || langCode, fullContext: segmentContext, contentType: contentTypeLabel }) }); const data = await res.json(); if (!data.success) { throw new Error(data.error || `Error occurred during ${stepName} retry.`); } if (stepName === 'deepl') { updatedSeg.deepl = data.deepl; } else if (stepName === 'gemini') { updatedSeg.gemini = data.gemini; } else if (stepName === 'openai') { updatedSeg.openai = data.openai; } else if (stepName === 'claude') { updatedSeg.claude = data.claude.final_translation; updatedSeg.agentNotes = data.claude.agent_notes; updatedSeg.conflictPct = data.claude.discrepancy_percentage; updatedSeg.hasError = data.claude.hasError || false; } if (['deepl', 'gemini', 'openai'].includes(stepName)) { const claudeRes = await fetch('/api/retry-step', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ step: 'claude', originalText: seg.original, deeplText: updatedSeg.deepl, geminiReview: updatedSeg.gemini, openaiReview: updatedSeg.openai, targetLang: langCode, targetLangName: LANGUAGES.find(l => l.code === langCode)?.name || langCode, fullContext: segmentContext, contentType: contentTypeLabel }) }); const claudeData = await claudeRes.json(); if (claudeData.success) { updatedSeg.claude = claudeData.claude.final_translation; updatedSeg.agentNotes = claudeData.claude.agent_notes; updatedSeg.conflictPct = claudeData.claude.discrepancy_percentage; updatedSeg.hasError = claudeData.claude.hasError || false; } } } setTasks(prevTasks => prevTasks.map(t => { if (String(t.id) === String(taskId)) { const out = t.outputs[langCode]; const newSegments = [...out.segments]; newSegments[segmentIndex] = updatedSeg; let newTranslatedJson = out.translatedJson; let newTranslatedMd = out.translatedMd; if (isMarkdownTask) { const parsedMd = parseMarkdownToSegments(t.originalJsonText); const segMap = new Map(); newSegments.forEach(s => segMap.set(s.id, s.claude)); newTranslatedMd = reconstructMarkdown(parsedMd.structureMap, segMap); newTranslatedJson = newTranslatedMd; } else { let parsedObj = JSON.parse(t.originalJsonText); const segMap = new Map(); newSegments.forEach(s => segMap.set(s.id, s.claude)); newTranslatedJson = reconstructJson(parsedObj, segMap); } const avgConflict = Math.round( newSegments.reduce((acc, s) => acc + (s.conflictPct || 0), 0) / newSegments.length ); return { ...t, outputs: { ...t.outputs, [langCode]: { ...out, segments: newSegments, translatedJson: newTranslatedJson, translatedMd: newTranslatedMd, conflictPct: avgConflict } } }; } return t; })); } catch (err) { console.error(`Retry step ${stepName} error:`, err); alert(`Error: ${err.message}`); } finally { setRetryingStepKey(null); } }; // Auto-Fix runner for any segment with old fallback notes useEffect(() => { let fixTarget = null; for (const t of tasks) { for (const lang of Object.keys(t.outputs || {})) { const out = t.outputs[lang]; if (out && out.segments) { const idx = out.segments.findIndex(s => s.agentNotes && s.agentNotes.includes("Claude JSON formatında cavab vermədi")); if (idx !== -1) { fixTarget = { taskId: String(t.id), langCode: lang, segmentIndex: idx }; break; } } } if (fixTarget) break; } if (fixTarget && !retryingStepKey) { console.log(`Auto-fixing fallback segment: Task ${fixTarget.taskId}, Lang ${fixTarget.langCode}, Seg ${fixTarget.segmentIndex}`); retryPipelineStep(fixTarget.taskId, fixTarget.langCode, fixTarget.segmentIndex, 'claude'); } }, [tasks, retryingStepKey]); const runAllLanguagesForTask = async (taskId) => { const task = tasks.find(t => t.id === taskId); if (!task) return; isCancelRequestedRef.current = false; // Execute all active target languages sequentially with a small breather for (let i = 0; i < task.targetLangs.length; i++) { if (isCancelRequestedRef.current) break; const langCode = task.targetLangs[i]; if (i > 0) { await new Promise(r => setTimeout(r, 600)); } if (isCancelRequestedRef.current) break; await runTranslationPipeline(taskId, langCode); } }; // --- Statistics & Task filtering calculations --- const activeTasks = tasks.filter(t => !t.archived); const archivedTasks = tasks.filter(t => t.archived); // Filter by Tab (Active vs Archive) AND Mode Panel (JSON vs MARKDOWN) const tabFilteredTasks = activeTab === 'active' ? activeTasks : archivedTasks; const visibleTasks = tabFilteredTasks.filter(t => { if (translationMode === 'MARKDOWN') { return t.contentType === 'MARKDOWN'; } return t.contentType !== 'MARKDOWN'; }); const totalTasks = tasks.length; const totalTargetLangs = tasks.reduce((acc, t) => acc + t.targetLangs.length, 0); const successfulOutputs = tasks.reduce((acc, t) => { return acc + Object.values(t.outputs).filter(o => o.status === 'Success').length; }, 0); const avgConflictOverall = (() => { let sum = 0; let count = 0; tasks.forEach(t => { Object.values(t.outputs).forEach(o => { if (o.status === 'Success') { sum += o.conflictPct; count++; } }); }); return count > 0 ? Math.round(sum / count) : 0; })(); const totalAllCost = calculateTotalAllTasksCost(tasks); return (
{/* HEADER SECTION */}

AI Content Translator

Multi-Agent Consensus AI Localization Platform for Websites, Apps, Emails, and Knowledge Base Markdown

{/* PANEL / MODE SWITCHER (JSON vs MARKDOWN) */}
{appMode === 'formbricks' && } {appMode === 'translator' && ( <> {/* KPI STATISTICS PANEL */}
{totalTasks}
Total Projects
{totalTargetLangs}
Target Languages
{successfulOutputs}
Languages Translated
{avgConflictOverall}%
Avg. Divergence
setIsPricingModalOpen(true)} style={{ position: 'relative' }} title="Click to view comprehensive API cost analytics and pricing breakdown" >
{formatCurrency(totalAllCost.total)}
Total API Cost
{/* MAIN TABLE VIEWER */}
{/* TAB SWITCHER: AKTİV vs ARXİV */}
{visibleTasks.length === 0 ? (
{activeTab === 'active' ? ( <>

No active projects yet

Click "New Project" to start a new multi-agent localization pipeline.

) : ( <>

Archive is empty

You can move completed localization projects from the active tab to archive.

)}
) : ( {visibleTasks.map((task) => { const totalLangs = task.targetLangs.length; const doneLangs = Object.values(task.outputs).filter(o => o.status === 'Success').length; const runningLangs = Object.values(task.outputs).filter(o => o.status.startsWith('Translating')).length; let overallStatusText = 'Draft'; let statusBadge = 'badge-draft'; if (runningLangs > 0) { overallStatusText = `Translating (${doneLangs}/${totalLangs})`; statusBadge = 'badge-running'; } else if (totalLangs > 0 && doneLangs === totalLangs) { overallStatusText = 'Completed'; statusBadge = 'badge-success'; } else if (Object.values(task.outputs).some(o => o.status === 'Error')) { overallStatusText = 'Has Errors'; statusBadge = 'badge-error'; } const taskCost = calculateTaskCost(task); return ( {/* Main Row */}
Kontent / Project Name Orijinal JSON (Kontent) Target Languagesi (Dil) Status Actions
updateTaskField(task.id, 'campaignName', e.target.value)} placeholder="Project / Campaign title..." style={{ width: '100%', fontWeight: '600', fontSize: '0.875rem' }} />
{activeCostPopoverId === task.id && (
e.stopPropagation()}>
Project Cost Breakdown
DeepL API: {formatCurrency(taskCost.deepl)}
Google Gemini: {formatCurrency(taskCost.gemini)}
OpenAI GPT-4o: {formatCurrency(taskCost.openai)}
Anthropic Claude: {formatCurrency(taskCost.claude)}
Total Project Cost: {formatCurrency(taskCost.total)}
{Object.keys(taskCost.byLang).length > 0 && ( <>
By Language:
{Object.keys(taskCost.byLang).map(code => (
🌐 {code}: {formatCurrency(taskCost.byLang[code].total)}
))} )}
)}
{task.originalJsonText ? (
{task.contentType === 'MARKDOWN' ? ( ) : ( )} {task.contentType === 'MARKDOWN' ? ( 📄 Markdown (.md) Document ({parseMarkdownToSegments(task.originalJsonText || '').segments.length} blok) ) : ( JSON Template ({(() => { try { return Object.keys(JSON.parse(task.originalJsonText || '{}')).length; } catch(e) { return '?'; }})() } blok) )}
) : (
Presets:
)}