From fe0f32e86ba16b6e04b8e8d7548f596fbd99db97 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 21 Jul 2026 00:30:56 +0200 Subject: [PATCH] =?UTF-8?q?feat(onboarding):=20popup=20de=20selecci=C3=B3n?= =?UTF-8?q?=20de=20plan=20+=20quitar=20tope=20diario=20free=20y=20'free=20?= =?UTF-8?q?trial'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Quitado el tope de 3 jobs/día por cuenta y 5 por IP en el plan free: la cuota de 20 min/mes es el único límite (el ledger ya capa el coste real y el tope diario confundía). Verificado que un free NO puede pasar de 20 min ni con reservas concurrentes: 10 reservas simultáneas de 5min -> solo 4 concedidas, ledger clavado en 20, el lock por usuario serializa. - Registro por email ya no tira a la página de pricing (rayaba): aterriza en la app y sale un popup PlanChoiceModal para elegir plan — free (via Google, por el gate anti-abuso) o los de pago inline con su precio. - Eliminado 'start free trial' / '3 days free' de la cabecera y de settings; ahora dicen 'choose a plan'. - vite.config: target del proxy configurable con VITE_PROXY_TARGET para dev en el host contra localhost:8000 sin CORS. Probado en dev local: el popup aparece al aterrizar sin plan y desde el botón 'choose a plan', con free + starter/creator/pro. --- app.py | 50 ++------- cloud/config.py | 7 +- dashboard/src/App.jsx | 30 ++++-- dashboard/src/components/PlanChoiceModal.jsx | 103 +++++++++++++++++++ dashboard/src/contexts/AuthContext.jsx | 11 +- dashboard/vite.config.js | 36 +++---- 6 files changed, 153 insertions(+), 84 deletions(-) create mode 100644 dashboard/src/components/PlanChoiceModal.jsx diff --git a/app.py b/app.py index 332ddc6..cde825f 100644 --- a/app.py +++ b/app.py @@ -130,18 +130,9 @@ def gemini_missing_error(): return HTTPException(status_code=400, detail="Missing X-Gemini-Key header") -def _client_ip(request) -> str: - """Client IP, honoring the proxy's X-Forwarded-For (Traefik in prod).""" - fwd = request.headers.get("x-forwarded-for") - if fwd: - return fwd.split(",")[0].strip() - return request.client.host if request.client else "unknown" - - -# In-memory abuse counters. Reset on restart by design — the hard monthly -# quota lives in the metering ledger; these only flatten bursts and casual -# multi-accounting, so losing them on a deploy is fine. -_daily_counters = {"date": None, "users": {}, "ips": {}} +# Probe rate limiter. In-memory, resets on restart by design — the hard monthly +# quota lives in the metering ledger; this only stops someone hammering the +# proxy with metadata probes. _probe_times: dict = {} # user_id -> [monotonic timestamps] PROBES_PER_HOUR = 15 @@ -164,13 +155,6 @@ def _maybe_send_quota_email(user): asyncio.create_task(send_out_of_minutes_email(user.email, upgrade_url)) -def _daily_bucket(kind: str) -> dict: - today = datetime.now(timezone.utc).strftime("%Y-%m-%d") - if _daily_counters["date"] != today: - _daily_counters.update(date=today, users={}, ips={}) - return _daily_counters[kind] - - def _check_probe_rate(user_id): now = time.monotonic() times = _probe_times.setdefault(str(user_id), []) @@ -212,23 +196,9 @@ async def reserve_process_minutes(request, url, input_path, job_id): raise HTTPException(status_code=429, detail="You already have the maximum number of jobs running. Please wait.") - # Free-plan daily burst caps, checked BEFORE the probe so URL spam never - # reaches the proxy. Per-account and per-IP (multi-account abuse). - if user.plan == "free": - user_counts = _daily_bucket("users") - if user_counts.get(str(user.id), 0) >= _cloud_config.FREE_DAILY_JOBS: - raise HTTPException(status_code=429, detail={ - "error": "daily_limit", - "message": "Free plan daily limit reached. Come back tomorrow or upgrade for more.", - }) - ip_counts = _daily_bucket("ips") - if ip_counts.get(_client_ip(request), 0) >= _cloud_config.FREE_DAILY_JOBS_PER_IP: - raise HTTPException(status_code=429, detail={ - "error": "daily_limit", - "message": "Free plan daily limit reached for this network. Come back tomorrow or upgrade.", - }) - - # Probe rate limit: probing costs a (cheap) proxied metadata call. + # Probe rate limit: probing costs a (cheap) proxied metadata call. The + # 20-minute monthly quota is the real bound on free usage; there is no daily + # job cap. _check_probe_rate(user.id) # Probe input duration (blocking → run in a thread). @@ -253,14 +223,6 @@ async def reserve_process_minutes(request, url, input_path, job_id): "minutes_remaining": e.remaining, }) - # Count the job against the free daily caps only once it actually reserved. - if user.plan == "free": - user_counts = _daily_bucket("users") - user_counts[str(user.id)] = user_counts.get(str(user.id), 0) + 1 - ip_counts = _daily_bucket("ips") - ip = _client_ip(request) - ip_counts[ip] = ip_counts.get(ip, 0) + 1 - return user.id, priority, reservation_id, user.plan diff --git a/cloud/config.py b/cloud/config.py index 38eee4f..9eee3c0 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -35,11 +35,8 @@ FREE_PLAN_MINUTES = 20 # Gate the free allowance behind Google sign-in; magic-link-only accounts are # disposable-email fodder and stay unentitled. FREE_REQUIRES_GOOGLE = True -# Max processing jobs per free account per UTC day (abuse bound on GPU/proxy). -FREE_DAILY_JOBS = 3 -# Same bound per client IP across free accounts. Generous on purpose: much of -# the audience is behind CGNAT (India/Indonesia share IPs among thousands). -FREE_DAILY_JOBS_PER_IP = 5 +# The 20-minute monthly quota is the only bound on free usage — no daily job +# cap (it confused users and the minute ledger already caps real cost). # Free users' clips expire from R2 after this many days (paid libraries are # durable). Also an upgrade lever, mirroring OpusClip's 3-day free exports. FREE_CLIP_RETENTION_DAYS = 7 diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 27590d9..f505fbc 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -12,6 +12,7 @@ import ScheduleWeekModal from './components/ScheduleWeekModal'; import UsageMeter from './components/UsageMeter'; import TopUpModal from './components/TopUpModal'; import StarBanner from './components/StarBanner'; +import PlanChoiceModal from './components/PlanChoiceModal'; import TrialUpgradeModal from './components/TrialUpgradeModal'; import LoginModal from './components/LoginModal'; import TrialGate from './components/TrialGate'; @@ -174,6 +175,7 @@ function App() { const { billingEnabled, isManaged, isSignedIn, me, plan, refreshMe } = useAuth(); const [showLogin, setShowLogin] = useState(false); const [showTopUp, setShowTopUp] = useState(false); + const [showPlanChoice, setShowPlanChoice] = useState(false); const [showTrialUpgrade, setShowTrialUpgrade] = useState(false); const [topUpInfo, setTopUpInfo] = useState({}); // Durable R2 URLs (per clip index) for the current job — used as a fallback when @@ -538,6 +540,19 @@ function App() { // `keysMissing` now means "self-host BYOK keys missing" — it never fires on hosted. const keysMissing = !billingEnabled && (!apiKey || !uploadPostKey); const needsPlan = billingEnabled && !isManaged; // hosted, signed-out or no active plan/trial + + // Fresh sign-up with no entitlement yet: show the plan-choice popup once + // (AuthContext set the flag after the auth redirect) instead of the pricing page. + useEffect(() => { + if (billingEnabled && isSignedIn && !isManaged) { + let flagged = false; + try { flagged = localStorage.getItem('os_show_plan_choice') === '1'; } catch (_) { /* ignore */ } + if (flagged) { + setShowPlanChoice(true); + try { localStorage.removeItem('os_show_plan_choice'); } catch (_) { /* ignore */ } + } + } + }, [billingEnabled, isSignedIn, isManaged]); // 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']; @@ -769,9 +784,9 @@ function App() { { window.location.hash = '#/account'; }} /> )} {billingEnabled && isSignedIn && !isManaged && ( - )} {billingEnabled && !isSignedIn && ( @@ -894,15 +909,15 @@ function App() {
-

Start your free trial

+

Choose your plan

- 3 days free + Free plan available

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

- ) : ( @@ -1552,6 +1567,7 @@ function App() { {showLogin && setShowLogin(false)} />} + {showPlanChoice && setShowPlanChoice(false)} />} {showTopUp && ( setShowTopUp(false)} diff --git a/dashboard/src/components/PlanChoiceModal.jsx b/dashboard/src/components/PlanChoiceModal.jsx new file mode 100644 index 0000000..ef323de --- /dev/null +++ b/dashboard/src/components/PlanChoiceModal.jsx @@ -0,0 +1,103 @@ +import React, { useState, useEffect } from 'react'; +import { Check, Loader2, Zap, ArrowRight } from 'lucide-react'; +import { useAuth } from '../contexts/AuthContext'; +import { apiJson } from '../lib/api'; +import Modal from './ui/Modal'; + +const PLAN_ORDER = ['starter', 'creator', 'pro']; +const FREE_MINUTES = 20; +const fmt = (a, c) => new Intl.NumberFormat('en-US', { style: 'currency', currency: (c || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((a || 0) / 100); + +// Shown right after a sign-up that isn't entitled yet, instead of dumping the +// user on the full pricing page. Free is the default choice; paid plans check +// out inline. The free tier needs a Google account (abuse gate), so for an +// email-only user the free CTA offers Google sign-in. +export default function PlanChoiceModal({ onClose }) { + const { loginWithGoogle, googleAuthEnabled } = useAuth(); + const [plans, setPlans] = useState([]); + const [loading, setLoading] = useState(true); + const [busy, setBusy] = useState(null); + + useEffect(() => { + apiJson('/api/billing/plans') + .then((d) => setPlans(d.plans || [])) + .catch(() => setPlans([])) + .finally(() => setLoading(false)); + }, []); + + const byPlan = (p) => plans.find((x) => x.plan === p && x.interval === 'month'); + + const checkout = async (price_id) => { + setBusy(price_id); + try { + const { url } = await apiJson('/api/billing/checkout', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ price_id }), + }); + window.location.href = url; + } catch (e) { setBusy(null); alert('Could not start checkout. Please try again.'); } + }; + + const startFree = () => { + // Free needs Google; loginWithGoogle re-auths the account as Google-linked, + // which flips them to entitled. A user already on Google never sees this. + if (googleAuthEnabled) loginWithGoogle(); + else onClose(); + }; + + return ( + + {loading ? ( +
+ ) : ( +
+ {/* Free — the default */} +
+
+

free

+ $0 +
+

try it on your own videos

+
    +
  • {FREE_MINUTES} min / month
  • +
  • No credit card
  • +
  • Watermark · clips kept 7 days
  • +
+ + {googleAuthEnabled && ( +

continue with google

+ )} +
+ + {/* Paid — compact list */} +
+
+

paid plans

+ +
+

no watermark · more minutes · durable library

+
+ {PLAN_ORDER.map((p) => { + const e = byPlan(p); + if (!e) return null; + return ( + + ); + })} +
+ +
+
+ )} +
+ ); +} diff --git a/dashboard/src/contexts/AuthContext.jsx b/dashboard/src/contexts/AuthContext.jsx index 666cfe7..8b93a37 100644 --- a/dashboard/src/contexts/AuthContext.jsx +++ b/dashboard/src/contexts/AuthContext.jsx @@ -69,10 +69,13 @@ export function AuthProvider({ children }) { // This handler only runs on the auth redirect, so a resolved user here is // a fresh sign-in / sign-up — the top of the conversion funnel. if (signedInMe?.user) track('Signup', { props: { method: kind === 'verify' ? 'magic_link' : 'google' } }); - // Google sign-ins are entitled (free plan) and land in the app; only - // magic-link-only accounts (no entitlement) are routed to pricing, where - // the free card tells them to use Google. - if (signedInMe?.user && !signedInMe?.entitled) destination = '#/pricing'; + // Everyone lands in the app. A signed-in user with no entitlement yet + // (email-only sign-up) gets a plan-choice popup there instead of being + // dumped on the pricing page. Google sign-ins are already on the free + // plan, so they never see it. + if (signedInMe?.user && !signedInMe?.entitled) { + try { localStorage.setItem('os_show_plan_choice', '1'); } catch (_) { /* ignore */ } + } } catch (e) { // fall through — user lands signed-out } finally { diff --git a/dashboard/vite.config.js b/dashboard/vite.config.js index 5087b49..5bcc2dd 100644 --- a/dashboard/vite.config.js +++ b/dashboard/vite.config.js @@ -1,6 +1,12 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +// Backend target for the dev proxy. Defaults to the docker-compose service +// name; set VITE_PROXY_TARGET=http://localhost:8000 to run the dev server on +// the host against a backend reachable at localhost (no CORS, same-origin). +const backend = process.env.VITE_PROXY_TARGET || 'http://backend:8000' +const renderer = process.env.VITE_RENDER_TARGET || 'http://renderer:3100' + // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], @@ -10,30 +16,12 @@ export default defineConfig({ 'www.openshorts.app' ], proxy: { - '/api': { - target: 'http://backend:8000', - changeOrigin: true, - }, - '/videos': { - target: 'http://backend:8000', - changeOrigin: true, - }, - '/thumbnails': { - target: 'http://backend:8000', - changeOrigin: true, - }, - '/gallery': { - target: 'http://backend:8000', - changeOrigin: true, - }, - '/video': { - target: 'http://backend:8000', - changeOrigin: true, - }, - '/render': { - target: 'http://renderer:3100', - changeOrigin: true, - } + '/api': { target: backend, changeOrigin: true }, + '/videos': { target: backend, changeOrigin: true }, + '/thumbnails': { target: backend, changeOrigin: true }, + '/gallery': { target: backend, changeOrigin: true }, + '/video': { target: backend, changeOrigin: true }, + '/render': { target: renderer, changeOrigin: true }, } } })