import React, { useState, useEffect, useRef, useMemo } from 'react'; import { Upload, Sparkles, Youtube, Instagram, Share2, ChevronDown, Check, Activity, LayoutDashboard, Settings, Plus, History, X, Terminal, Shield, LayoutGrid, Image, Globe, RotateCcw, Calendar, AlertTriangle, KeyRound, Bot, Users, Smartphone, ExternalLink, Copy, CheckCircle2, Mail, Loader2, Download, Menu, Lock } from 'lucide-react'; import KeyInput from './components/KeyInput'; import MediaInput from './components/MediaInput'; import McpConnectCard from './components/McpConnectCard'; import ResultCard from './components/ResultCard'; import ProcessingAnimation from './components/ProcessingAnimation'; // import Gallery from './components/Gallery'; import ThumbnailStudio from './components/ThumbnailStudio'; import SaaShortsTab from './components/SaaShortsTab'; import UGCGallery from './components/UGCGallery'; import ScheduleWeekModal from './components/ScheduleWeekModal'; import ClipEditor from './components/ClipEditor'; import ReframeEditor from './components/ReframeEditor'; import UsageMeter from './components/UsageMeter'; import TopUpModal from './components/TopUpModal'; import StarBanner from './components/StarBanner'; import PlanChoiceModal from './components/PlanChoiceModal'; import ClipTutorial from './components/ClipTutorial'; import TrialUpgradeModal from './components/TrialUpgradeModal'; import LoginModal from './components/LoginModal'; import TrialGate from './components/TrialGate'; import AdvancedBanner from './components/AdvancedBanner'; import HistoryTab from './components/HistoryTab'; import ProfileMenu from './components/ProfileMenu'; import Modal from './components/ui/Modal'; import { useAuth } from './contexts/AuthContext'; import { apiFetch, apiJson, QuotaError } from './lib/api'; import { track } from './lib/analytics'; // Enhanced "Encryption" using XOR + Base64 with a Salt // This is better than plain Base64 but still client-side. const SECRET_KEY = import.meta.env.VITE_ENCRYPTION_KEY || "OpenShorts-Static-Salt-Change-Me"; const ENCRYPTION_PREFIX = "ENC:"; const encrypt = (text) => { if (!text) return ''; try { const xor = text.split('').map((c, i) => String.fromCharCode(c.charCodeAt(0) ^ SECRET_KEY.charCodeAt(i % SECRET_KEY.length)) ).join(''); return ENCRYPTION_PREFIX + btoa(xor); } catch (e) { console.error("Encryption failed", e); return text; } }; const decrypt = (text) => { if (!text) return ''; if (text.startsWith(ENCRYPTION_PREFIX)) { try { const raw = text.slice(ENCRYPTION_PREFIX.length); // Check if it's plain base64 or our custom XOR (simple try) const xor = atob(raw); const result = xor.split('').map((c, i) => String.fromCharCode(c.charCodeAt(0) ^ SECRET_KEY.charCodeAt(i % SECRET_KEY.length)) ).join(''); return result; } catch (e) { // Fallback if decryption fails (might be old plain text) return ''; } } // Backward compatibility: If no prefix, assume old plain text (or return empty if you want to force re-login) // For migration: Return text as is, so it populates the field, and next save will encrypt it. return text; }; // Simple TikTok icon sine Lucide might not have it or it varies const TikTokIcon = ({ size = 16, className = "" }) => ( ); // Cloud accounts get an auto-generated opaque id (os_) as username — // meaningless to the user, so the selector shows connected networks instead. const isAutoProfileId = (username) => /^os_[0-9a-f]/i.test(username || ""); const formatRetention = (seconds) => { if (seconds >= 86400) return `${Math.round(seconds / 86400)} day${seconds >= 172800 ? 's' : ''}`; if (seconds >= 3600) return `${Math.round(seconds / 3600)} hour${seconds >= 7200 ? 's' : ''}`; return `${Math.max(1, Math.round(seconds / 60))} min`; }; const ProfileNetworkIcons = ({ profile, size = 12 }) => ( ); const UserProfileSelector = ({ profiles, selectedUserId, onSelect, onConnect }) => { const [isOpen, setIsOpen] = useState(false); if (!profiles || profiles.length === 0) return null; const selectedProfile = profiles.find(p => p.username === selectedUserId) || profiles[0]; const autoId = isAutoProfileId(selectedProfile?.username); return (
{isOpen && (
{profiles.map((profile) => ( ))}
{/* For managed users this dropdown otherwise does nothing (one profile, nothing to switch) — its real job is being the door to connecting the greyed-out networks it displays. */} {onConnect && ( )}
)}
); }; const SESSION_KEY = 'openshorts_session'; // Matches the self-host JOB_RETENTION_SECONDS default. A restore whose job was // already purged server-side fails gracefully and clears the saved session. const SESSION_MAX_AGE = 86400000; // 24 hours // Mock polling function const pollJob = async (jobId) => { const res = await apiFetch(`/api/status/${jobId}`); if (!res.ok) throw new Error('Status check failed'); return res.json(); }; function App() { // Cloud auth/billing session (inert when billing is disabled). const { billingEnabled, isManaged, isSignedIn, me, plan, refreshMe, jobRetentionSeconds, localLlm } = useAuth(); const [showLogin, setShowLogin] = useState(false); const [showTopUp, setShowTopUp] = useState(false); const [showPlanChoice, setShowPlanChoice] = useState(false); const [tutorialPhase, setTutorialPhase] = useState(null); // null | intro | coach | celebrate const [showTrialUpgrade, setShowTrialUpgrade] = useState(false); const [topUpInfo, setTopUpInfo] = useState({}); // Durable R2 URLs (per clip index) for the current job — used as a fallback when // the ephemeral local /videos/ files have been cleaned up (e.g. after a reload). const [durableClips, setDurableClips] = useState({}); const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || ''); // Social API State - Load encrypted or plain const [uploadPostKey, setUploadPostKey] = useState(() => { const stored = localStorage.getItem('uploadPostKey_v3'); if (stored) return decrypt(stored); return ''; }); // ElevenLabs API State - Load encrypted const [elevenLabsKey, setElevenLabsKey] = useState(() => { const stored = localStorage.getItem('elevenLabsKey_v1'); if (stored) return decrypt(stored); return ''; }); // fal.ai API State - Load encrypted const [falKey, setFalKey] = useState(() => { const stored = localStorage.getItem('falKey_v1'); if (stored) return decrypt(stored); return ''; }); const [uploadUserId, setUploadUserId] = useState(() => localStorage.getItem('uploadUserId') || ''); const [userProfiles, setUserProfiles] = useState([]); // List of {username, connected: []} // Post-generation social nudge: shown at the results peak until the user // either connects a network or dismisses it. Only 2.7% of cloud users who // reach the social flow ever connect an account — this is the moment (clips // just appeared) with the best odds of moving that number. const [socialNudgeDismissed, setSocialNudgeDismissed] = useState(() => { try { return localStorage.getItem('os_social_nudge_dismissed') === '1'; } catch (_) { return false; } }); const [showKeyModal, setShowKeyModal] = useState(false); const [jobId, setJobId] = useState(null); const [status, setStatus] = useState('idle'); // idle, processing, complete, error const [results, setResults] = useState(null); // Best clips first. The backend hands them back in transcript order, which // buries the strongest one wherever it happens to fall in the video — and // the first card is the one people actually watch and publish. // // The ORIGINAL array position travels with each clip and is what gets passed // down as `index`: it is the clip's identity everywhere else (clip_index on // /api/subtitle, /api/edit and publishing, the clip-N.mp4 download name, the // saved per-clip project state). Sorting the array itself would silently // repoint all of that at the wrong clip. const rankedClips = useMemo(() => { const clips = results?.clips; if (!Array.isArray(clips)) return []; return clips .map((clip, index) => ({ clip, index })) .sort((a, b) => { const sa = Number.isFinite(a.clip?.predicted_score) ? a.clip.predicted_score : -1; const sb = Number.isFinite(b.clip?.predicted_score) ? b.clip.predicted_score : -1; // Ties (and clips with no score at all) keep transcript order. return sb - sa || a.index - b.index; }); }, [results]); // Bulk subtitles: apply one style to every clip of the job (triggered from // within a clip's subtitle modal via "apply to all"). const [bulkSub, setBulkSub] = useState({ running: false, current: 0, total: 0, errors: 0 }); const [downloadingAll, setDownloadingAll] = useState(false); // Pre-flight quality gate: { info: {max_height, min_height, cookies_invalid}, data } const [qualityGate, setQualityGate] = useState(null); const [logs, setLogs] = useState([]); // Collapsed on phones: the log tail is the least useful thing on a 360px // screen and it was pushing the actual clips a full scroll down. const [logsVisible, setLogsVisible] = useState(() => { try { return window.innerWidth >= 768; } catch { return true; } }); const [processingMedia, setProcessingMedia] = useState(null); const [activeTab, setActiveTab] = useState('dashboard'); // dashboard, settings // Mobile only: the full nav lives in a drawer behind the header's menu button. const [navOpen, setNavOpen] = useState(false); // Reopened-project state (paid mode): per-clip {index, server_file, active_layers} // restored from the backend so ResultCards resume editing where they left off. const [projectState, setProjectState] = useState(null); // True when the current job was reopened from the library: its source video // was never persisted, so the session must not fall back to /api/source. const [noSource, setNoSource] = useState(false); const [sessionRecovered, setSessionRecovered] = useState(false); const [showScheduleWeek, setShowScheduleWeek] = useState(false); // Clip editor overlay: index of the clip being edited, or null. const [editingClip, setEditingClip] = useState(null); const [reframingClip, setReframingClip] = useState(null); // Silent-success "saved" states for the settings key inputs (design.md: no alert popups) const [elevenLabsSaved, setElevenLabsSaved] = useState(false); const [falSaved, setFalSaved] = useState(false); // Sync state for original video playback const [syncedTime, setSyncedTime] = useState(0); const [isSyncedPlaying, setIsSyncedPlaying] = useState(false); const [syncTrigger, setSyncTrigger] = useState(0); const handleClipPlay = (startTime) => { setSyncedTime(startTime); setIsSyncedPlaying(true); setSyncTrigger(prev => prev + 1); }; const handleClipPause = () => { setIsSyncedPlaying(false); }; // --- Project persistence (paid mode) --- // Debounced sync of each clip's browser-only edit state (Remotion layers + // current server file) to the backend, so a reopened project resumes intact. const clipStateSync = useRef({ jobId: null, pending: {}, files: {}, timer: null }); // Read by in-flight async chases to notice that the user moved on to another job. const jobIdRef = useRef(jobId); useEffect(() => { jobIdRef.current = jobId; }, [jobId]); const flushClipState = () => { const s = clipStateSync.current; if (s.timer) { clearTimeout(s.timer); s.timer = null; } const entries = Object.entries(s.pending); if (!s.jobId || entries.length === 0) return; const clips = entries.map(([i, v]) => ({ index: Number(i), active_layers: v.activeLayers, server_file: v.serverVideoFile, })); s.pending = {}; apiFetch(`/api/projects/${s.jobId}/state`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clips }), }).catch(() => {}); }; // One /api/history read, reduced to this job's clips. const fetchDurableMap = async () => { const d = await apiJson('/api/history'); const map = {}; for (const v of (d.videos || [])) { if (v.job_id === jobId && v.clip_index != null) map[v.clip_index] = { url: v.view_url, filename: v.filename }; } return map; }; // A server-side edit rewrites the clip's file while the R2 re-archive behind it // is still in flight (_archive_clip_edit_bg is fire-and-forget), so the durable // map goes stale and the card falls back to streaming from the API. Re-read the // map on a backoff until the archived name matches the clip's new file, then it // can play from R2 again. Gives up quietly: staying on /videos is correct, just // slower, and is exactly what happens for self-hosted users all the time. const chaseDurableFile = async (index, expectedFile) => { const forJob = jobId; for (const delay of [2500, 6000, 15000, 30000]) { await new Promise((r) => setTimeout(r, delay)); if (jobIdRef.current !== forJob) return; let map; try { map = await fetchDurableMap(); } catch { return; } // A new job started mid-chase: this map describes the old one, so dropping // it here keeps it from overwriting the new job's URLs. if (jobIdRef.current !== forJob) return; setDurableClips(map); if (map[index]?.filename === expectedFile) return; } }; const handleClipStateChange = (index, state) => { if (!isManaged || !jobId) return; const s = clipStateSync.current; if (s.jobId !== jobId) { s.pending = {}; s.files = {}; s.jobId = jobId; } s.pending[index] = state; // Cards report on mount too, so only an actual change of server file means an // edit just landed. The first report per clip is the mount, never a chase. const files = s.files || (s.files = {}); const file = state?.serverVideoFile; if (file && files[index] !== file) { const isMount = files[index] === undefined; files[index] = file; if (!isMount) chaseDurableFile(index, file); } if (s.timer) clearTimeout(s.timer); s.timer = setTimeout(flushClipState, 2000); }; // A recut replaced the clip's server file with a fresh render (burned layers // reset), so update the results, the reopened-project state and the synced // per-clip edit state, and let the ResultCard remount from the new file. const handleClipRerendered = (index, data) => { const newFile = (data.new_video_url || '').split('/').pop(); setResults((prev) => { if (!prev?.clips?.[index]) return prev; const clips = prev.clips.slice(); clips[index] = { ...clips[index], video_url: data.new_video_url, start: data.start, end: data.end, recipe: data.recipe, }; return { ...prev, clips }; }); setProjectState((prev) => { if (!prev?.clips) return prev; return { ...prev, clips: prev.clips.map((c) => (c.index === index ? { ...c, server_file: newFile, active_layers: null } : c)), }; }); // The old durable R2 object is deleted when the recut is archived, so the // stale URL would 404 as a fallback; drop it until the next refresh. setDurableClips((prev) => { if (!(index in prev)) return prev; const next = { ...prev }; delete next[index]; return next; }); handleClipStateChange(index, { activeLayers: null, serverVideoFile: newFile }); }; // Reopen an archived project from the History tab: the backend re-downloads // its files from R2 into the server's working dir and returns the full state. const restoreProject = async (projectJobId) => { const data = await apiJson(`/api/projects/${projectJobId}/restore`, { method: 'POST' }); flushClipState(); setProjectState(data.project_state || null); setNoSource(true); setJobId(data.job_id); setResults(data.result || null); setLogs(['♻️ Project restored from your library.']); setProcessingMedia(null); setQualityGate(null); setStatus('complete'); setActiveTab('dashboard'); }; // Apply one subtitle style to every clip of the job, sequentially. const handleBulkSubtitles = async (options) => { const clips = results?.clips || []; const total = clips.length; if (!total) return; setBulkSub({ running: true, current: 0, total, errors: 0 }); let errors = 0; for (let i = 0; i < total; i++) { setBulkSub({ running: true, current: i + 1, total, errors }); try { const res = await apiFetch('/api/subtitle', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ job_id: jobId, clip_index: i, position: options.position, font_size: options.fontSize, font_name: options.fontName, font_color: options.fontColor, border_color: options.borderColor, border_width: options.borderWidth, bg_color: options.bgColor, bg_opacity: options.bgOpacity, style: options.style || 'classic', highlight_color: options.highlightColor || '#FFD700', effect: options.effect || 'none', base_opacity: options.baseOpacity ?? 1.0, uppercase: options.uppercase || false, // Chain from the clip's current server file (its video_url basename). input_filename: (clips[i].video_url || '').split('/').pop(), }), }); if (!res.ok) errors++; } catch { errors++; } } setBulkSub({ running: false, current: total, total, errors }); refreshMe(); // Refresh results so each ResultCard picks up its new subtitled video_url. try { const data = await pollJob(jobId); if (data.result) setResults(data.result); } catch { /* keep current results */ } }; const handleDownloadAll = async () => { if (!jobId) return; setDownloadingAll(true); try { const res = await apiFetch(`/api/jobs/${jobId}/download-all`); if (!res.ok) throw new Error(await res.text()); const blob = await res.blob(); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `openshorts_clips_${(jobId || '').slice(0, 8)}.zip`; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); } catch (e) { alert(`Download failed: ${e.message}`); } finally { setDownloadingAll(false); } }; // Session Recovery: Restore on mount useEffect(() => { try { const saved = localStorage.getItem(SESSION_KEY); if (!saved) return; const session = JSON.parse(saved); if (Date.now() - session.timestamp > SESSION_MAX_AGE) { localStorage.removeItem(SESSION_KEY); return; } if (session.jobId && session.status && session.status !== 'idle') { setJobId(session.jobId); setResults(session.results || null); // Restore the source preview. Older sessions (or uploads) saved no // media, so fall back to the backend-served source for this job — // except for reopened projects, whose source was never persisted. if (session.processingMedia) setProcessingMedia(session.processingMedia); else if (!session.noSource) setProcessingMedia({ type: 'server', payload: `/api/source/${session.jobId}` }); if (session.noSource) setNoSource(true); if (session.projectState) setProjectState(session.projectState); if (session.activeTab) setActiveTab(session.activeTab); // If was processing, resume polling; if complete/error, just show results setStatus(session.status === 'processing' ? 'processing' : session.status); setSessionRecovered(true); setTimeout(() => setSessionRecovered(false), 5000); } } catch (e) { localStorage.removeItem(SESSION_KEY); } }, []); // Session Recovery: Save state changes useEffect(() => { if (status === 'idle') { localStorage.removeItem(SESSION_KEY); return; } try { // URL (YouTube) media serializes as-is. Uploaded 'file' media is a blob // that can't be persisted, so point the recovered preview at the source // served by the backend instead of dropping it. let persistMedia = null; if (processingMedia?.type === 'url') persistMedia = processingMedia; else if (processingMedia && jobId) persistMedia = { type: 'server', payload: `/api/source/${jobId}` }; const sessionData = { jobId, status, results, processingMedia: persistMedia, activeTab, noSource, projectState, timestamp: Date.now() }; localStorage.setItem(SESSION_KEY, JSON.stringify(sessionData)); } catch (e) { // localStorage full or serialization error - ignore } // eslint-disable-next-line react-hooks/exhaustive-deps }, [jobId, status, results, activeTab, noSource, projectState]); useEffect(() => { // Encrypt Gemini Key too for consistency if desired, but user asked specifically about Social integration not saving well. // For now keeping gemini plain for compatibility unless requested. if (apiKey) localStorage.setItem('gemini_key', apiKey); }, [apiKey]); useEffect(() => { if (uploadPostKey) { localStorage.setItem('uploadPostKey_v3', encrypt(uploadPostKey)); } if (uploadUserId) { localStorage.setItem('uploadUserId', uploadUserId); } }, [uploadPostKey, uploadUserId]); useEffect(() => { if (elevenLabsKey) { localStorage.setItem('elevenLabsKey_v1', encrypt(elevenLabsKey)); } }, [elevenLabsKey]); useEffect(() => { if (falKey) { localStorage.setItem('falKey_v1', encrypt(falKey)); } }, [falKey]); useEffect(() => { if ((uploadPostKey || isManaged) && userProfiles.length === 0) { fetchUserProfiles({ silent: true }); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [uploadPostKey, isManaged]); // For managed users, fetch the durable R2 URLs of the current job's clips. The // preview player prefers them (free egress, edge-served, and not competing with // the renders for the API process), and falls back to /videos when the local // file is newer than the archived one or the signed link fails. // Kept fresh by chaseDurableFile after each edit and by the completion chase // below; until either lands, the card just streams from /videos. useEffect(() => { if (!isManaged || !jobId || !(results?.clips?.length)) { setDurableClips({}); return; } let cancelled = false; fetchDurableMap() .then((map) => { if (!cancelled) setDurableClips(map); }) .catch(() => {}); return () => { cancelled = true; }; // Keyed on the clip COUNT, not on results: the status poll hands back a new // results object every couple of seconds while the job runs, and this used to // re-read the history on every one of them. // eslint-disable-next-line react-hooks/exhaustive-deps }, [isManaged, jobId, results?.clips?.length]); // A job is marked complete BEFORE _archive_managed_job has finished uploading // (app.py:878), so the read above can land while R2 still has nothing for it and // every card would stream from the API for the rest of the session. Chase until // all clips have a durable copy. useEffect(() => { const count = results?.clips?.length || 0; if (!isManaged || !jobId || status !== 'complete' || !count) return; let cancelled = false; (async () => { for (const delay of [0, 3000, 8000, 20000, 40000]) { if (delay) await new Promise((r) => setTimeout(r, delay)); if (cancelled) return; let map; try { map = await fetchDurableMap(); } catch { return; } if (cancelled) return; setDurableClips(map); if (Object.keys(map).length >= count) return; } })(); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [isManaged, jobId, status, results?.clips?.length]); useEffect(() => { let interval; if ((status === 'processing' || status === 'completed') && jobId) { interval = setInterval(async () => { try { const data = await pollJob(jobId); console.log("Job status:", data); // Update results if available (real-time) if (data.result) { setResults(data.result); } if (data.status === 'completed') { setStatus('complete'); clearInterval(interval); refreshMe(); } else if (data.status === 'failed') { setStatus('error'); const errorMsg = data.error || (data.logs && data.logs.length > 0 ? data.logs[data.logs.length - 1] : "Process failed"); setLogs(prev => [...prev, "Error: " + errorMsg]); clearInterval(interval); refreshMe(); } else { // Update logs if available if (data.logs) setLogs(data.logs); } } catch (e) { console.error("Polling error", e); } }, 2000); } return () => clearInterval(interval); }, [status, jobId, refreshMe]); // silent: background auto-fetch — never alert(), just log. Managed users need // no local key (the server resolves its own); BYOK sends the header. const fetchUserProfiles = async ({ silent = false } = {}) => { if (!uploadPostKey && !isManaged) return; try { const res = await apiFetch('/api/social/user', { headers: uploadPostKey ? { 'X-Upload-Post-Key': uploadPostKey } : {} }); if (!res.ok) throw new Error("Failed to fetch"); const data = await res.json(); if (data.profiles && data.profiles.length > 0) { setUserProfiles(data.profiles); // Auto select first if none selected if (!uploadUserId) { setUploadUserId(data.profiles[0].username); } } else if (!silent) { alert("No profiles found for this API Key."); } } catch (e) { if (!silent) alert("Error fetching User Profiles. Please check key."); console.error(e); } }; // Hosted is paid-only (no BYOK core). Self-host uses BYOK keys. // `keysMissing` now means "self-host BYOK keys missing" — it never fires on hosted. // A self-hosted server running the moment picker on a local LLM // (LLM_BASE_URL) does not need a Gemini key for the core pipeline. const geminiOk = !!apiKey || !!localLlm; const keysMissing = !billingEnabled && (!geminiOk || !uploadPostKey); const needsPlan = billingEnabled && !isManaged; // hosted, signed-out or no active plan/trial // Fresh sign-up: Clip Generator tutorial (AuthContext set os_show_clip_tutorial // after the auth redirect). QA: #app?tutorial=1. Resume coach if they refreshed // mid-job. Runs once on mount so a later isSignedIn flip cannot reset intro→coach. useEffect(() => { let showTutorial = false; let resumeCoach = false; try { const q = new URLSearchParams((window.location.hash.split('?')[1] || '')); const qa = q.get('tutorial'); if (qa === '1') showTutorial = true; if (qa === 'coach') resumeCoach = true; if (qa === 'celebrate') { setTutorialPhase('celebrate'); return; } if (localStorage.getItem('os_show_clip_tutorial') === '1') showTutorial = true; if (localStorage.getItem('os_clip_tutorial') === 'coach') resumeCoach = true; } catch (_) { /* ignore */ } if (showTutorial) { setTutorialPhase('intro'); setActiveTab('dashboard'); } else if (resumeCoach) { setTutorialPhase('coach'); setActiveTab('dashboard'); } }, []); // Legacy: an older build may still have set os_show_plan_choice. Don't open it // on top of the tutorial. useEffect(() => { if (tutorialPhase) return; if (!(billingEnabled && isSignedIn)) return; let showPlans = false; try { showPlans = localStorage.getItem('os_show_plan_choice') === '1'; } catch (_) { /* ignore */ } if (showPlans) { setShowPlanChoice(true); try { localStorage.removeItem('os_show_plan_choice'); } catch (_) { /* ignore */ } } }, [billingEnabled, isSignedIn, tutorialPhase]); const tutorialLock = tutorialPhase === 'intro' || tutorialPhase === 'coach' || tutorialPhase === 'celebrate'; useEffect(() => { if (tutorialLock && activeTab !== 'dashboard') setActiveTab('dashboard'); }, [tutorialLock, activeTab]); useEffect(() => { if (tutorialPhase === 'coach' && status === 'complete' && (results?.clips?.length > 0)) { setTutorialPhase('celebrate'); track('ClipTutorialCompleted', { props: { clips: results.clips.length } }); } }, [tutorialPhase, status, results]); const finishTutorial = () => { try { localStorage.setItem('os_clip_tutorial', 'done'); } catch (_) { /* ignore */ } try { localStorage.removeItem('os_show_clip_tutorial'); } catch (_) { /* ignore */ } setTutorialPhase(null); }; const startTutorial = () => { try { localStorage.setItem('os_clip_tutorial', 'coach'); } catch (_) { /* ignore */ } try { localStorage.removeItem('os_show_clip_tutorial'); } catch (_) { /* ignore */ } track('ClipTutorialStarted'); setTutorialPhase('coach'); setActiveTab('dashboard'); }; const skipTutorial = () => { track('ClipTutorialSkipped', { props: { phase: tutorialPhase } }); finishTutorial(); }; // Included in the plan (fully managed, no keys): Clip Generator + YouTube Studio. // Advanced (bring your own fal.ai + ElevenLabs keys): AI Shorts + AI Agent. const INCLUDED_TOOL_TABS = ['dashboard', 'thumbnails']; const ADVANCED_TOOL_TABS = ['saasshorts', 'ai-agent']; const TOOL_NAMES = { dashboard: 'the Clip Generator', thumbnails: 'the YouTube Studio' }; const gateThisTab = needsPlan && INCLUDED_TOOL_TABS.includes(activeTab); // included tool, no plan yet const advancedThisTab = billingEnabled && ADVANCED_TOOL_TABS.includes(activeTab); // BYOK-notice tools // Social nudge visibility: managed users with clips on screen and no network // connected yet. userProfiles being empty (not yet fetched / none created) // also counts as "not connected" — that is the 97% case. const connectedSocials = ((userProfiles.find((p) => p.username === uploadUserId) || userProfiles[0])?.connected) || []; const showSocialNudge = isManaged && !socialNudgeDismissed && connectedSocials.length === 0 && !tutorialLock; // One Seen event per job, only when the banner actually rendered. const socialNudgeSeenRef = useRef(null); useEffect(() => { if (status === 'complete' && (results?.clips?.length > 0) && showSocialNudge && socialNudgeSeenRef.current !== jobId) { socialNudgeSeenRef.current = jobId; track('SocialNudgeSeen', { props: { clips: results.clips.length } }); } }, [status, results, showSocialNudge, jobId]); // Managed users connect their socials via Upload-Post's branded hosted page. const handleConnectSocials = async () => { try { const { access_url } = await apiJson('/api/social/connect', { method: 'POST' }); // Same tab so the connect page's redirectUrl brings the user back into the app. if (access_url) window.location.href = access_url; } catch (e) { alert('Could not open the connection page. Please try again.'); } }; // Open the Upload-Post white-label page (which includes the scheduling calendar) // in a new tab, for consulting/managing scheduled posts from the dashboard. const handleOpenCalendar = async () => { try { const { access_url } = await apiJson('/api/social/connect', { method: 'POST' }); if (access_url) window.open(access_url, '_blank', 'noopener'); } catch (e) { alert('Could not open the calendar. Please try again.'); } }; const handleProcess = async (data, forceLowQuality = false) => { // Hosted: must be signed in AND on an active plan/trial. Self-host: BYOK keys. if (billingEnabled) { if (!isSignedIn) { setShowLogin(true); return; } if (!isManaged) { window.location.hash = '#/pricing'; return; } } else if (keysMissing) { setShowKeyModal(true); return; } setStatus('processing'); setLogs(["Starting process..."]); setResults(null); // Studio handovers have no local media object; the preview switches to the // backend-served source once the job id is known. setProcessingMedia(data.type === 'thumbnail_session' ? null : data); setQualityGate(null); setProjectState(null); setNoSource(false); try { let body; // BYOK sends the Gemini header; managed users rely on the bearer token // that apiFetch attaches automatically. const headers = apiKey ? { 'X-Gemini-Key': apiKey } : {}; // Advanced generation controls: only sent when the user set them, so the // default request stays byte-identical to the pre-feature one. const advanced = { target_clips: data.targetClips || null, clip_min_seconds: data.clipMinSeconds || null, clip_max_seconds: data.clipMaxSeconds || null, // Sent explicitly both ways: absent means off for raw API callers, // but the dashboard always states the user's choice. auto_hook: data.autoHook ? '1' : '0', auto_hook_style: data.autoHook ? (data.autoHookStyle || 'classic') : null, // 'auto' is the server default, so only a deliberate choice travels. layouts: data.layout && data.layout !== 'auto' ? data.layout : null, }; if (data.type === 'url') { headers['Content-Type'] = 'application/json'; body = JSON.stringify({ url: data.payload, acknowledged: !!data.acknowledged, output_format: data.outputFormat || 'auto', force_low_quality: forceLowQuality, ...Object.fromEntries(Object.entries(advanced).filter(([, v]) => v != null)), }); } else if (data.type === 'thumbnail_session') { // Handover from Thumbnail Studio (issue #68): the video and transcript // already live server-side, keyed by the Studio session. headers['Content-Type'] = 'application/json'; body = JSON.stringify({ thumbnail_session_id: data.payload, acknowledged: !!data.acknowledged, output_format: data.outputFormat || 'auto', ...Object.fromEntries(Object.entries(advanced).filter(([, v]) => v != null)), }); } else { const formData = new FormData(); formData.append('file', data.payload); formData.append('acknowledged', data.acknowledged ? 'true' : 'false'); formData.append('output_format', data.outputFormat || 'auto'); for (const [k, v] of Object.entries(advanced)) { if (v != null) formData.append(k, v); } body = formData; } const res = await apiFetch('/api/process', { method: 'POST', headers, body }); if (!res.ok) throw new Error(await res.text()); const resData = await res.json(); // Quality gate: the source is below the min resolution — ask before burning // 20 min on it. On confirm we resend with force_low_quality. if (resData.needs_confirmation) { setStatus('idle'); setQualityGate({ info: resData.quality_check, data }); return; } setJobId(resData.job_id); if (data.type === 'thumbnail_session') { setProcessingMedia({ type: 'server', payload: `/api/source/${resData.job_id}` }); } // Minutes are reserved at job start, not at complete. refreshMe(); } catch (e) { if (e instanceof QuotaError) { setStatus('idle'); refreshMe(); // Trial users hit the trial minute cap → prompt them to activate the plan // now (unlocks full minutes). Active users → offer a top-up. if (me?.status === 'trialing') { setShowTrialUpgrade(true); } else { setTopUpInfo({ required: e.minutesRequired, remaining: e.minutesRemaining }); setShowTopUp(true); } return; } setStatus('error'); setLogs(l => [...l, `Error starting job: ${e.message}`]); } }; const handleReset = () => { // Flush any pending edit-state sync before dropping the project: the clips // themselves are already archived to R2 as they were edited. flushClipState(); setStatus('idle'); setJobId(null); setResults(null); setLogs([]); setProcessingMedia(null); setProjectState(null); setNoSource(false); localStorage.removeItem(SESSION_KEY); }; // --- UI Components --- // One nav definition drives all three surfaces: the desktop rail, the mobile // drawer, and the bottom tab bar. `short` is the tab-bar label — the full one // wraps to two lines in a 5-up bar on a 360px phone. const navItems = [ { id: 'dashboard', ord: '01', icon: LayoutDashboard, label: 'Clip Generator', short: 'clips', primary: true }, { id: 'saasshorts', ord: '02', icon: Sparkles, label: 'AI Shorts', short: 'ai shorts', byok: true, primary: true }, { id: 'ai-agent', ord: '03', icon: Bot, label: 'AI Agent', short: 'agent', byok: true }, { id: 'ugc-gallery', ord: '04', icon: LayoutGrid, label: 'UGC Gallery', short: 'gallery', primary: true }, { id: 'thumbnails', ord: '05', icon: Image, label: 'YouTube Studio', short: 'studio', primary: true }, ...(billingEnabled && isSignedIn ? [{ id: 'history', ord: '06', icon: History, label: 'History', short: 'history' }] : []), { id: 'settings', ord: '07', icon: Settings, label: 'Settings', short: 'settings' }, ]; const activeNav = navItems.find((n) => n.id === activeTab); // Escape closes the mobile drawer. The shell itself is overflow-hidden, so // there is no body scroll to lock behind it. useEffect(() => { if (!navOpen) return; const onKey = (e) => { if (e.key === 'Escape') setNavOpen(false); }; document.addEventListener('keydown', onKey); return () => document.removeEventListener('keydown', onKey); }, [navOpen]); const goToTab = (id) => { if (tutorialLock && id !== 'dashboard') return; setActiveTab(id); setNavOpen(false); }; const tabLocked = (id) => tutorialLock && id !== 'dashboard'; // Shared footer links (landing, repo, pricing, contact) — same list in the // desktop rail and the mobile drawer, so they can never drift apart. const NavFooterLinks = ({ collapsed = false }) => ( <> landing page open source {billingEnabled && ( plans & pricing )} info@openshorts.app ); // Desktop rail: icon-only from md, labelled from lg. Below md it is gone // entirely — an unlabelled 80px rail ate a fifth of a phone screen. const Sidebar = () => (
Logo
openshorts
); // Mobile drawer: the complete nav, reachable from the header's menu button. const MobileNavDrawer = () => (
setNavOpen(false)} aria-hidden="true" />
setNavOpen(false)}>
openshorts
); // Bottom tab bar: the four everyday destinations plus "more" for the rest. // It is a flex sibling of the scrolling pane rather than `fixed`, so nothing // ever hides behind it and no pane needs compensating padding. const MobileTabBar = () => { const tabs = navItems.filter((n) => n.primary); const moreActive = !tabs.some((t) => t.id === activeTab); return ( ); }; return ( /* h-dvh where supported: on mobile Safari/Chrome `100vh` is the tallest the viewport ever gets, so a h-screen shell hides its own bottom bar behind the browser chrome until the user scrolls. */
{navOpen && }
{/* Top Header */}
{/* Mobile: the drawer handle, and the section name the icon rail used to carry. Without it a phone has no "where am I". */} {activeNav?.label || 'openshorts'} {status !== 'idle' && ( )}
{userProfiles.length > 0 && ( )} {/* Cloud: minutes meter + account/sign-in. For free users the meter opens the upgrade modal — otherwise the only path to a plan is failing against the quota wall. */} {billingEnabled && isManaged && ( { if (plan === 'free') { setTopUpInfo({ context: 'upsell' }); setShowTopUp(true); } else { window.location.hash = '#/account'; } }} /> )} {billingEnabled && isSignedIn && !isManaged && ( )} {billingEnabled && !isSignedIn && ( )} {billingEnabled && isSignedIn && } {/* Hidden below sm: the standing banner underneath already says the same thing, and two warnings in a 360px header is just noise. */} {keysMissing && ( )}
{/* Persistent Missing Keys Banner — visible on every screen */} {keysMissing && activeTab !== 'settings' && (
Required API keys missing.{' '} {!geminiOk && !uploadPostKey ? 'Set your Gemini and Upload-Post API keys to use OpenShorts.' : !geminiOk ? 'Set your Gemini API key to use OpenShorts.' : 'Set your Upload-Post API key to use OpenShorts.'}
)} {/* Session Recovery Banner */} {sessionRecovered && (
Session recovered Your previous work has been restored.
)} {/* Included tools (Clip Generator, YouTube Studio): non-blocking trial prompt. */} {gateThisTab && } {/* Advanced tools (AI Shorts, AI Agent): BYOK fal.ai + ElevenLabs notice. */} {advancedThisTab && goToTab('settings')} />} {/* Main Workspace */}
{/* View: Settings */} {activeTab === 'settings' && (

07 · SETTINGS

Settings

Privacy: keys only live in your browser (sent to backend just to process)
{/* Self-hosted installs have no account page, so the agent how-to lives here; cloud users get it (with OAuth) in Account. */} {!billingEnabled &&
} {isManaged ? (

Included in your plan

Managed

Your plan includes the Clip Generator and YouTube Studio, fully managed — no API keys required. AI Shorts & dubbing use your own fal.ai / ElevenLabs keys (below). Connect your social accounts to publish directly.

) : billingEnabled ? (

Choose your plan

Free plan available

Generate shorts with zero setup — no API keys needed. Start free with 20 min/month, or go paid from $12/mo. Cancel anytime.

) : ( <>

Social Integration

Required

Required to publish your clips to TikTok, Instagram Reels, and YouTube Shorts via Upload-Post. Includes a free tier (no credit card required).

setUploadPostKey(e.target.value)} className="input-field" placeholder="ey..." />
Connect your Upload-Post account to enable one-click publishing.
Keys are only stored in your browser. They are sent to the backend only to process your request, never stored server-side.
)}

Video Translation

BYOK

For AI Shorts & dubbing — bring your own key. Translate your clips to different languages using ElevenLabs AI dubbing (billed by ElevenLabs). Not covered by your plan.

setElevenLabsKey(e.target.value)} className="input-field" placeholder="sk_..." />
Get your API key from ElevenLabs to enable video translation.
Keys are only stored in your browser. They are sent to the backend only to process your request, never stored server-side.

AI Shorts (UGC Videos)

BYOK

Generate UGC-style videos with AI actors for any product or business using fal.ai. Not covered by your plan — bring your own fal.ai + ElevenLabs keys (billed by those providers, ~$0.65-2 per video). Your plan still covers the AI script & orchestration.

setFalKey(e.target.value)} className="input-field" placeholder="fal_..." />
Get your API key from fal.ai to enable AI actor video generation.
Keys are only stored in your browser. Sent to backend only to process requests.
)} {/* View: SaaS Shorts */} {activeTab === 'saasshorts' && ( )} {/* View: AI Agent */} {activeTab === 'ai-agent' && (
{/* Header */}

03 · AI AGENT · AUTONOMOUS SKILL

Your Personal Clipping Team

Drop your videos in a folder and a team of AI clippers picks the viral moments, edits them, and queues them for your approval — like having a 24/7 short-form editing crew on autopilot.

{/* Mobile-format warning */}

Upload videos already in vertical (9:16) mobile format.

The agent does not reframe horizontal footage. Make sure every source video is shot or pre-cropped to mobile/portrait format before dropping it into the input folder.

{/* Workflow */}

1. Drop your videos

Put your long-form vertical footage in the watched folder. The skill picks one video per run.

2. AI clippers work

Whisper transcribes, Gemini 3 Flash spots viral beats, FFmpeg cuts each clip and adds a hook overlay.

3. You validate, it ships

Approve the candidates you like and the skill auto-publishes them to TikTok, Reels and YouTube Shorts via Upload-Post.

{/* Repo CTA */}

skill-autoshorts

The Claude Code skill that powers this workflow. Install it once and trigger it whenever you want a fresh batch of clips.

View on GitHub
git clone https://github.com/mutonby/skill-autoshorts
Daily batch — picks one long video per run
Whisper transcription with word-level timing
Gemini 3 Flash multimodal moment detection
Auto-publish to TikTok, Reels & YouTube Shorts
)} {/* View: UGC Gallery */} {activeTab === 'ugc-gallery' && (
)} {/* View: History */} {activeTab === 'history' && (
)} {activeTab === 'thumbnails' && ( { setActiveTab('dashboard'); // The Studio source is the user's own upload, published to their // own channel; the handover carries that same attestation. handleProcess({ type: 'thumbnail_session', payload: sessionId, acknowledged: true }); }} /> )} {/* View: Gallery */} {/* {activeTab === 'gallery' && ( )} */} {/* View: Dashboard (Idle) */} {activeTab === 'dashboard' && status === 'idle' && (
{/* On a phone the hero used to fill the fold on its own and push the uploader — the whole point of the screen — below it. The eyebrow, the display size and the gaps all shrink first. */}

01 · CLIP GENERATOR

Create Viral Shorts

Drop your long-form video below to instantly generate viral clips with AI.

{/* The same pipeline is an MCP server: point people at the one place that explains how to drive it from an agent. */} {!tutorialLock && (

Or let an agent do it:{' '} { if (!billingEnabled) { e.preventDefault(); goToTab('settings'); } }} className="text-ink2 underline underline-offset-2 hover:text-brass transition-colors" > connect Claude, ChatGPT or n8n →

)}
YouTube Instagram TikTok
)} {/* View: Processing / Results (Split View) */} {activeTab === 'dashboard' && (status === 'processing' || status === 'complete' || status === 'error') && (
{/* Left Panel: Preview & Status */}

Live Analysis

{status.toUpperCase()}
{/* Video Preview */} {processingMedia && ( )} {/* Phones only. The scan box drops its invented telemetry at this size and the log terminal below starts collapsed, so without this the screen would say nothing about what the job is actually doing. The log tail is the real answer. */} {status === 'processing' && (
{logs.length ? logs[logs.length - 1] : 'starting up…'}
)} {/* The render is dead time: the user is watching a progress bar with nothing to do, so this is where the one star ask goes. */} {status === 'processing' && (
)} {/* Logs Terminal */}
{logsVisible && (
{logs.map((log, i) => (
{new Date().toLocaleTimeString()} {log}
))} {status === 'processing' && (
_
)}
)}
{/* Right Panel: Results Grid */}
{/* Title + counters on one row, the two actions on their own row below. Wrapping them all together dropped a lone half-width "schedule week" pill under the title on a phone. */}

Generated Shorts {results?.clips?.length > 0 && ( {results.clips.length} Clips )} {results?.cost_analysis && !isManaged && ( GEMINI · ${results.cost_analysis.total_cost.toFixed(5)} )}

{results?.clips?.length > 0 && status === 'complete' && (
{results.clips.length > 1 && ( )}
)}
{status === 'complete' && results?.clips?.length > 0 && (
{/* Peak-moment upsell: they just SAW their clips — sell while they're proud of the result, before asking for stars. */} {plan === 'free' && ( )} {/* Distribution nudge at the same peak: clips on screen, publishing them is one connect away. Hidden once any network is linked or the user dismisses it. */} {showSocialNudge && (
Publish these clips straight from here.{' '} Connect your YouTube, TikTok or Instagram once — after that every clip is one click from posted.
{/* On a phone the dismiss X rides the copy, so the CTA below can run the full width of the card. */}
)} {/* Self-host only: cloud archives clips to the video library, here they really are gone once the retention sweep runs. */} {!billingEnabled && jobRetentionSeconds > 0 && (
Clips are kept for {formatRetention(jobRetentionSeconds)}, then deleted.{' '} Download what you want to keep, or raise JOB_RETENTION_SECONDS in your env.
)}
)}
{results && results.clips && results.clips.length > 0 ? (
{rankedClips.map(({ clip, index: i }) => ( setEditingClip(index)} onReframeClip={(index) => setReframingClip(index)} initialState={projectState?.clips?.find((c) => c.index === i) || null} onStateChange={handleClipStateChange} durable={durableClips[i]} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} geminiApiKey={apiKey} elevenLabsKey={elevenLabsKey} isManaged={isManaged} connectedPlatforms={(userProfiles.find((p) => p.username === uploadUserId) || userProfiles[0])?.connected ?? null} onConnectSocials={isManaged ? handleConnectSocials : null} onPlay={(time) => handleClipPlay(time)} onPause={handleClipPause} onBulkSubtitle={handleBulkSubtitles} clipCount={results.clips.length} bulkProgress={bulkSub} /> ))}
) : ( status === 'processing' ? (

Waiting for clips...

They appear here one by one as each finishes rendering.

) : status === 'error' ? (

Generation failed.

) : null )}
)}
{/* Phone navigation. A flex sibling of the scrolling pane, not a fixed overlay, so content is never trapped behind it. */}
{/* Missing API Key Modal */} setShowKeyModal(false)} eyebrow="SETUP" title={!geminiOk && !uploadPostKey ? 'Required API Keys Missing' : !geminiOk ? 'Gemini API Key Required' : 'Upload-Post API Key Required'} footer={
} >

OpenShorts needs both a Gemini API key and an Upload-Post API key. Both have free tiers.

{/* Gemini block */}

{apiKey ? : } Gemini API Key {apiKey && — set}

{!apiKey && ( <>
  1. Go to aistudio.google.com/app/apikey
  2. Sign in with your Google account
  3. Click "Create API Key"
  4. Copy the key and paste it below
{ if (e.key === 'Enter' && e.target.value.trim()) { setApiKey(e.target.value.trim()); } }} /> )}
{/* Upload-Post block */}

{uploadPostKey ? : } Upload-Post API Key {uploadPostKey && — set}

{!uploadPostKey && ( <>

Required to publish your clips to TikTok, Instagram Reels, and YouTube Shorts. Free tier available, no credit card needed.

  1. Register at app.upload-post.com
  2. Connect your TikTok, Instagram, or YouTube accounts
  3. Go to API Keys and generate one
  4. Paste it below
{ if (e.key === 'Enter' && e.target.value.trim()) { setUploadPostKey(e.target.value.trim()); } }} /> )}
setShowScheduleWeek(false)} clips={results?.clips || []} jobId={jobId} uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} isManaged={isManaged} /> {/* Pre-flight quality gate */} {qualityGate && ( setQualityGate(null)} size="md" eyebrow="HEADS UP" title="low source quality">

YouTube only offers {qualityGate.info.max_height}p for this video (below the {qualityGate.info.min_height}p we recommend). Processing anyway will produce lower-quality clips.

{qualityGate.info.cookies_invalid && (

Your YouTube cookies look expired — refreshing them (export again from an incognito window) often unlocks HD.

)}
)} {editingClip !== null && results?.clips?.[editingClip] && ( setEditingClip(null)} onRerendered={handleClipRerendered} /> )} {reframingClip !== null && results?.clips?.[reframingClip] && ( setReframingClip(null)} onReframed={handleClipRerendered} /> )} {showLogin && setShowLogin(false)} />} {tutorialPhase && ( )} {showPlanChoice && setShowPlanChoice(false)} />} {showTopUp && ( setShowTopUp(false)} required={topUpInfo.required} remaining={topUpInfo.remaining} context={topUpInfo.context || 'wall'} /> )} {showTrialUpgrade && ( setShowTrialUpgrade(false)} /> )}
); } export default App;