feat(autopilot): clip every new video on the connected YouTube channel

Most subscribers use OpenShorts on one day and cancel. Autopilot makes the
value recur: once switched on, every new upload on the user's YouTube channel
(listed through the existing Upload-Post connection, no scraping) is sent
through the normal /api/process pipeline, the user gets an email when the
clips are ready, and with autopublish on the best clips are scheduled on
their socials, one a day.

- cloud/autopilot.py: poller, in-process job submission as the user,
  completion hook, autopublish, and /api/autopilot{,/videos,/run}
- guard rails: only videos published after switching on, max 3 days old,
  1 automatic job per user per day, first N minutes per video, Shorts skipped,
  paid plans only, dedupe by (user, video) across the deploy handover
- dashboard: new Autopilot tab (sidebar + mobile menu, #app?tab=autopilot)
- connect page can return to the Autopilot tab
- analytics: ClipsDelivered/JobFailed now report source=url and the plan

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
victorcavero14 2026-09-22 21:36:19 +02:00
parent ea789999e8
commit 8f57560fa5
15 changed files with 1720 additions and 20 deletions

View file

@ -315,6 +315,9 @@ portrait clip cannot reproduce the shrink either.
| POST | `/mcp` | MCP server (JSON-RPC): the pipeline as agent tools |
| POST/GET/DELETE | `/api/keys` | User API keys (cloud mode, session JWT only) |
| DELETE | `/api/account` | Erase the account and everything in it (GDPR art. 17) |
| GET/PUT | `/api/autopilot` | Autopilot settings, connected accounts, recent runs (cloud only) |
| GET | `/api/autopilot/videos` | Latest uploads of the connected YouTube channel + what Autopilot did |
| POST | `/api/autopilot/run` | Clip one channel video now (`{video_id}`) |
### Agent access (MCP, API keys, webhooks)
@ -356,6 +359,41 @@ portrait clip cannot reproduce the shrink either.
can carry durable download links; survives redeploys via the resume manifest.
`PUBLIC_API_URL` env sets the absolute-URL base when behind a proxy.
### Autopilot (`cloud/autopilot.py`, dashboard tab "Autopilot")
Cloud-only retention feature: every new video on the user's connected YouTube
channel becomes clips on its own, and optionally the best ones are scheduled
on their socials, one a day. Paid plans only (it spends minutes unattended).
- **Channel listing** comes from Upload-Post, not scraping:
`GET /api/uploadposts/media?platform=youtube&user=os_<id>` reads the
channel's uploads playlist with the user's own OAuth token, so it includes
videos uploaded straight to YouTube. There is no push from Upload-Post, so a
loop polls (tick 5 min, each user at most once per 55 min).
- **Jobs go through the normal pipeline**: an in-process `POST /api/process`
(`httpx.ASGITransport`, like the MCP server) authenticated with a freshly
issued session JWT for the user. Metering, the probe, the per-plan job
limit, the quality gate and the download proxies apply unchanged. The
per-job content attestation is recorded once as `rights_ack_at`.
- **Guard rails**: only videos published after `enabled_at` (switching on never
clips the back catalogue) and at most 3 days old; 1 automatic job per user
per 24 h; `max_minutes` per video (default 30, sent as the partial-clip
`max_minutes`); YouTube Shorts are skipped (`HEAD /shorts/<id>` answers 200
for a Short and 303 to `/watch` for a regular video, checked on prod IPs).
- **Dedupe across the deploy handover**: two containers poll at once during a
rolling deploy, so a video is claimed by INSERTing its `autopilot_runs` row
(unique `user_id, video_id`) before anything is submitted. A draining
instance stops polling. A 429 (job limit) or 5xx drops the claim to retry.
- **Completion**: `run_job_wrapper` calls `on_job_finished` after the R2
archive. A guarded UPDATE (`status='processing'` → final) makes it once-only;
it sends the Autopilot email (replacing the generic clips-ready one) and,
with autopublish on, uploads the top `clips_to_publish` clips by
`predicted_score` to Upload-Post in a background task, scheduled one a day at
`publish_hour` in the user's IANA `timezone`. Runs stuck in processing for
6 h are marked `timeout`.
- `AUTOPILOT_DISABLED=1` turns the poller off without touching the API.
- Both tables are in `account.USER_OWNED_TABLES`.
### Account erasure (GDPR art. 17)
`DELETE /api/account` (`cloud/account.py`, dashboard: Account → Delete account)

22
app.py
View file

@ -1373,6 +1373,9 @@ async def run_job_wrapper(job_id):
await _settle_reservation(job_id, job)
# Archive the completed clips to the user's durable R2 library (history).
await _archive_managed_job(job_id)
# Autopilot bookkeeping + autopublish (before the generic clips-ready
# email, which it replaces for its own jobs).
await _autopilot_job_finished(job_id, job)
# Fire the caller's webhook (after archive, so durable links exist).
await _notify_job_webhook(job_id)
# Operational alerting for managed jobs (proxy out of credits / failures).
@ -1426,6 +1429,18 @@ def _archive_clip_edit_bg(job_id: str, clip_index: int, filename: str):
asyncio.create_task(_run())
async def _autopilot_job_finished(job_id, job):
if not BILLING_ENABLED or not job or not job.get('user_id'):
return
try:
reason = None
if job.get('status') != 'completed':
reason = _alerts._classify_failure(_job_error_text(job.get('logs', [])))
await cloud.autopilot.on_job_finished(job_id, job, reason)
except Exception as e:
print(f"⚠️ Autopilot completion error for {job_id}: {e}")
async def _notify_clips_ready(job_id):
"""Email the owner when their clips finish — processing takes minutes, so
this lets them close the tab. Once per job (email_sent flag)."""
@ -1574,7 +1589,7 @@ async def _track_job_outcome(job, ok, err):
job_index=job_index,
clips=clips if ok else None,
plan=job.get('user_plan'),
source="url" if job.get('url') else "upload",
source="url" if _job_source_url(job) else "upload",
reason=(_alerts._classify_failure(err) if not ok and err else None),
)
except Exception as e:
@ -1810,6 +1825,9 @@ async def lifespan(app: FastAPI):
# Account erasure lives in cloud/, which can't import app.py; hand it the
# one thing only this module can do — wipe the local working files.
cloud.account.register_local_purge(_purge_local_jobs_for_user)
# Autopilot: watch connected YouTube channels for new videos. Paused
# while this instance drains so only the new container submits jobs.
cloud.autopilot.start(app, is_active=lambda: not _draining)
# Nag on Telegram while the residential proxy is down/out of credits —
# a single job-failure alert is easy to miss and ingest stays broken
# until someone tops the balance up.
@ -2669,6 +2687,8 @@ async def process_endpoint(
'webhook_url': webhook_url,
'webhook_secret': webhook_secret,
'base_url': api_base,
# Read by the ClipsDelivered/JobFailed analytics event (plan).
'user_plan': user_plan,
}
# Persist the owner so recovered jobs keep their multi-tenant guard after a

View file

@ -27,7 +27,7 @@ def setup_sync(app):
app.add_middleware(SessionMiddleware, secret_key=settings.jwt_secret)
from . import (auth, oauth, billing, social_profiles, videos, api_keys,
account, mcp_oauth, marketing)
account, mcp_oauth, marketing, autopilot)
oauth.register()
billing._init_stripe()
app.include_router(auth.router)
@ -38,6 +38,8 @@ def setup_sync(app):
app.include_router(api_keys.router)
app.include_router(mcp_oauth.router)
app.include_router(account.router)
# Autopilot: clip new videos from the user's connected YouTube channel.
app.include_router(autopilot.router)
# Unsubscribe from the one commercial email (LSSI art. 21.2).
app.include_router(marketing.router)

View file

@ -41,7 +41,7 @@ from . import database, email_policy, storage
from .models import (
User, Subscription, CreditTopup, UsageLedger, MagicLinkToken,
SignupAttribution, ApiKey, UploadPostProfile, UserVideo, ClipExpiryWarning,
Project, AccountDeletion, OAuthCode,
Project, AccountDeletion, OAuthCode, AutopilotRun, AutopilotSettings,
)
# Every table that holds rows belonging to a user, child-first (clip_expiry_
@ -56,6 +56,7 @@ from .models import (
USER_OWNED_TABLES = (
ClipExpiryWarning, UserVideo, Project, UsageLedger, CreditTopup,
Subscription, ApiKey, SignupAttribution, UploadPostProfile, OAuthCode,
AutopilotRun, AutopilotSettings,
)
# The optional "why are you leaving" answer, as a closed list. It was a free

844
cloud/autopilot.py Normal file
View file

@ -0,0 +1,844 @@
"""Autopilot: clip every new video on the user's YouTube channel, by itself.
The user connects YouTube once (the same Upload-Post profile the dashboard
already uses for posting) and switches Autopilot on. From then on:
1. A poller lists the channel's latest uploads through Upload-Post
(``GET /api/uploadposts/media?platform=youtube``). That endpoint reads the
channel's uploads playlist with the user's own OAuth token, so it sees
videos uploaded straight to YouTube, not just ones posted through us, and
no scraping is involved.
2. A video published after Autopilot was switched on becomes a job on the
normal pipeline: an in-process ``POST /api/process`` with the video URL,
authenticated as the user. Metering, the minute reservation, the probe, the
per-plan job limit and the download proxies all apply exactly as when the
user pastes the link themselves, so nothing here has to be kept in sync.
3. When the job finishes, ``on_job_finished`` (called from app.py's job
wrapper) records the outcome, emails the user, and, if they asked for it,
schedules the best clips on their connected accounts, one a day.
Why this exists: most subscribers used the product on one day and never came
back (6 of 33 retained subscribers had used it on 3+ distinct days, sep-2026).
Value that arrives every week without the user doing anything is the lever.
Guard rails, each one a cost that would otherwise scale with the channel:
- only videos published after ``enabled_at`` and at most ``MAX_VIDEO_AGE`` old,
so switching it on never processes the back catalogue;
- ``DAILY_AUTO_LIMIT`` automatic jobs per user per 24 h (downloads go through
the shared proxy pool);
- ``max_minutes`` per video (the first N minutes of a long stream), so one
two-hour live does not empty the month;
- YouTube Shorts are skipped: they already are short-form.
"""
import asyncio
import os
import uuid
from datetime import datetime, timedelta, timezone
from typing import Iterable, List, Optional
import httpx
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from sqlalchemy import and_, delete, func, select, update
from sqlalchemy.exc import IntegrityError
from . import database
from .config import settings
from .models import AutopilotRun, AutopilotSettings, UploadPostProfile, User
router = APIRouter()
API_BASE = "https://api.upload-post.com/api"
PAID_PLANS = ("starter", "creator", "pro")
PUBLISH_PLATFORMS = ("tiktok", "instagram", "youtube")
MAX_MINUTES_CHOICES = (10, 20, 30, 45, 60, 90)
DEFAULT_MAX_MINUTES = 30
DEFAULT_CLIPS_TO_PUBLISH = 3
MAX_CLIPS_TO_PUBLISH = 5
DEFAULT_PUBLISH_HOUR = 17
TICK_SECONDS = 300 # how often the loop wakes up
CHECK_EVERY = timedelta(minutes=55) # per-user channel check interval
MAX_VIDEO_AGE = timedelta(days=3) # older uploads are never picked automatically
DAILY_AUTO_LIMIT = 1 # automatic jobs per user per rolling 24 h
MANUAL_DAILY_LIMIT = 5 # "clip this video" clicks per user per 24 h
STALE_RUN_AFTER = timedelta(hours=6) # a job that never reported back
CHANNEL_LIST_LIMIT = 12
# Run statuses. "queued" only exists between the INSERT that claims a video and
# the /api/process answer; "processing" means a job id exists.
QUEUED, PROCESSING, COMPLETED, FAILED, SKIPPED = (
"queued", "processing", "completed", "failed", "skipped")
_app = None # the FastAPI app, for in-process calls (set by start())
_is_active = None # callable: False while this instance drains for a deploy
_task = None # strong ref: the loop only keeps weak references to tasks
_bg_tasks = set()
# --------------------------------------------------------------------------- #
# Pure helpers (unit-tested without a database)
# --------------------------------------------------------------------------- #
def parse_ts(value) -> Optional[datetime]:
"""An Upload-Post/YouTube timestamp ('2026-09-22T10:01:35Z') as aware UTC."""
if not value:
return None
if isinstance(value, datetime):
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
try:
dt = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except ValueError:
return None
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
def pick_new_videos(media: Iterable[dict], baseline: Optional[datetime],
seen_ids: set, now: datetime,
max_age: timedelta = MAX_VIDEO_AGE) -> List[dict]:
"""Channel uploads Autopilot should clip now, oldest first.
A video qualifies when it was published after the baseline (the moment
Autopilot was switched on), is not older than ``max_age``, and has not been
picked before. Items without an id or a parseable timestamp are ignored:
better to miss one than to clip the back catalogue.
"""
if baseline is None:
return []
out = []
for item in media or []:
vid = (item or {}).get("id")
published = parse_ts((item or {}).get("timestamp"))
if not vid or published is None or vid in seen_ids:
continue
if published <= baseline or now - published > max_age:
continue
out.append(item)
out.sort(key=lambda m: parse_ts(m.get("timestamp")))
return out
def rank_clips(clips: List[dict], n: int) -> List[int]:
"""Indices of the ``n`` clips worth publishing, best first.
``predicted_score`` is the second-pass virality score the selector already
computes; clips without one keep their pipeline order after the scored ones.
"""
if n <= 0 or not clips:
return []
def score(i):
try:
return float(clips[i].get("predicted_score"))
except (TypeError, ValueError):
return float("-inf")
order = sorted(range(len(clips)), key=lambda i: (-score(i), i))
return order[:n]
def schedule_slots(now: datetime, n: int, hour: int = DEFAULT_PUBLISH_HOUR,
tz_name: Optional[str] = None) -> List[str]:
"""``n`` local datetimes (ISO, no offset) at ``hour``, one per day.
Starts today if the slot is still at least an hour away, else tomorrow.
Upload-Post takes the local wall time plus an IANA ``timezone`` parameter.
"""
tz = _zone(tz_name)
local_now = now.astimezone(tz)
first = local_now.replace(hour=hour % 24, minute=0, second=0, microsecond=0)
if first - local_now < timedelta(hours=1):
first += timedelta(days=1)
return [(first + timedelta(days=k)).strftime("%Y-%m-%dT%H:%M:%S") for k in range(n)]
def _zone(tz_name: Optional[str]):
try:
from zoneinfo import ZoneInfo
return ZoneInfo(tz_name) if tz_name else timezone.utc
except Exception:
return timezone.utc
def outcome_from_process(status_code: int, body) -> dict:
"""Map an /api/process answer to what the run becomes.
Returns ``{"status", "reason", "job_id", "retry"}``. ``retry`` means the
claim should be dropped and the video tried again on a later tick (the
user is at their simultaneous-job limit, or the server hiccuped).
"""
body = body if isinstance(body, dict) else {}
detail = body.get("detail")
if status_code == 200:
if body.get("needs_confirmation"):
return {"status": SKIPPED, "reason": "low_quality", "job_id": None, "retry": False}
if body.get("job_id"):
return {"status": PROCESSING, "reason": None, "job_id": body["job_id"], "retry": False}
return {"status": FAILED, "reason": "no_job_id", "job_id": None, "retry": False}
if status_code == 402:
return {"status": SKIPPED, "reason": "out_of_minutes", "job_id": None, "retry": False}
if status_code == 429:
return {"status": QUEUED, "reason": "busy", "job_id": None, "retry": True}
if status_code == 400:
text = str(detail or "").lower()
if "short-form" in text or "only" in text and "long" in text:
return {"status": SKIPPED, "reason": "too_short", "job_id": None, "retry": False}
return {"status": SKIPPED, "reason": "unavailable", "job_id": None, "retry": False}
if status_code == 403:
return {"status": SKIPPED, "reason": "url_ingest_disabled", "job_id": None, "retry": False}
if status_code >= 500:
return {"status": QUEUED, "reason": "server_error", "job_id": None, "retry": True}
return {"status": FAILED, "reason": f"http_{status_code}", "job_id": None, "retry": False}
def clean_platforms(values) -> List[str]:
"""Keep the platforms Autopilot can publish to, in a stable order."""
wanted = {str(v).lower() for v in (values or [])}
return [p for p in PUBLISH_PLATFORMS if p in wanted]
def eligible(user) -> bool:
"""Autopilot is part of the paid plans (it spends minutes on its own)."""
return bool(user is not None and getattr(user, "entitled", False)
and getattr(user, "plan", None) in PAID_PLANS)
# --------------------------------------------------------------------------- #
# Upload-Post
# --------------------------------------------------------------------------- #
class ChannelError(Exception):
"""The channel could not be listed; ``code`` is shown to the user."""
def __init__(self, code: str):
super().__init__(code)
self.code = code
def _headers():
return {"Authorization": f"Apikey {settings.managed_upload_post_key}"}
async def fetch_channel_videos(profile: str, limit: int = CHANNEL_LIST_LIMIT) -> List[dict]:
"""The latest uploads of the YouTube channel connected to ``profile``."""
async with httpx.AsyncClient(timeout=30) as client:
resp = await client.get(
f"{API_BASE}/uploadposts/media", headers=_headers(),
params={"platform": "youtube", "user": profile, "limit": limit})
try:
data = resp.json()
except ValueError:
data = {}
if resp.status_code == 200 and data.get("success") is not False:
return [m for m in (data.get("media") or []) if isinstance(m, dict)]
message = str(data.get("error") or data.get("message") or "").lower()
if "not have a youtube" in message or "not associated" in message:
raise ChannelError("youtube_not_connected")
if "reauth" in message or "expired" in message or "revoked" in message \
or resp.status_code in (401, 403):
raise ChannelError("youtube_reauth_required")
raise ChannelError("channel_unavailable")
async def fetch_social_accounts(profile: str) -> dict:
"""``{platform: {handle, display_name, reauth_required}}`` for a profile."""
async with httpx.AsyncClient(timeout=20) as client:
resp = await client.get(f"{API_BASE}/uploadposts/users/{profile}",
headers=_headers())
if resp.status_code != 200:
return {}
try:
accounts = ((resp.json() or {}).get("profile") or {}).get("social_accounts") or {}
except ValueError:
return {}
out = {}
for platform, info in accounts.items():
if isinstance(info, dict) and info:
out[platform] = {
"handle": info.get("handle"),
"display_name": info.get("display_name"),
"reauth_required": bool(info.get("reauth_required")),
}
return out
async def is_youtube_short(video_id: str) -> bool:
"""True when YouTube serves this id as a Short.
``/shorts/<id>`` answers 200 for a Short and redirects to ``/watch`` for a
regular video. Any other answer (a consent page, a bot check) reads as
"not a Short" and the normal pipeline's own too-short gate still applies.
"""
try:
async with httpx.AsyncClient(timeout=10, follow_redirects=False) as client:
resp = await client.head(f"https://www.youtube.com/shorts/{video_id}")
return resp.status_code == 200
except Exception:
return False
async def _upload_clip(profile: str, file_path: str, clip: dict, platforms: List[str],
when: str, tz_name: str) -> bool:
"""Schedule one clip on Upload-Post. Mirrors app.post_to_socials' payload."""
loop = asyncio.get_event_loop()
content = await loop.run_in_executor(None, _read_bytes, file_path)
title = clip.get("video_title_for_youtube_short") or clip.get("title") or "New short"
description = (clip.get("video_description_for_instagram")
or clip.get("video_description_for_tiktok") or title)
data = {
"user": profile,
"title": title,
"platform[]": platforms,
"async_upload": "true",
"scheduled_date": when,
"timezone": tz_name or "UTC",
}
if "tiktok" in platforms:
data["tiktok_title"] = description
data["post_mode"] = os.environ.get("TIKTOK_POST_MODE", "MEDIA_UPLOAD").strip()
if "instagram" in platforms:
data["instagram_title"] = description
data["media_type"] = "REELS"
if "youtube" in platforms:
data["youtube_title"] = title
data["youtube_description"] = description
data["privacyStatus"] = "public"
files = {"video": (os.path.basename(file_path), content, "video/mp4")}
async with httpx.AsyncClient(timeout=300) as client:
resp = await client.post(f"{API_BASE}/upload", headers=_headers(),
data=data, files=files)
if resp.status_code not in (200, 201, 202):
print(f"⚠️ Autopilot publish failed ({resp.status_code}): {resp.text[:300]}")
return False
return True
def _read_bytes(path):
with open(path, "rb") as f:
return f.read()
# --------------------------------------------------------------------------- #
# Database helpers
# --------------------------------------------------------------------------- #
async def _load_user(user_id):
from .auth import _load_current_user
async with database.session() as s:
return await _load_current_user(s, user_id)
async def _profile_for(user_id) -> Optional[str]:
async with database.session() as s:
prof = await s.get(UploadPostProfile, user_id)
return prof.profile_username if prof else None
async def _get_settings(user_id) -> Optional[AutopilotSettings]:
async with database.session() as s:
return await s.get(AutopilotSettings, user_id)
async def _set_check_result(user_id, error: Optional[str]):
async with database.session() as s:
async with s.begin():
await s.execute(update(AutopilotSettings)
.where(AutopilotSettings.user_id == user_id)
.values(last_checked_at=func.now(), last_error=error))
async def _count_recent(user_id, trigger: str, since: datetime) -> int:
async with database.session() as s:
return (await s.execute(
select(func.count(AutopilotRun.id)).where(
AutopilotRun.user_id == user_id,
AutopilotRun.trigger == trigger,
AutopilotRun.created_at >= since,
AutopilotRun.status.in_((QUEUED, PROCESSING, COMPLETED, FAILED)),
))).scalar_one()
async def _seen_ids(user_id, video_ids) -> set:
if not video_ids:
return set()
async with database.session() as s:
rows = await s.execute(select(AutopilotRun.video_id).where(
AutopilotRun.user_id == user_id, AutopilotRun.video_id.in_(list(video_ids))))
return {r[0] for r in rows}
async def _claim(user_id, video: dict, trigger: str) -> Optional[uuid.UUID]:
"""INSERT the run row; the unique constraint makes the claim exclusive."""
run_id = uuid.uuid4()
try:
async with database.session() as s:
async with s.begin():
s.add(AutopilotRun(
id=run_id, user_id=user_id, video_id=video["id"],
video_url=video.get("permalink") or f"https://www.youtube.com/watch?v={video['id']}",
video_title=(video.get("caption") or "")[:300] or None,
thumbnail_url=video.get("thumbnail_url"),
published_at=parse_ts(video.get("timestamp")),
trigger=trigger, status=QUEUED,
))
except IntegrityError:
return None
return run_id
async def _update_run(run_id, **values):
async with database.session() as s:
async with s.begin():
await s.execute(update(AutopilotRun).where(AutopilotRun.id == run_id).values(**values))
async def _drop_run(run_id):
async with database.session() as s:
async with s.begin():
await s.execute(delete(AutopilotRun).where(AutopilotRun.id == run_id))
# --------------------------------------------------------------------------- #
# Submitting a job through the normal pipeline
# --------------------------------------------------------------------------- #
async def _submit(user_id, email, run_id, video_url: str, max_minutes: int) -> dict:
"""``POST /api/process`` in-process, as the user, and record the outcome."""
from .auth import issue_jwt
if _app is None:
raise RuntimeError("autopilot not started")
token = issue_jwt(user_id, email)
base = os.environ.get("PUBLIC_API_URL", "").rstrip("/") or "http://localhost"
body = {
"url": video_url,
# Recorded once when the user switched Autopilot on for their own
# channel (rights_ack_at); the pipeline wants it per job.
"acknowledged": True,
"max_minutes": max_minutes,
"auto_hook": "1",
"auto_hook_style": "classic",
}
try:
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=_app),
base_url=base, timeout=600) as client:
resp = await client.post(
"/api/process", json=body,
headers={"Authorization": f"Bearer {token}",
"User-Agent": "OpenShorts-Autopilot/1.0"})
try:
payload = resp.json()
except ValueError:
payload = {}
outcome = outcome_from_process(resp.status_code, payload)
except Exception as e:
print(f"⚠️ Autopilot submit error for {video_url}: {e}")
outcome = {"status": QUEUED, "reason": "server_error", "job_id": None, "retry": True}
if outcome["retry"]:
await _drop_run(run_id) # try this video again on a later tick
else:
await _update_run(run_id, status=outcome["status"], reason=outcome["reason"],
job_id=outcome["job_id"])
print(f"🤖 Autopilot {video_url} -> {outcome['status']}"
f"{' (' + outcome['reason'] + ')' if outcome['reason'] else ''}")
return outcome
async def _start_video(user, video: dict, trigger: str, max_minutes: int) -> dict:
"""Claim a channel video and push it into the pipeline."""
run_id = await _claim(user.id, video, trigger)
if run_id is None:
return {"status": "duplicate", "reason": "already_picked", "job_id": None}
if await is_youtube_short(video["id"]):
await _update_run(run_id, status=SKIPPED, reason="youtube_short")
return {"status": SKIPPED, "reason": "youtube_short", "job_id": None}
url = video.get("permalink") or f"https://www.youtube.com/watch?v={video['id']}"
return await _submit(user.id, user.email, run_id, url, max_minutes)
# --------------------------------------------------------------------------- #
# The poller
# --------------------------------------------------------------------------- #
async def check_user(user_id) -> Optional[str]:
"""One channel check for one user. Returns an error code or None."""
prefs = await _get_settings(user_id)
if prefs is None or not prefs.enabled:
return None
user = await _load_user(user_id)
if not eligible(user):
await _set_check_result(user_id, "plan_required")
return "plan_required"
profile = await _profile_for(user_id)
if not profile:
await _set_check_result(user_id, "youtube_not_connected")
return "youtube_not_connected"
try:
media = await fetch_channel_videos(profile)
except ChannelError as e:
await _set_check_result(user_id, e.code)
return e.code
now = datetime.now(timezone.utc)
seen = await _seen_ids(user_id, [m.get("id") for m in media if m.get("id")])
fresh = pick_new_videos(media, parse_ts(prefs.enabled_at), seen, now)
budget = DAILY_AUTO_LIMIT - await _count_recent(user_id, "auto", now - timedelta(days=1))
for video in fresh:
if budget <= 0:
break # the rest stay unclaimed and are picked up on a later day
result = await _start_video(user, video, "auto", prefs.max_minutes or DEFAULT_MAX_MINUTES)
if result["status"] in (PROCESSING, FAILED):
budget -= 1
if result.get("reason") in ("out_of_minutes", "busy"):
break # nothing else will fit right now
await _set_check_result(user_id, None)
return None
async def _expire_stale_runs():
"""A job that never reported back (container killed past its resume
attempts) must not show 'processing' forever."""
cutoff = datetime.now(timezone.utc) - STALE_RUN_AFTER
async with database.session() as s:
async with s.begin():
await s.execute(update(AutopilotRun).where(
AutopilotRun.status.in_((QUEUED, PROCESSING)),
AutopilotRun.updated_at < cutoff,
).values(status=FAILED, reason="timeout"))
async def poll_once():
await _expire_stale_runs()
due_before = datetime.now(timezone.utc) - CHECK_EVERY
async with database.session() as s:
user_ids = [r[0] for r in await s.execute(
select(AutopilotSettings.user_id).where(
AutopilotSettings.enabled.is_(True),
(AutopilotSettings.last_checked_at.is_(None))
| (AutopilotSettings.last_checked_at < due_before),
).order_by(AutopilotSettings.last_checked_at.asc().nullsfirst()))]
for uid in user_ids:
if _is_active is not None and not _is_active():
return # draining for a deploy: the new instance takes over
try:
await check_user(uid)
except Exception as e:
print(f"⚠️ Autopilot check failed for {uid}: {e}")
await asyncio.sleep(1) # be gentle with Upload-Post and YouTube
async def _loop():
await asyncio.sleep(60) # let the instance finish booting and resuming jobs
while True:
try:
if _is_active is None or _is_active():
await poll_once()
except asyncio.CancelledError:
return
except Exception as e:
print(f"⚠️ Autopilot loop error: {e}")
await asyncio.sleep(TICK_SECONDS)
def start(app, is_active=None):
"""Start the poller. ``is_active`` returns False while the instance drains."""
global _app, _is_active, _task
_app = app
_is_active = is_active
if os.environ.get("AUTOPILOT_DISABLED", "").lower() in ("1", "true", "yes"):
print("🤖 Autopilot poller disabled (AUTOPILOT_DISABLED).")
return
_task = asyncio.create_task(_loop())
# --------------------------------------------------------------------------- #
# Job completion (called from app.run_job_wrapper)
# --------------------------------------------------------------------------- #
async def on_job_finished(job_id: str, job: dict, failure_reason: Optional[str] = None):
"""Settle the run for ``job_id`` if Autopilot started it; no-op otherwise.
Runs on the instance that ran the job. The status flip is a guarded
UPDATE, so a second call for the same job does nothing.
"""
if not job_id or not isinstance(job, dict):
return
ok = job.get("status") == "completed"
clips = ((job.get("result") or {}).get("clips")) or []
async with database.session() as s:
async with s.begin():
row = (await s.execute(
update(AutopilotRun)
.where(and_(AutopilotRun.job_id == job_id,
AutopilotRun.status == PROCESSING))
.values(status=COMPLETED if ok else FAILED,
reason=None if ok else (failure_reason or "processing_failed"),
clips_count=len(clips) if ok else 0)
.returning(AutopilotRun.id, AutopilotRun.user_id, AutopilotRun.video_title)
)).first()
if row is None or not ok or not clips:
return
run_id, user_id, video_title = row
prefs = await _get_settings(user_id)
platforms = clean_platforms(prefs.publish_platforms if prefs else [])
to_post = []
if prefs and prefs.autopublish and platforms:
n = max(0, min(MAX_CLIPS_TO_PUBLISH, prefs.clips_to_publish or DEFAULT_CLIPS_TO_PUBLISH))
to_post = rank_clips(clips, n)
# Our own email replaces the generic "clips ready" one for this job.
job["email_sent"] = True
try:
from .emails import send_autopilot_clips_email
async with database.session() as s:
user = await s.get(User, user_id)
if user and user.email:
await send_autopilot_clips_email(
user.email, video_title, len(clips), len(to_post),
f"{settings.frontend_url}/#app?tab=autopilot")
except Exception as e:
print(f"⚠️ Autopilot email failed for {job_id}: {e}")
if to_post:
profile = await _profile_for(user_id)
output_dir = job.get("output_dir") or ""
items = []
for i in to_post:
rel = clips[i].get("video_url") or ""
path = os.path.join(output_dir, os.path.basename(rel))
if rel and os.path.exists(path):
items.append((clips[i], path))
if profile and items:
task = asyncio.create_task(_publish(run_id, profile, items, platforms, prefs))
_bg_tasks.add(task)
task.add_done_callback(_bg_tasks.discard)
async def _publish(run_id, profile, items, platforms, prefs):
"""Schedule the chosen clips, one a day. Runs in the background so the
job slot is not held while the files upload."""
slots = schedule_slots(datetime.now(timezone.utc), len(items),
prefs.publish_hour if prefs.publish_hour is not None else DEFAULT_PUBLISH_HOUR,
prefs.timezone)
posted = 0
for (clip, path), when in zip(items, slots):
try:
if await _upload_clip(profile, path, clip, platforms, when, prefs.timezone or "UTC"):
posted += 1
except Exception as e:
print(f"⚠️ Autopilot publish error: {e}")
await _update_run(run_id, posted_count=posted,
reason=None if posted == len(items) else "publish_partial")
# --------------------------------------------------------------------------- #
# API
# --------------------------------------------------------------------------- #
class AutopilotUpdate(BaseModel):
enabled: Optional[bool] = None
rights_ack: Optional[bool] = None
autopublish: Optional[bool] = None
publish_platforms: Optional[List[str]] = None
clips_to_publish: Optional[int] = None
max_minutes: Optional[int] = None
publish_hour: Optional[int] = None
timezone: Optional[str] = None
class ManualRun(BaseModel):
video_id: str
def _settings_view(prefs: Optional[AutopilotSettings]) -> dict:
return {
"enabled": bool(prefs and prefs.enabled),
"enabled_at": prefs.enabled_at.isoformat() if prefs and prefs.enabled_at else None,
"rights_ack": bool(prefs and prefs.rights_ack_at),
"autopublish": bool(prefs and prefs.autopublish),
"publish_platforms": clean_platforms(prefs.publish_platforms) if prefs else [],
"clips_to_publish": (prefs.clips_to_publish if prefs else None) or DEFAULT_CLIPS_TO_PUBLISH,
"max_minutes": (prefs.max_minutes if prefs else None) or DEFAULT_MAX_MINUTES,
"publish_hour": prefs.publish_hour if prefs and prefs.publish_hour is not None
else DEFAULT_PUBLISH_HOUR,
"timezone": prefs.timezone if prefs else None,
"last_checked_at": prefs.last_checked_at.isoformat() if prefs and prefs.last_checked_at else None,
"last_error": prefs.last_error if prefs else None,
}
def _run_view(r: AutopilotRun) -> dict:
return {
"id": str(r.id),
"video_id": r.video_id,
"video_url": r.video_url,
"video_title": r.video_title,
"thumbnail_url": r.thumbnail_url,
"published_at": r.published_at.isoformat() if r.published_at else None,
"trigger": r.trigger,
"status": r.status,
"reason": r.reason,
"job_id": r.job_id,
"clips_count": r.clips_count,
"posted_count": r.posted_count,
"created_at": r.created_at.isoformat() if r.created_at else None,
}
async def _recent_runs(user_id, limit=20):
async with database.session() as s:
return list((await s.execute(
select(AutopilotRun).where(AutopilotRun.user_id == user_id)
.order_by(AutopilotRun.created_at.desc()).limit(limit))).scalars())
@router.get("/api/autopilot")
async def get_autopilot(request: Request):
from .auth import get_current_user_required
user = await get_current_user_required(request)
prefs = await _get_settings(user.id)
profile = await _profile_for(user.id)
accounts = {}
if profile:
try:
accounts = await fetch_social_accounts(profile)
except Exception:
accounts = {}
return {
"eligible": eligible(user),
"plan": user.plan,
"settings": _settings_view(prefs),
"accounts": accounts,
"youtube": accounts.get("youtube"),
"limits": {
"daily_auto": DAILY_AUTO_LIMIT,
"max_minutes_choices": list(MAX_MINUTES_CHOICES),
"max_clips_to_publish": MAX_CLIPS_TO_PUBLISH,
"platforms": list(PUBLISH_PLATFORMS),
},
"runs": [_run_view(r) for r in await _recent_runs(user.id)],
}
@router.put("/api/autopilot")
async def put_autopilot(payload: AutopilotUpdate, request: Request):
from .auth import get_current_user_required
user = await get_current_user_required(request)
turning_on = payload.enabled is True
if turning_on and not eligible(user):
raise HTTPException(status_code=403, detail={
"error": "plan_required",
"message": "Autopilot is included in the Starter, Creator and Pro plans."})
async with database.session() as s:
async with s.begin():
prefs = await s.get(AutopilotSettings, user.id)
if prefs is None:
prefs = AutopilotSettings(user_id=user.id, enabled=False, autopublish=False,
clips_to_publish=DEFAULT_CLIPS_TO_PUBLISH,
max_minutes=DEFAULT_MAX_MINUTES,
publish_hour=DEFAULT_PUBLISH_HOUR)
s.add(prefs)
if payload.rights_ack:
prefs.rights_ack_at = prefs.rights_ack_at or datetime.now(timezone.utc)
if turning_on:
if not prefs.rights_ack_at:
raise HTTPException(status_code=400, detail={
"error": "rights_ack_required",
"message": "Confirm you own the content of this channel first."})
if not prefs.enabled:
# New baseline: only videos published from now on.
prefs.enabled_at = datetime.now(timezone.utc)
prefs.last_checked_at = None
prefs.last_error = None
prefs.enabled = True
elif payload.enabled is False:
prefs.enabled = False
if payload.autopublish is not None:
prefs.autopublish = bool(payload.autopublish)
if payload.publish_platforms is not None:
prefs.publish_platforms = clean_platforms(payload.publish_platforms)
if payload.clips_to_publish is not None:
prefs.clips_to_publish = max(1, min(MAX_CLIPS_TO_PUBLISH, int(payload.clips_to_publish)))
if payload.max_minutes is not None:
if int(payload.max_minutes) not in MAX_MINUTES_CHOICES:
raise HTTPException(status_code=400, detail="Unsupported max_minutes value.")
prefs.max_minutes = int(payload.max_minutes)
if payload.publish_hour is not None:
prefs.publish_hour = max(0, min(23, int(payload.publish_hour)))
if payload.timezone is not None:
tz = payload.timezone.strip()[:64]
prefs.timezone = tz if (tz and _zone(tz) is not timezone.utc) or tz == "UTC" else prefs.timezone
return {"settings": _settings_view(await _get_settings(user.id))}
@router.get("/api/autopilot/videos")
async def list_channel_videos(request: Request):
"""The channel's latest uploads, each with what Autopilot did with it."""
from .auth import get_current_user_required
user = await get_current_user_required(request)
profile = await _profile_for(user.id)
if not profile:
return {"videos": [], "error": "youtube_not_connected"}
try:
media = await fetch_channel_videos(profile)
except ChannelError as e:
return {"videos": [], "error": e.code}
ids = [m.get("id") for m in media if m.get("id")]
runs = {}
if ids:
async with database.session() as s:
for r in (await s.execute(select(AutopilotRun).where(
AutopilotRun.user_id == user.id,
AutopilotRun.video_id.in_(ids)))).scalars():
runs[r.video_id] = _run_view(r)
return {"videos": [{
"id": m.get("id"),
"title": m.get("caption"),
"url": m.get("permalink"),
"thumbnail_url": m.get("thumbnail_url"),
"published_at": m.get("timestamp"),
"run": runs.get(m.get("id")),
} for m in media if m.get("id")], "error": None}
@router.post("/api/autopilot/run")
async def run_now(payload: ManualRun, request: Request):
"""Clip one channel video now ("clip my latest video"), outside the
automatic schedule. The video must belong to the user's own channel."""
from .auth import get_current_user_required
user = await get_current_user_required(request)
if not eligible(user):
raise HTTPException(status_code=403, detail={
"error": "plan_required",
"message": "Autopilot is included in the Starter, Creator and Pro plans."})
prefs = await _get_settings(user.id)
if not prefs or not prefs.rights_ack_at:
raise HTTPException(status_code=400, detail={
"error": "rights_ack_required",
"message": "Confirm you own the content of this channel first."})
now = datetime.now(timezone.utc)
if await _count_recent(user.id, "manual", now - timedelta(days=1)) >= MANUAL_DAILY_LIMIT:
raise HTTPException(status_code=429, detail="Daily limit reached. Try again tomorrow.")
profile = await _profile_for(user.id)
if not profile:
raise HTTPException(status_code=400, detail={"error": "youtube_not_connected",
"message": "Connect your YouTube channel first."})
try:
media = await fetch_channel_videos(profile, limit=50)
except ChannelError as e:
raise HTTPException(status_code=400, detail={"error": e.code, "message": "Could not read your channel."})
video = next((m for m in media if m.get("id") == payload.video_id), None)
if video is None:
raise HTTPException(status_code=404, detail="That video is not on your connected channel.")
# A video that failed or was skipped earlier (out of minutes, a hiccup) can
# be retried by hand; one that is running or done cannot be doubled.
async with database.session() as s:
async with s.begin():
await s.execute(delete(AutopilotRun).where(
AutopilotRun.user_id == user.id,
AutopilotRun.video_id == payload.video_id,
AutopilotRun.status.in_((FAILED, SKIPPED))))
result = await _start_video(user, video, "manual", prefs.max_minutes or DEFAULT_MAX_MINUTES)
if result["status"] == "duplicate":
raise HTTPException(status_code=409, detail="This video was already clipped by Autopilot.")
if result.get("retry") or result["status"] == QUEUED:
raise HTTPException(status_code=429, detail=(
"You already have the maximum number of jobs running. Try again in a few minutes."
if result.get("reason") == "busy" else "Could not start the job. Try again shortly."))
return {"status": result["status"], "reason": result.get("reason"), "job_id": result.get("job_id")}

View file

@ -79,6 +79,36 @@ async def send_clips_ready_email(email: str, job_title: str, clip_count: int,
await send_email(email, f"Your clips are ready — {title}", html)
async def send_autopilot_clips_email(email: str, video_title: str, clip_count: int,
scheduled_count: int, dashboard_url: str):
"""Autopilot finished clipping a new channel video on its own.
This is the email that makes Autopilot visible: the user did nothing, and
this is where they find out the work got done anyway.
"""
import html as _html
title = _html.escape((video_title or "your new video").strip())
plural = "s" if clip_count != 1 else ""
if scheduled_count:
posting = (f"<p>The best {scheduled_count} {'is' if scheduled_count == 1 else 'are'} "
f"scheduled to publish, one a day, on the accounts you picked.</p>")
else:
posting = "<p>Review them, tweak anything you like, and post the ones you want.</p>"
html = f"""
<div style="font-family:system-ui,sans-serif;max-width:480px;margin:0 auto">
<h2>Autopilot clipped your new video 🎬</h2>
<p>You published <strong>{title}</strong> and OpenShorts already turned it
into {clip_count} short{plural}.</p>
{posting}
<p><a href="{dashboard_url}" style="display:inline-block;background:#111;color:#fff;
padding:12px 20px;border-radius:8px;text-decoration:none">See my clips</a></p>
<p style="color:#666;font-size:13px">You can pause Autopilot anytime from the
Autopilot page in your dashboard.</p>
</div>
"""
await send_email(email, f"Autopilot: {clip_count} new short{plural} from your video", html)
async def send_clips_expiring_email(email: str, clip_count: int):
"""Free clips enter their last day before deletion — honest loss aversion.

View file

@ -6,6 +6,7 @@ usage_ledger) are designed for atomic, restart-safe metering — see cloud/meter
import uuid
from sqlalchemy import (
Column, String, Integer, Numeric, Boolean, DateTime, ForeignKey, Text, func, Index,
UniqueConstraint,
)
from sqlalchemy.dialects.postgresql import UUID, CITEXT, JSONB
@ -319,3 +320,65 @@ class ProxyUsage(Base):
route = Column(String(32), nullable=True) # winning attempt label, or "none"
paid_bytes = Column(Integer, nullable=False, default=0)
detail = Column(JSONB, nullable=True) # attempts: [{label, ok, bytes, error}]
class AutopilotSettings(Base):
"""Per-user switch for Autopilot: clip every new video on the user's
connected YouTube channel, and optionally publish the best clips.
The channel itself is not stored here. It is whatever YouTube account the
user connected to their Upload-Post profile, read at poll time, so
reconnecting a different channel just works and disconnecting stops it.
``enabled_at`` is the baseline: only videos published after it are clipped
automatically, so switching Autopilot on never burns the month on the back
catalogue. Older videos can still be clipped by hand from the same page.
"""
__tablename__ = "autopilot_settings"
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
primary_key=True)
enabled = Column(Boolean, nullable=False, default=False)
enabled_at = Column(DateTime(timezone=True), nullable=True)
# The user confirmed they own (or have rights to) the channel's content.
# /api/process requires that attestation per job; Autopilot records it once.
rights_ack_at = Column(DateTime(timezone=True), nullable=True)
autopublish = Column(Boolean, nullable=False, default=False)
publish_platforms = Column(JSONB, nullable=True) # ["tiktok", "instagram", "youtube"]
clips_to_publish = Column(Integer, nullable=False, default=3)
max_minutes = Column(Integer, nullable=False, default=30)
# Autopublish slot: one clip a day at this local hour, in this IANA zone.
publish_hour = Column(Integer, nullable=False, default=17)
timezone = Column(Text, nullable=True)
last_checked_at = Column(DateTime(timezone=True), nullable=True)
last_error = Column(Text, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
class AutopilotRun(Base):
"""One channel video Autopilot picked up, and what happened to it.
The (user_id, video_id) unique constraint is the dedupe: during a deploy two
API containers run the poller at once, and only the one whose INSERT wins
submits the job.
"""
__tablename__ = "autopilot_runs"
id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"),
nullable=False, index=True)
video_id = Column(Text, nullable=False)
video_url = Column(Text, nullable=True)
video_title = Column(Text, nullable=True)
thumbnail_url = Column(Text, nullable=True)
published_at = Column(DateTime(timezone=True), nullable=True)
trigger = Column(String(12), nullable=False, default="auto") # auto | manual
status = Column(String(16), nullable=False, default="queued") # queued | processing | completed | failed | skipped
reason = Column(Text, nullable=True)
job_id = Column(Text, nullable=True, index=True)
clips_count = Column(Integer, nullable=True)
posted_count = Column(Integer, nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
__table_args__ = (
UniqueConstraint("user_id", "video_id", name="uq_autopilot_user_video"),
)

View file

@ -70,14 +70,23 @@ async def ensure_profile(user) -> str:
return username
async def get_connect_url(username: str) -> str:
# Where the connect page sends the user back to. A closed list: the value
# comes from the client and ends up in a redirect.
RETURN_TARGETS = {
"account": "/#/account?connected=1",
"autopilot": "/#app?tab=autopilot&connected=1",
}
async def get_connect_url(username: str, return_to: str = "account") -> str:
"""Generate a branded, single-use connection URL (~1h) for the user's socials."""
back = RETURN_TARGETS.get(return_to, RETURN_TARGETS["account"])
payload = {
"username": username,
"logoImage": settings.openshorts_logo_url,
"connectTitle": "Connect your social accounts",
"connectDescription": "Link TikTok, Instagram and YouTube to post your shorts directly from OpenShorts.",
"redirectUrl": f"{settings.frontend_url}/#/account?connected=1",
"redirectUrl": f"{settings.frontend_url}{back}",
"redirectButtonText": "Back to OpenShorts",
"platforms": CONNECT_PLATFORMS,
"showCalendar": True, # keep the scheduling calendar available in the page
@ -99,5 +108,5 @@ async def social_connect(request: Request):
from .auth import get_current_user_required
user = await get_current_user_required(request)
username = await ensure_profile(user)
access_url = await get_connect_url(username)
access_url = await get_connect_url(username, request.query_params.get("return_to") or "account")
return {"access_url": access_url}

View file

@ -1,5 +1,5 @@
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 { 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, Rocket } from 'lucide-react';
import KeyInput from './components/KeyInput';
import MediaInput from './components/MediaInput';
import McpConnectCard from './components/McpConnectCard';
@ -22,6 +22,7 @@ import LoginModal from './components/LoginModal';
import TrialGate from './components/TrialGate';
import AdvancedBanner from './components/AdvancedBanner';
import HistoryTab from './components/HistoryTab';
import AutopilotTab from './components/AutopilotTab';
import ProfileMenu from './components/ProfileMenu';
import Modal from './components/ui/Modal';
import { useAuth } from './contexts/AuthContext';
@ -822,6 +823,27 @@ function App() {
if (tutorialLock && activeTab !== 'dashboard') setActiveTab('dashboard');
}, [tutorialLock, activeTab]);
// Deep links into a tab: #app?tab=autopilot (Autopilot emails, the social
// connect page's return URL). Read once per hash change, then the query is
// dropped so a reload does not keep forcing the tab.
const [autopilotConnected, setAutopilotConnected] = useState(false);
useEffect(() => {
const DEEP_LINK_TABS = ['autopilot', 'history', 'settings', 'thumbnails', 'dashboard'];
const apply = () => {
const hash = window.location.hash || '';
if (!hash.startsWith('#app?')) return;
const params = new URLSearchParams(hash.slice(5));
const tab = params.get('tab');
if (!tab || !DEEP_LINK_TABS.includes(tab)) return; // e.g. #app?tutorial=1
setActiveTab(tab);
if (tab === 'autopilot' && params.get('connected') === '1') setAutopilotConnected(true);
try { window.history.replaceState(null, '', '#app'); } catch (_) { /* ignore */ }
};
apply();
window.addEventListener('hashchange', apply);
return () => window.removeEventListener('hashchange', apply);
}, []);
useEffect(() => {
if (tutorialPhase === 'coach' && status === 'complete' && (results?.clips?.length > 0)) {
setTutorialPhase('celebrate');
@ -1067,12 +1089,14 @@ function App() {
// 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' },
// Cloud only: it runs on the managed pipeline and the Upload-Post connection.
...(billingEnabled ? [{ id: 'autopilot', ord: '02', icon: Rocket, label: 'Autopilot', short: 'autopilot', isNew: true }] : []),
{ id: 'saasshorts', ord: '03', icon: Sparkles, label: 'AI Shorts', short: 'ai shorts', byok: true, primary: true },
{ id: 'ai-agent', ord: '04', icon: Bot, label: 'AI Agent', short: 'agent', byok: true },
{ id: 'ugc-gallery', ord: '05', icon: LayoutGrid, label: 'UGC Gallery', short: 'gallery', primary: true },
{ id: 'thumbnails', ord: '06', icon: Image, label: 'YouTube Studio', short: 'studio', primary: true },
...(billingEnabled && isSignedIn ? [{ id: 'history', ord: '07', icon: History, label: 'History', short: 'history' }] : []),
{ id: 'settings', ord: '08', icon: Settings, label: 'Settings', short: 'settings' },
];
const activeNav = navItems.find((n) => n.id === activeTab);
@ -1162,7 +1186,8 @@ function App() {
<span className="text-sm lowercase hidden lg:block flex-1 text-left truncate">{item.label}</span>
{tabLocked(item.id)
? <Lock size={12} className="shrink-0 hidden lg:block" />
: item.byok ? <span className="readout hidden lg:block">BYOK</span> : null}
: item.byok ? <span className="readout hidden lg:block">BYOK</span>
: item.isNew ? <span className="badge-brass hidden lg:block">new</span> : null}
<span className="readout hidden lg:block">{item.ord}</span>
</button>
);
@ -1225,7 +1250,8 @@ function App() {
<span className="text-[0.95rem] lowercase flex-1 text-left truncate">{item.label}</span>
{tabLocked(item.id)
? <Lock size={12} className="shrink-0" />
: item.byok ? <span className="readout shrink-0">BYOK</span> : null}
: item.byok ? <span className="readout shrink-0">BYOK</span>
: item.isNew ? <span className="badge-brass shrink-0">new</span> : null}
</button>
);
})}
@ -1427,7 +1453,7 @@ function App() {
<div className="h-full overflow-y-auto p-4 sm:p-8 max-w-2xl mx-auto animate-fade">
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-8">
<div>
<p className="eyebrow mb-1.5">07 · SETTINGS</p>
<p className="eyebrow mb-1.5">08 · SETTINGS</p>
<h1 className="font-display lowercase text-2xl text-ink">Settings</h1>
</div>
<div className="flex items-center gap-2 text-xs text-muted mt-1">
@ -1786,6 +1812,31 @@ function App() {
</div>
)}
{/* View: Autopilot */}
{activeTab === 'autopilot' && (
<div className="h-full overflow-y-auto custom-scrollbar animate-fade">
<div className="max-w-6xl mx-auto p-4 sm:p-6 md:p-8">
{isSignedIn ? (
<AutopilotTab
onOpenProject={restoreProject}
onUpgrade={() => setShowPlanChoice(true)}
justConnected={autopilotConnected}
/>
) : (
<div className="max-w-2xl mx-auto card p-8 text-center">
<Rocket size={28} className="mx-auto mb-4 text-brass" />
<h1 className="font-display lowercase text-2xl text-ink mb-2">your channel, clipped on its own</h1>
<p className="text-muted text-sm mb-6">
Connect your YouTube channel and every new video turns into shorts automatically.
Sign in to set it up.
</p>
<button onClick={() => setShowLogin(true)} className="btn-primary">sign in</button>
</div>
)}
</div>
</div>
)}
{/* View: History */}
{activeTab === 'history' && (
<div className="h-full overflow-y-auto custom-scrollbar animate-fade">

View file

@ -0,0 +1,498 @@
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',
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 (
<span className="relative inline-flex items-center shrink-0">
<input
type="checkbox"
role="switch"
aria-label={label}
checked={checked}
disabled={disabled}
onChange={(e) => onChange(e.target.checked)}
className="sr-only peer"
/>
<span className="w-11 h-6 rounded-full bg-paper3 border border-rule2 peer-checked:bg-brass peer-disabled:opacity-40 transition-colors after:content-[''] after:absolute after:left-1 after:top-1 after:w-4 after:h-4 after:rounded-full after:bg-ink after:transition-transform peer-checked:after:translate-x-5" />
</span>
);
}
function StatusBadge({ run }) {
if (!run) return <span className="readout">not clipped</span>;
const { status } = run;
if (status === 'completed') {
return (
<span className="badge-ok inline-flex items-center gap-1">
<CheckCircle2 size={11} /> {run.clips_count || 0} clips
{run.posted_count ? ` · ${run.posted_count} scheduled` : ''}
</span>
);
}
if (status === 'processing' || status === 'queued') {
return <span className="badge-brass inline-flex items-center gap-1"><Loader2 size={11} className="animate-spin" /> clipping</span>;
}
if (status === 'skipped') return <span className="badge-warn">{REASON_TEXT[run.reason] || 'skipped'}</span>;
return <span className="badge-danger">{REASON_TEXT[run.reason] || 'failed'}</span>;
}
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 [rightsAck, setRightsAck] = useState(false);
const [running, setRunning] = useState(null); // video id being submitted
const [notice, setNotice] = 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) => {
if (on && !data?.settings?.rights_ack && !rightsAck) {
setNotice('Confirm you own the content of this channel to switch Autopilot on.');
return;
}
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.');
}
}, [data, rightsAck, 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) => {
if (!data?.settings?.rights_ack && !rightsAck) {
setNotice('Confirm you own the content of this channel first.');
return;
}
setRunning(video.id);
setNotice('');
try {
if (!data?.settings?.rights_ack) await save({ rights_ack: true });
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') setNotice(`Clipping “${video.title || 'your video'}”. We will email you when the clips are ready.`);
else setNotice(`Not clipped: ${REASON_TEXT[r.reason] || r.reason || r.status}.`);
} catch (e) {
if (e?.name === 'QuotaError') setNotice('You are out of minutes for this period.');
else setNotice(errText(e, 'Could not start the job.'));
} finally {
setRunning(null);
load();
}
}, [data, rightsAck, save, 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 <div className="flex justify-center py-20"><Loader2 className="animate-spin text-brass" /></div>;
}
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 (
<div className="max-w-4xl mx-auto animate-fade">
<p className="eyebrow mb-1.5">02 · AUTOPILOT</p>
<h1 className="font-display lowercase text-3xl text-ink mb-2">your channel, clipped on its own</h1>
<p className="text-muted text-sm mb-8 max-w-2xl">
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.
</p>
{loadError && <p className="text-danger text-sm mb-4">{loadError}</p>}
{notice && (
<div className="mb-6 rounded-card border border-brass/40 bg-brass/5 px-4 py-3 text-sm text-ink2">{notice}</div>
)}
{/* Plan gate: Autopilot spends minutes on its own, so it is a paid feature. */}
{!eligible && (
<div className="card p-6 mb-6">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2">
<Lock size={16} className="text-brass" /> included in paid plans
</h3>
<p className="text-muted text-sm mb-4">
Autopilot runs on your plan&apos;s minutes, so it comes with Starter, Creator and Pro.
Every new upload turns into shorts without you opening OpenShorts.
</p>
<button onClick={() => { track('AutopilotUpgradeClick'); onUpgrade?.(); }} className="btn-primary">
<Rocket size={16} /> choose a plan
</button>
</div>
)}
{/* 1 · channel */}
<div className="card p-6 mb-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div className="flex items-center gap-3 min-w-0">
<div className="w-10 h-10 rounded-full bg-paper3 border border-rule flex items-center justify-center shrink-0">
<Youtube size={18} className={yt ? 'text-brass' : 'text-muted'} />
</div>
<div className="min-w-0">
<p className="eyebrow">01 · CHANNEL</p>
{yt ? (
<p className="text-ink truncate">{yt.display_name || yt.handle} <span className="readout ml-1">{yt.handle}</span></p>
) : (
<p className="text-muted text-sm">no YouTube channel connected yet</p>
)}
</div>
</div>
{(!yt || yt.reauth_required) && (
<button onClick={connect} className="btn-primary" disabled={!eligible}>
<Youtube size={16} /> {yt ? 'reconnect youtube' : 'connect youtube'}
</button>
)}
{yt && !yt.reauth_required && (
<button onClick={connect} className="btn-quiet text-xs">manage accounts</button>
)}
</div>
{yt?.reauth_required && (
<p className="text-warn text-sm mt-3 flex items-center gap-2"><AlertTriangle size={14} /> YouTube needs you to reconnect this channel.</p>
)}
</div>
{/* 2 · switch */}
<div className="card p-6 mb-6">
<div className="flex items-start justify-between gap-4">
<div>
<p className="eyebrow mb-1">02 · AUTOPILOT</p>
<p className="text-ink">{s.enabled ? 'on: new videos are clipped automatically' : 'off'}</p>
<p className="text-muted text-sm mt-1">
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.
</p>
{s.enabled && s.last_checked_at && (
<p className="readout mt-2 flex items-center gap-1"><Clock size={11} /> last check {fmtDate(s.last_checked_at)} · every hour</p>
)}
</div>
<Switch
label="autopilot"
checked={!!s.enabled}
disabled={saving || !eligible || !yt}
onChange={toggleEnabled}
/>
</div>
{!s.rights_ack && (
<label className="flex items-start gap-3 mt-5 text-sm text-ink2 cursor-pointer">
<input
type="checkbox"
checked={rightsAck}
onChange={(e) => setRightsAck(e.target.checked)}
className="mt-0.5 accent-[var(--color-accent)]"
/>
<span>I own the content published on this channel, or have the rights to process it.</span>
</label>
)}
{errorText && (
<p className="text-warn text-sm mt-4 flex items-center gap-2"><AlertTriangle size={14} /> {errorText}</p>
)}
<div className="grid sm:grid-cols-2 gap-4 mt-6">
<label className="block">
<span className="eyebrow block mb-2">minutes per video</span>
<select
className="input-field"
value={s.max_minutes || 30}
disabled={saving || !eligible}
onChange={(e) => save({ max_minutes: Number(e.target.value) })}
>
{limits.max_minutes_choices.map((m) => <option key={m} value={m}>first {m} min</option>)}
</select>
</label>
</div>
</div>
{/* 3 · autopublish */}
<div className="card p-6 mb-6">
<div className="flex items-start justify-between gap-4">
<div>
<p className="eyebrow mb-1">03 · AUTOPUBLISH</p>
<p className="text-ink">{s.autopublish ? 'the best clips are scheduled for you' : 'off: you review and post the clips yourself'}</p>
<p className="text-muted text-sm mt-1">
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()}).
</p>
</div>
<Switch
label="autopublish"
checked={!!s.autopublish}
disabled={saving || !eligible}
onChange={(on) => { track('AutopilotAutopublish', { props: { on: String(on) } }); save({ autopublish: on }); }}
/>
</div>
{s.autopublish && (
<>
<div className="mt-5">
<span className="eyebrow block mb-2">publish to</span>
<div className="flex flex-wrap gap-2">
{limits.platforms.map((p) => {
const connected = !!accounts[p];
const on = (s.publish_platforms || []).includes(p);
return connected ? (
<button
key={p}
onClick={() => togglePlatform(p)}
disabled={saving}
aria-pressed={on}
className={`px-4 py-2 rounded-full text-sm lowercase border transition-colors ${on ? 'border-brass bg-brass/10 text-ink' : 'border-rule2 text-muted hover:text-ink2'}`}
>
{on && <CheckCircle2 size={13} className="inline mr-1.5 -mt-0.5 text-brass" />}{PLATFORM_LABELS[p]}
</button>
) : (
<button key={p} onClick={connect} className="px-4 py-2 rounded-full text-sm lowercase border border-dashed border-rule2 text-muted hover:text-ink2">
+ connect {PLATFORM_LABELS[p]}
</button>
);
})}
</div>
{(s.publish_platforms || []).length === 0 && (
<p className="text-warn text-sm mt-3">Pick at least one account, or nothing gets published.</p>
)}
{(s.publish_platforms || []).includes('tiktok') && (
<p className="text-muted text-xs mt-3">TikTok clips arrive as drafts in your TikTok inbox: open the app to post them.</p>
)}
</div>
<div className="grid sm:grid-cols-2 gap-4 mt-5">
<label className="block">
<span className="eyebrow block mb-2">clips per video</span>
<select
className="input-field"
value={s.clips_to_publish || 3}
disabled={saving}
onChange={(e) => save({ clips_to_publish: Number(e.target.value) })}
>
{Array.from({ length: limits.max_clips_to_publish || 5 }, (_, i) => i + 1).map((n) => (
<option key={n} value={n}>{n} {n === 1 ? 'clip' : 'clips'} (one a day)</option>
))}
</select>
</label>
<label className="block">
<span className="eyebrow block mb-2">time of day</span>
<select
className="input-field"
value={s.publish_hour ?? 17}
disabled={saving}
onChange={(e) => save({ publish_hour: Number(e.target.value) })}
>
{Array.from({ length: 24 }, (_, h) => h).map((h) => (
<option key={h} value={h}>{String(h).padStart(2, '0')}:00</option>
))}
</select>
</label>
</div>
</>
)}
</div>
{/* 4 · channel videos */}
{yt && (
<div className="card p-6 mb-6">
<div className="flex items-center justify-between gap-3 mb-4">
<div>
<p className="eyebrow mb-1">04 · YOUR LATEST VIDEOS</p>
<p className="text-muted text-sm">Clip any of them now, or let Autopilot handle the next one.</p>
</div>
<button onClick={load} className="btn-quiet text-xs" aria-label="refresh"><RefreshCw size={13} /> refresh</button>
</div>
{videosError && <p className="text-warn text-sm mb-3">{ERROR_TEXT[videosError] || 'Could not read your channel.'}</p>}
{videos === null && <div className="flex justify-center py-6"><Loader2 className="animate-spin text-brass" size={18} /></div>}
{videos && videos.length === 0 && !videosError && (
<p className="text-muted text-sm">No videos on this channel yet.</p>
)}
<div className="divide-y divide-rule">
{(videos || []).map((v) => {
const run = v.run;
const canRun = eligible && (!run || run.status === 'failed'
|| (run.status === 'skipped' && run.reason !== 'youtube_short'));
return (
<div key={v.id} className="flex items-center gap-3 py-3">
{v.thumbnail_url ? (
<img src={v.thumbnail_url} alt="" className="w-20 sm:w-24 h-[45px] sm:h-[54px] object-cover rounded-input border border-rule shrink-0" loading="lazy" />
) : (
<div className="w-20 sm:w-24 h-[45px] sm:h-[54px] rounded-input bg-paper3 shrink-0" />
)}
<div className="min-w-0 flex-1">
<a href={v.url} target="_blank" rel="noopener noreferrer" className="text-sm text-ink2 hover:text-ink line-clamp-2">
{v.title || v.id} <ExternalLink size={11} className="inline -mt-0.5 text-muted" />
</a>
<div className="flex flex-wrap items-center gap-2 mt-1">
<span className="readout">{fmtDate(v.published_at)}</span>
<StatusBadge run={run} />
</div>
</div>
{run?.status === 'completed' && run.job_id ? (
<button onClick={() => openProject(run.job_id)} className="btn-quiet text-xs shrink-0" disabled={opening === run.job_id}>
{opening === run.job_id ? <Loader2 size={13} className="animate-spin" /> : <FolderOpen size={13} />} open
</button>
) : canRun ? (
<button onClick={() => runNow(v)} className="btn-ghost px-4 py-2 text-xs shrink-0" disabled={!!running}>
{running === v.id ? <Loader2 size={13} className="animate-spin" /> : <Scissors size={13} />} clip it
</button>
) : null}
</div>
);
})}
</div>
</div>
)}
{/* 5 · activity */}
{runs.length > 0 && (
<div className="card p-6 mb-10">
<p className="eyebrow mb-4">05 · ACTIVITY</p>
<div className="space-y-3">
{runs.map((r) => (
<div key={r.id} className="flex items-center gap-3 text-sm">
{r.status === 'completed' ? <CheckCircle2 size={15} className="text-ok shrink-0" />
: (r.status === 'processing' || r.status === 'queued') ? <Loader2 size={15} className="animate-spin text-brass shrink-0" />
: r.status === 'skipped' ? <Play size={15} className="text-muted shrink-0" />
: <AlertTriangle size={15} className="text-danger shrink-0" />}
<span className="text-ink2 truncate flex-1">{r.video_title || r.video_id}</span>
{r.posted_count ? <span className="readout hidden sm:inline-flex items-center gap-1"><Send size={11} /> {r.posted_count} scheduled</span> : null}
<span className="readout shrink-0">{r.trigger === 'manual' ? 'manual' : 'auto'} · {fmtDate(r.created_at)}</span>
</div>
))}
</div>
</div>
)}
</div>
);
}

View file

@ -56,7 +56,7 @@ export default function HistoryTab({ onReopenProject }) {
return (
<div className="h-full overflow-y-auto p-8 max-w-5xl mx-auto animate-fade">
<p className="eyebrow mb-1.5">06 · HISTORY</p>
<p className="eyebrow mb-1.5">07 · HISTORY</p>
<h1 className="font-display lowercase text-2xl text-ink mb-2">Your library</h1>
<p className="text-muted text-sm mb-8 lowercase">
All the shorts you've generated, saved while your plan is active. Kept for 7 days after your plan ends. Reopen a project to keep editing its clips.

View file

@ -400,7 +400,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
{/* Header */}
<div className="flex items-end justify-between mb-2">
<div>
<p className="eyebrow mb-2">02 · AI SHORTS</p>
<p className="eyebrow mb-2">03 · AI SHORTS</p>
<h1 className="font-display lowercase text-2xl text-ink">AI Shorts</h1>
</div>
{step > 0 && (

View file

@ -471,7 +471,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
{/* Header */}
<div className="flex items-end justify-between mb-2">
<div>
<p className="eyebrow mb-2">05 · YOUTUBE STUDIO</p>
<p className="eyebrow mb-2">06 · YOUTUBE STUDIO</p>
<h1 className="font-display lowercase text-2xl text-ink flex items-center gap-3">
<span className="w-10 h-10 rounded-card bg-paper3 flex items-center justify-center">
<Image size={18} className="text-brass" />

View file

@ -47,7 +47,7 @@ export default function UGCGallery() {
return (
<div className="space-y-6">
<div>
<p className="eyebrow mb-1">04 · UGC GALLERY</p>
<p className="eyebrow mb-1">05 · UGC GALLERY</p>
<h2 className="font-display lowercase text-2xl md:text-3xl text-ink">ugc gallery</h2>
<p className="readout mt-2">
{loadingVideos ? '…' : videos.length} videos

144
tests/test_autopilot.py Normal file
View file

@ -0,0 +1,144 @@
"""Autopilot (cloud/autopilot.py): the decisions that run without a person.
Everything here fires on its own schedule and spends the user's minutes, so
the pure rules are pinned down: which channel videos get picked, which clips
get published and when, and how each /api/process answer is recorded.
"""
from datetime import datetime, timedelta, timezone
from cloud import autopilot as ap
NOW = datetime(2026, 9, 22, 18, 0, tzinfo=timezone.utc)
def _video(vid, hours_ago):
ts = (NOW - timedelta(hours=hours_ago)).strftime("%Y-%m-%dT%H:%M:%SZ")
return {"id": vid, "timestamp": ts, "permalink": f"https://www.youtube.com/watch?v={vid}"}
class TestPickNewVideos:
def test_only_videos_after_the_baseline(self):
baseline = NOW - timedelta(hours=5)
media = [_video("old", 10), _video("new", 2)]
assert [v["id"] for v in ap.pick_new_videos(media, baseline, set(), NOW)] == ["new"]
def test_switching_on_never_picks_the_back_catalogue(self):
media = [_video("a", 1), _video("b", 30)]
assert ap.pick_new_videos(media, NOW, set(), NOW) == []
def test_no_baseline_means_nothing(self):
assert ap.pick_new_videos([_video("a", 1)], None, set(), NOW) == []
def test_already_seen_videos_are_skipped(self):
baseline = NOW - timedelta(days=1)
media = [_video("a", 1), _video("b", 2)]
assert [v["id"] for v in ap.pick_new_videos(media, baseline, {"a"}, NOW)] == ["b"]
def test_too_old_even_if_after_baseline(self):
baseline = NOW - timedelta(days=30)
media = [_video("stale", 24 * 5), _video("fresh", 3)]
assert [v["id"] for v in ap.pick_new_videos(media, baseline, set(), NOW)] == ["fresh"]
def test_oldest_first(self):
baseline = NOW - timedelta(days=2)
media = [_video("newest", 1), _video("older", 20), _video("middle", 8)]
assert [v["id"] for v in ap.pick_new_videos(media, baseline, set(), NOW)] == \
["older", "middle", "newest"]
def test_items_without_id_or_timestamp_are_ignored(self):
baseline = NOW - timedelta(days=1)
media = [{"id": "x"}, {"timestamp": "2026-09-22T17:00:00Z"}, {"id": "y", "timestamp": "garbage"}]
assert ap.pick_new_videos(media, baseline, set(), NOW) == []
class TestRankClips:
def test_best_scores_first(self):
clips = [{"predicted_score": 40}, {"predicted_score": 90}, {"predicted_score": 70}]
assert ap.rank_clips(clips, 2) == [1, 2]
def test_unscored_clips_keep_order_after_scored(self):
clips = [{}, {"predicted_score": "55"}, {}, {"predicted_score": None}]
assert ap.rank_clips(clips, 4) == [1, 0, 2, 3]
def test_n_larger_than_clips(self):
assert ap.rank_clips([{"predicted_score": 1}], 3) == [0]
def test_zero(self):
assert ap.rank_clips([{"predicted_score": 1}], 0) == []
class TestScheduleSlots:
def test_one_a_day_at_the_hour(self):
now = datetime(2026, 9, 22, 8, 0, tzinfo=timezone.utc)
assert ap.schedule_slots(now, 3, hour=17) == [
"2026-09-22T17:00:00", "2026-09-23T17:00:00", "2026-09-24T17:00:00"]
def test_starts_tomorrow_when_the_slot_is_under_an_hour_away(self):
now = datetime(2026, 9, 22, 16, 30, tzinfo=timezone.utc)
assert ap.schedule_slots(now, 1, hour=17) == ["2026-09-23T17:00:00"]
def test_local_timezone(self):
# 08:00 UTC is 10:00 in Madrid (CEST): 17:00 local is still today.
now = datetime(2026, 9, 22, 8, 0, tzinfo=timezone.utc)
assert ap.schedule_slots(now, 1, hour=17, tz_name="Europe/Madrid") == ["2026-09-22T17:00:00"]
def test_unknown_timezone_falls_back_to_utc(self):
now = datetime(2026, 9, 22, 8, 0, tzinfo=timezone.utc)
assert ap.schedule_slots(now, 1, hour=17, tz_name="Not/AZone") == ["2026-09-22T17:00:00"]
class TestOutcomeFromProcess:
def test_job_started(self):
o = ap.outcome_from_process(200, {"job_id": "j1", "status": "queued"})
assert o == {"status": "processing", "reason": None, "job_id": "j1", "retry": False}
def test_quality_gate_is_a_skip(self):
assert ap.outcome_from_process(200, {"needs_confirmation": True})["reason"] == "low_quality"
def test_out_of_minutes_is_a_skip(self):
o = ap.outcome_from_process(402, {"detail": {"error": "quota_exceeded"}})
assert (o["status"], o["reason"], o["retry"]) == ("skipped", "out_of_minutes", False)
def test_job_limit_is_retried_later(self):
o = ap.outcome_from_process(429, {"detail": "max jobs"})
assert o["retry"] is True and o["reason"] == "busy"
def test_short_source(self):
detail = ("This video is only 40s long — clip generation needs at least 45s "
"of material to cut from. It already is short-form content.")
assert ap.outcome_from_process(400, {"detail": detail})["reason"] == "too_short"
def test_other_400_is_unavailable(self):
o = ap.outcome_from_process(400, {"detail": "Could not determine the video duration."})
assert (o["status"], o["reason"]) == ("skipped", "unavailable")
def test_server_error_is_retried(self):
assert ap.outcome_from_process(502, "not json")["retry"] is True
class TestSmallRules:
def test_platforms_are_filtered_and_ordered(self):
assert ap.clean_platforms(["YouTube", "facebook", "tiktok"]) == ["tiktok", "youtube"]
assert ap.clean_platforms(None) == []
def test_only_paid_plans_are_eligible(self):
class U:
def __init__(self, plan, entitled=True):
self.plan, self.entitled = plan, entitled
assert ap.eligible(U("starter"))
assert ap.eligible(U("pro"))
assert not ap.eligible(U("free"))
assert not ap.eligible(U(None))
assert not ap.eligible(U("creator", entitled=False))
assert not ap.eligible(None)
def test_parse_ts(self):
assert ap.parse_ts("2026-09-22T10:01:35Z") == datetime(2026, 9, 22, 10, 1, 35, tzinfo=timezone.utc)
assert ap.parse_ts("nope") is None
assert ap.parse_ts(None) is None
def test_connect_return_targets_are_a_closed_list():
from cloud import social_profiles
assert set(social_profiles.RETURN_TARGETS) == {"account", "autopilot"}
assert all(v.startswith("/#") for v in social_profiles.RETURN_TARGETS.values())