(() => { "use strict"; const api = (url) => window.apiFetch(url); let jobs = []; let users = []; const el = (id) => document.getElementById(id); function escapeHtml(value) { return String(value ?? "").replace(/[&<>"']/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); } function statusLabel(status) { return String(status || "unknown").toLowerCase(); } function renderSummary(items) { for (const state of ["queued", "running", "completed", "failed"]) { const count = items.filter(j => statusLabel(j.status) === state).length; const target = el(`cf2-count-${state}`); if (target) target.textContent = count; } const userTarget = el("cf2-count-users"); if (userTarget && Array.isArray(users)) { userTarget.textContent = users.length; } } function renderJobs(items) { const container = el("cf2-job-history"); if (!container) return; if (!items.length) { container.textContent = "No jobs found for the selected filters."; return; } container.innerHTML = items.map(job => `

${escapeHtml(job.unit)}

${escapeHtml(job.status)}

${escapeHtml(job.current_stage || "No stage reported")}

${escapeHtml(job.topic)}

${escapeHtml(job.created_at || "")}

${statusLabel(job.status) === "running" ? ` ` : ""}
`).join(""); container.querySelectorAll("[data-job]").forEach(button => { button.addEventListener("click", () => { window.cf2OpenHistoryJob(button.dataset.job); }); }); } function currentFilters() { const role = (sessionStorage.getItem("cf2_role") || "").toLowerCase(); const params = new URLSearchParams(); const unit = el("cf2-filter-unit")?.value || ""; const status = el("cf2-filter-status")?.value || ""; if (unit) params.set("unit", unit); if (status) params.set("status", status); if (role === "super_admin") { const owner = el("cf2-filter-user")?.value || ""; const roleFilter = el("cf2-filter-role")?.value || ""; if (owner) params.set("owner_user_id", owner); if (roleFilter) params.set("role", roleFilter); } const qs = params.toString(); return qs ? "?" + qs : ""; } function applyFilters() { renderSummary(jobs); renderJobs(jobs); } async function refreshJobs() { try { const response = await api("/api/jobs" + currentFilters()); if (!response.ok) throw new Error("HTTP " + response.status); jobs = await response.json(); applyFilters(); } catch (error) { const container = el("cf2-job-history"); if (container) container.textContent = "Unable to load jobs: " + error.message; } } async function loadUnitFilter() { const select = el("cf2-filter-unit"); if (!select) return; try { const response = await api("/api/units"); if (!response.ok) return; const units = await response.json(); select.innerHTML = '' + units.map(u => '' ).join(""); } catch (error) { console.error("Unable to load unit filter options:", error); } } window.cf2RefreshJobs = refreshJobs; window.cf2SyncUnitFilter = function(unitName) { const select = el("cf2-filter-unit"); if (!select) return; if (unitName) { const exists = Array.from(select.options).some(o => o.value === unitName); if (!exists) return; select.value = unitName; } else { select.value = ""; } refreshJobs(); }; async function loadUsers() { const role = sessionStorage.getItem("cf2_role"); if (role !== "super_admin") return; const response = await api("/api/users"); if (!response.ok) return; users = await response.json(); const select = el("cf2-filter-user"); if (!select) return; select.innerHTML = ''; users.forEach(user => { const option = document.createElement("option"); option.value = user.user_id; option.textContent = `${user.username} (${user.role})`; select.appendChild(option); }); } window.enforceRoleVisibility = function() { const role = (sessionStorage.getItem("cf2_role") || "").toLowerCase(); const isSuperAdmin = role === "super_admin"; const userFilter = document.getElementById("cf2-filter-user"); const roleFilter = document.getElementById("cf2-filter-role"); if (userFilter) userFilter.style.display = isSuperAdmin ? "inline-block" : "none"; if (roleFilter) roleFilter.style.display = isSuperAdmin ? "inline-block" : "none"; document.querySelectorAll(".cf2-superadmin-only").forEach(elem => { elem.style.display = isSuperAdmin ? "" : "none"; }); }; const enforceRoleVisibility = window.enforceRoleVisibility; async function init() { enforceRoleVisibility(); await loadUnitFilter(); await loadUsers(); const activeUnit = el("unitSelect")?.value || ""; if (activeUnit) window.cf2SyncUnitFilter(activeUnit); await refreshJobs(); document.querySelectorAll(".cf2-filter").forEach(select => { select.addEventListener("change", () => refreshJobs()); }); setInterval(() => { if (!document.hidden) refreshJobs(); }, 5000); } window.cf2OpenHistoryJob = async (jobId) => { try { await window.cf2SelectHistoryJob(jobId); } catch (error) { console.error("Unable to open historical job:", error); alert(error.message); } }; window.cf2WorkspaceNavigate = (target) => { if (target === "catalog" || target === "pd-catalog-view") { window.pdCatalogOpen?.(); return; } window.pdCatalogClose?.(); el(target)?.scrollIntoView({behavior: "smooth"}); }; document.addEventListener("DOMContentLoaded", init); })(); // === CF2 Voice Recorder Integration === (function() { const btnRecord = document.getElementById('btnRecordAudio'); const btnText = document.getElementById('recordBtnText'); const status = document.getElementById('recordStatus'); const audioPreview = document.getElementById('audioPreview'); let mediaRecorder = null; let audioChunks = []; let recordedFile = null; if (!btnRecord) return; btnRecord.addEventListener('click', async () => { if (mediaRecorder && mediaRecorder.state === 'recording') { mediaRecorder.stop(); return; } try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); mediaRecorder = new MediaRecorder(stream); audioChunks = []; mediaRecorder.ondataavailable = (e) => audioChunks.push(e.data); mediaRecorder.onstop = () => { const blob = new Blob(audioChunks, { type: mediaRecorder.mimeType }); const ext = mediaRecorder.mimeType.includes('webm') ? 'webm' : (mediaRecorder.mimeType.includes('ogg') ? 'ogg' : 'wav'); recordedFile = new File([blob], `voice_recording_${Date.now()}.${ext}`, { type: mediaRecorder.mimeType }); audioPreview.src = URL.createObjectURL(blob); audioPreview.classList.remove('hidden'); status.classList.add('hidden'); btnText.textContent = 'Record Voice'; btnRecord.classList.remove('bg-gray-600', 'hover:bg-gray-700'); btnRecord.classList.add('bg-red-600', 'hover:bg-red-700'); stream.getTracks().forEach(track => track.stop()); }; mediaRecorder.start(); status.classList.remove('hidden'); btnText.textContent = 'Stop Recording'; btnRecord.classList.remove('bg-red-600', 'hover:bg-red-700'); btnRecord.classList.add('bg-gray-600', 'hover:bg-gray-700'); } catch (err) { console.error('Microphone access denied:', err); alert('Microphone access is required to record voice.'); } }); window.getCf2RecordedAudio = () => recordedFile; console.log('[cf2-recorder] initialized; button bound:', !!btnRecord); })(); // === CF2 Dynamic Unit UI & Capability Renderer === window.CF2_UNIT_UI_CACHE = window.CF2_UNIT_UI_CACHE || {}; window.resetUnitTransientState = function() { try { if (typeof mediaRecorder !== 'undefined' && mediaRecorder && mediaRecorder.state === 'recording') { mediaRecorder.stop(); } if (typeof recordedFile !== 'undefined') { recordedFile = null; } } catch (_) {} const audioPreview = document.getElementById('audioPreview'); if (audioPreview) { audioPreview.pause(); audioPreview.removeAttribute('src'); audioPreview.classList.add('hidden'); } const recordStatus = document.getElementById('recordStatus'); if (recordStatus) recordStatus.classList.add('hidden'); const recordBtnText = document.getElementById('recordBtnText'); if (recordBtnText) recordBtnText.textContent = 'Record Voice'; const dynContainer = document.getElementById('unitDynamicInputsContainer'); if (dynContainer) dynContainer.innerHTML = ''; }; window.renderUnitDynamicInputs = function(inputs) { const container = document.getElementById('unitDynamicInputsContainer'); if (!container) return; container.replaceChildren(); (inputs || []).forEach((inp) => { if (!inp || !inp.id || inp.type === 'file') return; const wrap = document.createElement('div'); const label = document.createElement('label'); label.className = 'block text-xs font-semibold text-zinc-300 uppercase tracking-wider mb-2'; label.textContent = (inp.label || inp.id) + (inp.required ? ' *' : ''); wrap.appendChild(label); if (inp.type === 'radio_cards' && Array.isArray(inp.options)) { wrap.className = 'md:col-span-2 p-4 bg-zinc-950/80 border border-zinc-800 rounded-xl'; if (inp.hint) { const hint = document.createElement('p'); hint.className = 'text-[11px] text-amber-400/90 mb-3'; hint.textContent = inp.hint; wrap.appendChild(hint); } const grid = document.createElement('div'); grid.className = 'grid grid-cols-1 sm:grid-cols-2 gap-4'; inp.options.forEach((opt, index) => { const card = document.createElement('label'); card.className = 'flex items-center gap-3 bg-zinc-900/90 border border-zinc-800 rounded-xl p-3.5 cursor-pointer'; const radio = document.createElement('input'); radio.type = 'radio'; radio.name = inp.id; radio.value = String(opt.value); radio.dataset.unitField = inp.id; radio.dataset.valueShape = inp.value_shape || 'scalar'; radio.checked = inp.default != null ? String(inp.default) === radio.value : index === 0; radio.required = !!inp.required; const text = document.createElement('div'); const title = document.createElement('div'); title.className = 'text-xs font-bold text-zinc-100'; title.textContent = opt.label || opt.value; text.appendChild(title); if (opt.description) { const description = document.createElement('div'); description.className = 'text-[11px] text-zinc-400 mt-0.5'; description.textContent = opt.description; text.appendChild(description); } card.append(radio, text); grid.appendChild(card); }); wrap.appendChild(grid); } else { let field; if (inp.type === 'select' && Array.isArray(inp.options)) { field = document.createElement('select'); inp.options.forEach((opt) => { const option = document.createElement('option'); option.value = typeof opt === 'object' ? opt.value : opt; option.textContent = typeof opt === 'object' ? (opt.label || opt.value) : opt; field.appendChild(option); }); } else { field = document.createElement('input'); field.type = 'text'; field.placeholder = inp.placeholder || ''; } field.className = 'w-full bg-zinc-950 border border-zinc-700 rounded-xl px-4 py-3 text-sm text-zinc-100'; field.id = `unit_input_${inp.id}`; field.name = inp.id; field.dataset.unitField = inp.id; field.dataset.valueShape = inp.value_shape || 'scalar'; if (inp.default != null) field.value = String(inp.default); field.required = !!inp.required; label.htmlFor = field.id; wrap.appendChild(field); } container.appendChild(wrap); }); }; window.collectUnitDynamicInputs = function(container) { const params = {}; container.querySelectorAll('[data-unit-field]').forEach((field) => { if (field.disabled || (field.type === 'radio' && !field.checked)) return; if (field.value === '') return; params[field.dataset.unitField] = field.dataset.valueShape === 'list' ? [field.value] : field.value; }); return params; }; window.applyUnitCapabilityManifest = function(unitName, ui) { const slug = String(unitName || '').trim().toLowerCase(); document.body.setAttribute('data-unit', slug); window.resetUnitTransientState(); const jobForm = (ui && ui.job_form) || {}; const workspace = String((ui && ui.workspace) || 'job_form').trim().toLowerCase(); const isJobForm = workspace === 'job_form'; const jobCard = document.getElementById('jobFormCard'); if (jobCard) { jobCard.style.display = isJobForm ? '' : 'none'; jobCard.classList.toggle('hidden', !isJobForm); } const inboxPanel = document.getElementById('cf2-inbox-panel'); if (inboxPanel) { const showInbox = workspace === 'chat_inbox'; inboxPanel.style.display = showInbox ? '' : 'none'; inboxPanel.classList.toggle('hidden', !showInbox); if (showInbox) { const iframe = document.getElementById('cf2-inbox-iframe'); if (iframe) { const targetSrc = `/chat-inbox?unit=${encodeURIComponent(slug)}`; if (iframe.getAttribute('src') !== targetSrc) { iframe.setAttribute('src', targetSrc); } } } } const newJobBtn = document.getElementById('cf2NewJobBtn'); if (newJobBtn) { newJobBtn.style.display = isJobForm ? '' : 'none'; newJobBtn.classList.toggle('hidden', !isJobForm); } const features = jobForm.features || {}; const inputs = jobForm.inputs || []; const titleEl = document.getElementById('jobFormTitle'); if (titleEl && ui && ui.title) titleEl.textContent = ui.title; const subEl = document.getElementById('jobFormSubtitle'); if (subEl && ui && ui.subtitle) subEl.textContent = ui.subtitle; const submitBtn = document.getElementById('submitBtn'); if (submitBtn && ui && ui.submit_label) submitBtn.textContent = ui.submit_label; const topicContainer = document.getElementById('topicInputContainer'); if (topicContainer) { const showTopic = jobForm.show_topic !== false; topicContainer.style.display = showTopic ? '' : 'none'; } const audioBox = document.getElementById('audioRecorderContainer'); const audioBtn = document.getElementById('btnRecordAudio'); const supportsAudio = features.audio_recording === true; if (audioBox) { audioBox.style.display = supportsAudio ? 'flex' : 'none'; audioBox.classList.toggle('hidden', !supportsAudio); } if (audioBtn) { audioBtn.disabled = !supportsAudio; } const fileInput = document.getElementById('fileInput'); const fileInputLabel = document.getElementById('fileInputLabelText'); const fileInputHint = document.getElementById('fileInputTypesHint'); const fileSpec = inputs.find((i) => i && i.type === 'file'); if (fileInput && fileSpec && Array.isArray(fileSpec.accepts) && fileSpec.accepts.length) { fileInput.setAttribute('accept', fileSpec.accepts.join(',')); } if (fileInputLabel && jobForm.file_label) { fileInputLabel.textContent = jobForm.file_label; } if (fileInputHint && jobForm.file_hint) { fileInputHint.textContent = jobForm.file_hint; } const branding = (ui && ui.branding) || {}; const applyBrandText = (id, value, toggleHidden) => { const el = document.getElementById(id); if (!el) return; if (value) { el.textContent = String(value); el.style.whiteSpace = 'pre-line'; el.dataset.manifestSet = '1'; if (toggleHidden) el.hidden = false; } else if (el.dataset.manifestSet) { el.textContent = ''; delete el.dataset.manifestSet; if (toggleHidden) el.hidden = true; } }; applyBrandText('dyn-brand-slogan', branding.slogan, false); applyBrandText('dyn-brand-tagline', branding.tagline, true); document.querySelectorAll('[data-capability="header_search"]').forEach((el) => { el.style.display = features.header_search === true ? '' : 'none'; const input = el.querySelector('input'); if (input && branding.search_placeholder) input.placeholder = String(branding.search_placeholder); }); window.renderUnitDynamicInputs(inputs); const dynamic = document.getElementById('unitDynamicInputsContainer'); if (dynamic) dynamic.dataset.unit = slug; }; window.cf2UnitDashboardUrl = function(unitName, jobId) { const unit = (window.cf2Units || []).find((u) => (u.name || u.id) === unitName); const raw = unit && unit.dashboard_url; if (typeof raw !== 'string' || !raw.startsWith('/') || raw.startsWith('//')) return ''; try { const url = new URL(raw, window.location.origin); if (url.origin !== window.location.origin) return ''; if (jobId) url.searchParams.set('job', jobId); return url.pathname + url.search; } catch (_) { return ''; } }; window.applyUnitCapabilityUI = async function(unitName) { const slug = String(unitName || '').trim().toLowerCase(); const requestId = window.CF2_UNIT_UI_REQUEST = (window.CF2_UNIT_UI_REQUEST || 0) + 1; const dynamic = document.getElementById('unitDynamicInputsContainer'); if (dynamic) { dynamic.replaceChildren(); delete dynamic.dataset.unit; } if (!slug) return; if (window.CF2_UNIT_UI_CACHE[slug]) { window.applyUnitCapabilityManifest(slug, window.CF2_UNIT_UI_CACHE[slug]); return; } try { const token = localStorage.getItem('cf2_token') || sessionStorage.getItem('cf2_token') || ''; const headers = token ? { 'Authorization': `Bearer ${token}` } : {}; const unitUrl = `/api/units/${encodeURIComponent(slug)}`; const res = (typeof window.apiFetch === "function") ? await window.apiFetch(unitUrl) : await fetch(unitUrl, { headers }); if (res.ok) { const data = await res.json(); if (data && data.ui_schema) { window.CF2_UNIT_UI_CACHE[slug] = data.ui_schema; if (requestId === window.CF2_UNIT_UI_REQUEST) window.applyUnitCapabilityManifest(slug, data.ui_schema); return; } } } catch (_) {} if (requestId !== window.CF2_UNIT_UI_REQUEST) return; window.applyUnitCapabilityManifest(slug, { title: `${slug.toUpperCase()} Workspace`, job_form: { features: { audio_recording: false } } }); }; document.addEventListener('DOMContentLoaded', () => { const sel = document.getElementById('unitSelect'); if (sel) { if (sel.value) window.applyUnitCapabilityUI(sel.value); } }); /* CF2 responsive sidebar menu */ (() => { const bind = () => { const button = document.getElementById("menu-toggle"); const sidebar = document.getElementById("cf2-sidebar"); const overlay = document.getElementById("sidebar-overlay"); if (!button || !sidebar || !overlay || button.dataset.cf2MenuBound) return; button.dataset.cf2MenuBound = "1"; const mobile = () => window.matchMedia("(max-width: 767.98px)").matches; const closeMobile = () => { sidebar.classList.remove("cf2-mobile-open"); overlay.classList.remove("cf2-mobile-open"); overlay.classList.add("hidden"); document.body.classList.remove("cf2-mobile-nav-open"); button.setAttribute("aria-expanded", String(!document.body.classList.contains("cf2-sidebar-collapsed"))); }; button.addEventListener("click", () => { if (!mobile()) { const collapsed = document.body.classList.toggle("cf2-sidebar-collapsed"); button.setAttribute("aria-expanded", String(!collapsed)); return; } const open = !sidebar.classList.contains("cf2-mobile-open"); sidebar.classList.toggle("cf2-mobile-open", open); overlay.classList.toggle("cf2-mobile-open", open); overlay.classList.toggle("hidden", !open); document.body.classList.toggle("cf2-mobile-nav-open", open); button.setAttribute("aria-expanded", String(open)); }); overlay.addEventListener("click", closeMobile); sidebar.querySelectorAll("button").forEach( item => item.addEventListener("click", closeMobile) ); document.addEventListener("keydown", event => { if (event.key === "Escape") closeMobile(); }); window.addEventListener("resize", closeMobile); }; if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", bind, { once: true }); else bind(); })();