import React, { useState, useEffect, useCallback, useRef } from 'react'; import { Rocket, Youtube, Loader2, RefreshCw, Play, CheckCircle2, AlertTriangle, Clock, Scissors, Send, ExternalLink, FolderOpen, Lock, } from 'lucide-react'; import { apiJson } from '../lib/api'; import { track } from '../lib/analytics'; // Autopilot: every new video on the user's connected YouTube channel is turned // into shorts automatically, and optionally the best ones are scheduled on // their socials, one a day. The channel comes from the Upload-Post connection // the app already uses for posting (GET /api/uploadposts/media under the hood), // so there is nothing to paste: connect once, switch it on. const PLATFORM_LABELS = { tiktok: 'TikTok', instagram: 'Instagram', youtube: 'YouTube Shorts' }; const ERROR_TEXT = { plan_required: 'Autopilot is paused: it needs an active Starter, Creator or Pro plan.', youtube_not_connected: 'Connect your YouTube channel so Autopilot can see your new videos.', youtube_reauth_required: 'YouTube asked to reconnect your channel. Reconnect it to keep Autopilot running.', channel_unavailable: 'We could not read your channel on the last check. We will try again shortly.', }; const REASON_TEXT = { youtube_short: 'already a short', private_video: 'private on YouTube — set it to Unlisted to clip it', out_of_minutes: 'out of minutes', too_short: 'too short to clip', unavailable: 'not available yet (private or processing)', low_quality: 'only low quality available', timeout: 'did not finish', processing_failed: 'processing failed', publish_partial: 'some clips could not be scheduled', url_ingest_disabled: 'links are disabled on this server', }; const fmtDate = (iso) => (iso ? new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : ''); // ApiError.detail is a string or {error, message}; never hand an object to JSX. const errText = (e, fallback) => { const d = e?.detail; if (typeof d === 'string' && d) return d; if (d && typeof d.message === 'string') return d.message; return fallback; }; const browserTimezone = () => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'; } catch { return 'UTC'; } }; function Switch({ checked, onChange, disabled, label }) { return ( onChange(e.target.checked)} className="sr-only peer" /> ); } function StatusBadge({ run }) { if (!run) return not clipped; const { status } = run; if (status === 'completed') { return ( {run.clips_count || 0} clips {run.posted_count ? ` · ${run.posted_count} scheduled` : ''} ); } if (status === 'processing' || status === 'queued') { return clipping; } if (status === 'skipped') return {REASON_TEXT[run.reason] || 'skipped'}; return {REASON_TEXT[run.reason] || 'failed'}; } export default function AutopilotTab({ onOpenProject, onUpgrade, justConnected }) { const [data, setData] = useState(null); // GET /api/autopilot const [videos, setVideos] = useState(null); // GET /api/autopilot/videos const [videosError, setVideosError] = useState(null); const [loadError, setLoadError] = useState(''); const [saving, setSaving] = useState(false); const [running, setRunning] = useState(null); // video id being submitted const [notice, setNotice] = useState(''); // Feedback for "clip it", shown next to the list: the page-level notice sits // at the top of the tab, off screen from the button, so a click looked dead. const [listNotice, setListNotice] = useState(''); const [opening, setOpening] = useState(null); const pollRef = useRef(null); const load = useCallback(async () => { try { const d = await apiJson('/api/autopilot'); setData(d); setLoadError(''); if (d.youtube) { const v = await apiJson('/api/autopilot/videos'); setVideos(v.videos || []); setVideosError(v.error || null); } else { setVideos([]); } } catch (e) { setLoadError(errText(e, 'Could not load Autopilot. Please try again.')); } }, []); useEffect(() => { load(); }, [load]); // Coming back from the connect page (#app?tab=autopilot&connected=1). useEffect(() => { if (justConnected) { setNotice('Accounts connected.'); track('AutopilotChannelConnected'); } }, [justConnected]); // Refresh while something is being clipped, so the badge flips on its own. const busy = (data?.runs || []).some((r) => r.status === 'processing' || r.status === 'queued'); useEffect(() => { clearInterval(pollRef.current); if (busy) pollRef.current = setInterval(load, 20000); return () => clearInterval(pollRef.current); }, [busy, load]); const save = useCallback(async (patch) => { setSaving(true); setNotice(''); try { const d = await apiJson('/api/autopilot', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ timezone: browserTimezone(), ...patch }), }); setData((prev) => ({ ...prev, settings: d.settings })); return d.settings; } catch (e) { setNotice(errText(e, 'Could not save. Please try again.')); return null; } finally { setSaving(false); } }, []); const connect = useCallback(async () => { track('AutopilotConnectClick'); try { const { access_url } = await apiJson('/api/social/connect?return_to=autopilot', { method: 'POST' }); if (access_url) window.location.href = access_url; } catch (e) { setNotice(errText(e, 'Could not open the connection page. Please try again.')); } }, []); const toggleEnabled = useCallback(async (on) => { const s = await save(on ? { enabled: true, rights_ack: true } : { enabled: false }); if (s) { track(on ? 'AutopilotEnabled' : 'AutopilotDisabled', { props: { autopublish: String(!!s.autopublish) } }); setNotice(on ? 'Autopilot is on. Your next video will be clipped automatically.' : 'Autopilot paused.'); } }, [save]); const togglePlatform = useCallback((p) => { const cur = data?.settings?.publish_platforms || []; const next = cur.includes(p) ? cur.filter((x) => x !== p) : [...cur, p]; save({ publish_platforms: next }); }, [data, save]); const runNow = useCallback(async (video) => { setRunning(video.id); setListNotice(''); try { const r = await apiJson('/api/autopilot/run', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ video_id: video.id }), }); track('AutopilotManualRun', { props: { status: r.status } }); if (r.status === 'processing') setListNotice(`Clipping “${video.title || 'your video'}”. We will email you when the clips are ready.`); else setListNotice(`Not clipped: ${REASON_TEXT[r.reason] || r.reason || r.status}.`); } catch (e) { if (e?.name === 'QuotaError') setListNotice('You are out of minutes for this period.'); else setListNotice(errText(e, 'Could not start the job.')); } finally { setRunning(null); load(); } }, [load]); const openProject = useCallback(async (jobId) => { if (!onOpenProject || opening) return; setOpening(jobId); try { await onOpenProject(jobId); } catch { setNotice('Could not open this project yet. Find it in History.'); } setOpening(null); }, [onOpenProject, opening]); if (!data && !loadError) { return
; } const s = data?.settings || {}; const yt = data?.youtube; const accounts = data?.accounts || {}; const eligible = !!data?.eligible; const limits = data?.limits || { max_minutes_choices: [10, 20, 30, 45, 60, 90], max_clips_to_publish: 5, platforms: ['tiktok', 'instagram', 'youtube'] }; const runs = data?.runs || []; const errorText = s.enabled && s.last_error ? ERROR_TEXT[s.last_error] : null; return (

02 · AUTOPILOT

your channel, clipped on its own

Publish on YouTube as usual. Autopilot notices every new video, turns it into shorts and emails you when they are ready. Switch on autopublish and the best ones go out on TikTok, Instagram and YouTube Shorts, one a day.

{loadError &&

{loadError}

} {notice && (
{notice}
)} {/* Plan gate: Autopilot spends minutes on its own, so it is a paid feature. */} {!eligible && (

included in paid plans

Autopilot runs on your plan's minutes, so it comes with Starter, Creator and Pro. Every new upload turns into shorts without you opening OpenShorts.

)} {/* 1 · channel */}

01 · CHANNEL

{yt ? (

{yt.display_name || yt.handle} {yt.handle}

) : (

no YouTube channel connected yet

)}
{(!yt || yt.reauth_required) && ( )} {yt && !yt.reauth_required && ( )}
{yt?.reauth_required && (

YouTube needs you to reconnect this channel.

)}
{/* 2 · switch */}

02 · AUTOPILOT

{s.enabled ? 'on: new videos are clipped automatically' : 'off'}

Only videos you publish from now on. Up to {limits.daily_auto || 1} video a day, the first {' '}{s.max_minutes || 30} minutes of each. Shorts are skipped.

{s.enabled && s.last_checked_at && (

last check {fmtDate(s.last_checked_at)} · every hour

)}
{errorText && (

{errorText}

)}
{/* 3 · autopublish */}

03 · AUTOPUBLISH

{s.autopublish ? 'the best clips are scheduled for you' : 'off: you review and post the clips yourself'}

Picks the {s.clips_to_publish || 3} highest-scoring clips of each video and schedules them one a day at {String(s.publish_hour ?? 17).padStart(2, '0')}:00 ({s.timezone || browserTimezone()}).

{ track('AutopilotAutopublish', { props: { on: String(on) } }); save({ autopublish: on }); }} />
{s.autopublish && ( <>
publish to
{limits.platforms.map((p) => { const connected = !!accounts[p]; const on = (s.publish_platforms || []).includes(p); return connected ? ( ) : ( ); })}
{(s.publish_platforms || []).length === 0 && (

Pick at least one account, or nothing gets published.

)} {(s.publish_platforms || []).includes('tiktok') && (

TikTok clips arrive as drafts in your TikTok inbox: open the app to post them.

)}
)}
{/* 4 · channel videos */} {yt && (

04 · YOUR LATEST VIDEOS

Clip any of them now, or let Autopilot handle the next one.

{listNotice && (
{listNotice}
)} {videosError &&

{ERROR_TEXT[videosError] || 'Could not read your channel.'}

} {videos === null &&
} {videos && videos.length === 0 && !videosError && (

No videos on this channel yet.

)}
{(videos || []).map((v) => { const run = v.run; // Skipped runs can be retried too: private videos used to be // misread as Shorts, and a real Short just skips again. const canRun = eligible && (!run || run.status === 'failed' || run.status === 'skipped'); return (
{v.thumbnail_url ? ( ) : (
)}
{v.title || v.id}
{fmtDate(v.published_at)}
{run?.status === 'completed' && run.job_id ? ( ) : canRun ? ( ) : null}
); })}
)} {/* 5 · activity */} {runs.length > 0 && (

05 · ACTIVITY

{runs.map((r) => (
{r.status === 'completed' ? : (r.status === 'processing' || r.status === 'queued') ? : r.status === 'skipped' ? : } {r.video_title || r.video_id} {r.posted_count ? {r.posted_count} scheduled : null} {r.trigger === 'manual' ? 'manual' : 'auto'} · {fmtDate(r.created_at)}
))}
)}
); }