Coolify starts the new container before stopping the old one and both share
output/, so the new one used to re-enqueue at startup the very jobs the old
one was still rendering, and the old one had 30 s to live regardless.
- Each instance stamps output/.instance; an instance that sees another id
drains: finishes what it runs, starts nothing, leaves queued manifests.
- A running job heartbeats its manifest every 10 s; the resume scan (startup
and every 30 s) adopts only manifests nobody heartbeated for 60 s, so no
job runs twice and none is lost. Reservations of live-elsewhere jobs are
kept out of the orphan refund; poison jobs stay refundable.
- SIGTERM drains too (up to DRAIN_TIMEOUT_SECONDS, default 840) before the
signal reaches uvicorn, so the socket stays open and Traefik keeps getting
answers. The app's Coolify stop grace period is now 900 s.
- /api/status answers from disk for a job this instance never held, so a
poll landing on either container during the handover works.
Verified in the local stack: SIGTERM mid-job -> job finished its clips,
'Drained', exit 0; status polled 200 throughout an 8 min drain; a job
submitted during the drain was left for, and resumed by, the next instance.
Eight findings from re-reading the erasure path, each one something that would
have shown up in production rather than in a test:
- The local purge missed two stores. SaaSShorts outputs (output/saas_<id>) and
generated thumbnails record ownership in their own in-memory dicts, not in
the .owner file, so neither was erased. Thumbnails are the serious half: the
hourly sweep deliberately skips their directory, so a deleted user's
generated images stayed on disk forever, publicly served at /thumbnails/.
- The purge ran on the event loop. rmtree over gigabytes of video stalled every
other request on the process; it goes through asyncio.to_thread now.
- Paths from those dicts are now resolved through _safe_under, so a session id
or output_dir containing ".." deletes nothing.
- Deleting a user made a webhook path reachable that never was: _apply_topup
takes the user id from Stripe metadata, so a top-up completing around the
deletion inserted a row pointing at a user that no longer exists. The FK
violation 500s the webhook, and since the event is only recorded after
handle_event returns, Stripe retries the same doomed insert for three days.
It confirms the row exists first.
- The "why are you leaving" box was free text stored in a record that
deliberately outlives the account, which is how personal data ends up in one
by accident. It is a closed list now, which also makes twenty deletions a
month countable instead of readable.
- Two concurrent deletes wrote two erasure records and sent two goodbye emails.
The DELETE's rowcount now decides which call is the real one; the UI holds a
ref so a double click doesn't fire a second Stripe cancel and R2 purge.
- The delete button armed itself when the confirm box was empty, if the page
ever rendered before /api/me resolved.
- The goodbye email claimed we keep "a one-way hash of your email and nothing
else", which was not true of the Stripe reference beside it. Fixed in the
email and in the privacy policy, EN and ES.
Also: skip the Upload-Post call when no managed key is configured, and say
plainly in the in-flight comment that it covers metered work only.
tests/test_account_local_purge.py covers tenant isolation across all three
stores and both traversal attempts; test_account_erasure.py gains the
confirmation gate, the API-key refusal, and the already-cancelled-at-Stripe
case that would otherwise trap a user forever.
The privacy policy already told users that "deleting your account from the
dashboard removes your content" — there was no way to do it. This adds one:
Account -> Delete account in the dashboard, DELETE /api/account on the server.
The endpoint refuses API-key auth (a leaked osk_ must not destroy the account
it was issued from) and requires the caller to retype the account email; the UI
does the same, collapsed behind a danger zone that itemises what actually goes.
Erasure is immediate and irreversible, because after it there is nothing left
to authenticate a recovery request against.
The order of the steps is the design, each one a failure mode:
- Stripe cancel first, aborting everything if it fails, so we never erase a
user we are still billing. An InvalidRequestError is treated as already
cancelled: a portal cancellation whose webhook never landed leaves our row
reading "active" forever, and the one account that could not be deleted
would be the one Stripe already stopped charging.
- R2 before the database, because those rows are the only index of which
objects belong to the user; dropping them first turns a failed purge into
permanent orphans.
- The DB delete is one transaction over an explicit table list, not the
declared ON DELETE CASCADEs: create_all never ALTERs an existing table, so a
constraint added after a table shipped lives in the models and not in
production. tests/test_account_erasure.py fails if a new table references
users.id without joining that list.
- A reserved usage_ledger row blocks the delete: erasing under a running job
would pull the output from beneath it and leave the reservation unsettled.
What survives, and why: the Stripe customer and its invoices (six years,
Spanish commercial law) and one account_deletions row holding a sha256 of the
email as proof the erasure happened, itself purged after five years by the
retention sweeper. app.py registers a callback so the working files in output/
and uploads/ go too instead of waiting for the hourly sweep.
Privacy policy sections 6 (EN + ES) now point at the button and name both
survivors; the Legal hub summary says the same in one line.
A job in flight published every clip as the clean reframe name, guessed by the
status poller. The hook and the captions live in derived files
(hooked_<ts>_<clean>, subtitled_<ts>_hooked_<ts>_<clean>), and only when the
WHOLE job finished did the result get rebuilt through _canonical_clip_file and
resolve to them. So a six-clip job showed clip 1 hook-less for the five clips
after it, which reads as the hook feature being broken.
main.py now prints CLIP_READY <index> <filename> at the end of each clip's
chain, after the caption step and carrying its result, so the name is the file
that will actually be delivered. app.py consumes the marker the way it already
consumes PROXY_BYTES: intercepted in enqueue_output, never shown as a log line.
The poller now serves only announced clips. That also closes the older hazard
in the code it replaces, whose own comment admitted it was guessing: presence
on disk was treated as done, so a clip could be served while ffmpeg was still
writing it. A clip whose marker never arrives (it failed) stays hidden until
the job ends and the result is rebuilt from disk, as before.
The stdio reconfigure only covers the API process. main.py prints an
emoji on its first line and configures nothing, so on a cp1252 console
the server now starts but every job dies before rendering.
Measured 22-ago-2026 against prod, on one 46 MB / 52 s clip:
origin -> itself through Traefik 130 MB/s
origin -> a datacenter client 838 KB/s
origin -> the author's browser 90 KB/s (8.5 min for one clip)
R2 S3 endpoint -> the server 11 MB/s, 206
R2 S3 endpoint -> that browser 503, every single request
So the API process is not the bottleneck (it serves the file at 130 MB/s while
the box sits at 0.01 MB/s of egress); the long path out of Hetzner is. And the
fix for that, R2, is unreachable from a browser: *.r2.cloudflarestorage.com is
an S3 endpoint, and a presigned GET that curl fetches at 11 MB/s with identical
headers returns 503 to Chrome.
R2_PUBLIC_BASE points presigned_get() at a custom domain bound to the bucket
instead, which serves the same objects through the normal Cloudflare edge.
Unset, everything keeps signing S3 URLs exactly as before, so this is inert
until the domain exists. Switched at that one choke point because every caller
hands the URL to a browser.
The download button streamed nothing to the screen while it buffered tens of MB
into a blob, which on a slow link is minutes of a button that looks dead. It now
reports percentage, which needs Content-Length readable from JS, which needs the
CORS middleware to name it in expose_headers.
Every log line in app.py is emoji-prefixed and a Windows console is cp1252
by default, so _recover_jobs_from_disk() kills the server during startup:
print(f"♻️ Recovered {recovered} completed job(s) from disk.")
UnicodeEncodeError: 'charmap' codec can't encode characters in 0-1
ERROR: Application startup failed. Exiting.
It never binds a port, so the dashboard is simply unreachable on a stock
Windows box. PYTHONIOENCODING=utf-8 works around it, but that has to be
known before the first run, and the traceback does not suggest it.
subtitles._configure_stdio already does exactly this for the transcription
path. The server needs it too, and needs it before the first print, so it
runs at module scope rather than in the lifespan hook.
Verified: uvicorn with no PYTHONIOENCODING, and an import under a stdout
forced to cp1252/strict. Both start and log the emoji correctly.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QiYkHKB7Tp7X6NdnEutda2
The job runner built its command as ["python", "-u", "main.py"], which
resolves against PATH. Inside the Docker image there is exactly one
interpreter so it works, but in the documented non-Docker install --
a venv -- PATH points at whatever Python came first, not the one running
the server. Every job then dies immediately:
ModuleNotFoundError: No module named 'cv2'
The CLI works fine in the same checkout, so it presents as "the dashboard
is broken" rather than anything to do with interpreters.
_run_quality_probe five hundred lines up already uses sys.executable for
exactly this reason; this makes the two agree.
Verified: same job, same venv, failed before and completed after.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QiYkHKB7Tp7X6NdnEutda2
The static ISP pool (dfa3124) moved downloads off the paid proxy but never
touched cloud/metering.py, so probe_url_minutes kept reading PROXY_URL alone.
Every managed YouTube submission still paid DataImpulse for 0.2-1 MB of yt-dlp
metadata (measured through a counting proxy) while the download itself went out
free over Decodo — and invisibly, because PROXY_BYTES only counts the bytes of
the winning download attempt.
The probe now walks the same cheapest-first chain as the download: direct when
DIRECT_FIRST=1, then the statics rotated per probe, then the paid proxy as the
last resort. Proxies are the outer loop and extractor strategies the inner one,
so the paid route is only reached after every free one has failed on both.
That also stops a drained paid proxy from taking YouTube ingest down on its own
("Could not determine the video duration") while the statics are healthy.
Two smaller cuts on the same path: a user with no minutes left now gets its 402
before the probe instead of after it, and a failed route no longer dumps a
yt-dlp ERROR block per proxy per strategy into the API log (the watcher is what
reports a dead route).
Cloud keeps every user's connected accounts as profiles inside one
Upload-Post account, so the profile string is the only thing separating
'schedule to my TikTok' from 'schedule to a stranger's'. All three call
sites read `forced_profile or <client-supplied profile>`, which honours
the client's value whenever the server fails to resolve its own — one
resolver bug away from a cross-tenant write, and invisible in review
because the happy path looks identical.
resolve_post_profile() now refuses in cloud mode instead of falling
back, and never consults the client value there; self-host keeps
picking its own profile, since it owns the account behind the key.
Tests pin both behaviours and the profile filter on the scheduled-post
list, which is what stops one tenant reading or cancelling another's
queue.
GET /api/social/scheduled lists the caller's pending posts and
DELETE /api/social/scheduled/{job_id} cancels one. Upload-Post's own
schedule endpoint takes no profile filter and returns the whole managed
account, so both filter by the caller's profile server-side — the same
multi-tenant trap as the impressions endpoint, and the reason cancel
404s instead of 403s on someone else's job.
The template picked its next daily slot from n8n workflow static data,
which two approvals tapped seconds apart both read before either wrote,
booking the same slot and publishing together (seen in a live run). It
now derives the slot from the server-held queue, which is shared state
and cannot race with itself that way.
Upload-Post's /total-impressions/{profile} echoes the requested profile
but returns account-wide numbers — a profile with zero posts got 85K
Instagram impressions — which for managed users leaks other tenants'
aggregates into the dashboard card and the analytics API. Aggregate the
post-analytics cache instead, which is correctly scoped by ?user=, and
keep the same response shape (total_impressions + per_platform).
GET /api/social/analytics (profile totals), /analytics/posts (per-post
cached metrics) and /analytics/impressions (windowed totals). Managed
users are locked to their own profile and rate-limited to 60/h in a
bucket separate from the metering probes; cloud without a plan gets a
clean 402 no_plan instead of a misleading missing-header 400. BYOK
keeps its own key and picks the profile with ?user=.
Prod 20-ago, 5 of 12 managed jobs failed and the alert said 'youtube
download' — no download had terminally failed. Three fixes:
- The quality probe now reports source duration, and /api/process rejects
sources under MIN_SOURCE_SECONDS (default 45, 0 disables) on all three
ingest paths with a clear message. A 24s YouTube Short cannot yield
15-60s clips; Gemini returns nothing and the job burns managed minutes
to die with 'no usable clips' (3 of the 5 failures, one user retrying
the same cat video).
- _job_error_text drops per-attempt download warnings when a later
attempt succeeded (HD-direct fails on every job since the server IP
ban; static proxies recover it), and gained an 'Error:' marker so
raised exceptions (RuntimeError:, GeminiBlockedError:) reach the alert
instead of a bare 'Traceback ... exit code 1'. The classifier names
'no clips found (user video)' as its own content-shaped category.
- (env, no code) DIRECT_FIRST=0 in prod: with the server IP banned the
direct attempt only added ~10s and the noise behind these alerts.
Issue #68: publishing a video to YouTube from the Studio now offers
'create clips from this video'. /api/process accepts a
thumbnail_session_id, hardlinks the session's source under the job's
name (so /api/source, the clip editor and retention treat it like a
normal upload) and forwards the session's transcript via a new
main.py --transcript flag, so the pipeline skips a second Whisper pass.
Any problem with the forwarded transcript (missing file, no segments,
silent source) falls back to transcribing normally, and empty
transcripts are not forwarded at all. Contract pinned by six endpoint
tests plus a fallback case; verified end to end locally against the
running app (speech video: 'Reusing precomputed transcript (4
segments)' in the job log).
Issue #46 round two: the 1h sweep kept deleting finished projects under
self-hosters who never touched their env. The disk is already bounded by
OUTPUT_MAX_GB / UPLOADS_MAX_GB, so age can afford to be generous. Cloud
keeps the tight default because clips are archived to R2 on completion.
The results panel now tells self-host users how long their clips live
and which env var controls it, and the restorable-session window follows
the new default.
Turns the clip editor into a three-point editing surface: mark in/out on
the source, send the range to the clip, and scrub the result — with the
timeline honest about which parts of the edit the last render can already
show.
- Chrome: the source track ignored drags entirely. Without preventDefault
the gesture became a text selection and then a native drag, which
swallows every later pointer event and shows the not-allowed cursor.
- The source track's block is draggable (body moves, edges trim) and every
gesture on it scrubs the source monitor, so a cut is chosen against the
picture rather than against numbers.
- Three-point editing: mark in / mark out (i / o) off the monitor's
playhead, then "replace #N" (.) or "insert after #N" (,). Dragging empty
track marks a range instead of silently appending a segment.
- /edl ships the whole source transcript instead of a ±45s window: a cut
can only be extended into words the editor was sent. The panel shows all
of it, follows playback, and seeks the monitor on click.
- Layout: source monitor + its track + transcript | clip preview + its
track | controls. Each track sits under the video it drives.
- The clip timeline works while edited. A cut that only removes material
keeps nothing but frames the last render already produced, so it stays
scrubbable and playable; only material the render never saw is marked
red, and the playhead — now a solid handle — stops at its edge.
Transcript words render in memoised 50-word slices: repainting a couple of
thousand of them costs ~66ms, and timeupdate fires four times a second.
The residential proxy ran out of traffic (407 TRAFFIC_EXHAUSTED,
19-aug-2026) and every YouTube-URL job failed with only easy-to-miss
one-shot alerts. Now:
- cloud/alerts.py: a background watcher probes the proxy every 30 min
(generate_204, a few bytes of paid traffic). On failure it alerts
immediately, re-alerts every 2 h while the proxy stays down, and sends
a recovery confirmation when it answers again — so exhaustion is caught
even before the next user job fails.
- record_job_outcome: a proxy-classified job failure also opens the
incident, so job-driven detection and the probe share one state.
- app.py: the watcher starts from the lifespan in managed mode.
- tests/test_proxy_watch.py: state machine (first alert, renotify window,
recovery + reset, job-error trigger).
The auto-hook was burned into the canonical clip in place, so editing the
hook stacked a second overlay on top of the first. Hooks now follow the
exact derivation pattern captions use:
- main.py: auto_hook_clip writes hooked_<ts>_<clean>.mp4 next to the clean
canonical instead of mutating it; captions burn on top of the hooked file
(subtitled_<ts>_hooked_<ts>_<clean>). Watermark moves BEFORE the hook so
the branding lives in the canonical and survives hook replacement.
- app.py: _strip_burned_hook walks hooked_/legacy hook_ prefixes back like
_strip_burned_captions; /api/hook strips captions AND the old hook before
burning, so a new hook always REPLACES the previous one. New remove flag
strips the hook entirely (captions re-applied, no metering). Burned hook
recorded/cleared in clip metadata (auto_hook key) and returned as
burned_hook. _canonical_clip_file resolves hooked_*/hook_* derivations.
- cloud/videos.py: archive the hooked_ intermediate of a captioned hook so
restored projects keep the walk-back chain editable.
- ResultCard: stripBurns knows hooked_<ts>_ (the Remotion preview now
composes over the truly clean clip — no more stacked preview), burned
hook tracked in state, remove handler wired to the modal.
- HookModal: warning now says replace, plus a 'remove hook from clip'
action when one is burned.
Auto-hook (opt-in per job, dashboard default ON):
- /api/process accepts auto_hook + auto_hook_style; absent means off, so
API/MCP/webhook callers keep byte-identical output.
- main.py auto_hook_clip burns each clip's viral_hook_text (Gemini already
produced it, it was only used to pre-fill the modal) into the canonical
clip in place — after reframe, under watermark and captions — so every
derived-name convention (subtitled_/recut_ walk-backs, R2 archive,
restore) keeps working untouched. Fail-open like auto_caption_clip.
- Burned hook recorded as clip.auto_hook in metadata; the hook modal warns
before stacking a second one.
- MediaInput: 'auto hook titles' toggle + style select in advanced options,
persisted in localStorage.
Emoji that actually render:
- Gemini prompt now asks for 1-2 emojis in viral_hook_text.
- Dockerfile installs fonts-noto-color-emoji — without it prod silently
stripped every emoji (no candidate font existed in the image).
- hooks.py supports fixed-bitmap color fonts (NotoColorEmoji only loads at
its 109px strike; Apple Color Emoji at 160): glyphs render at native size
and are Lanczos-rescaled to the text size instead of being treated as
unavailable. macOS system font added for local dev.
Editor polish:
- HookModal persists last style/position/size/entrance (always reset to
classic before, which read as the picker being broken).
- Remotion preview positions aligned to hooks.py (top 20%, bottom 70%).
- Warning when a bottom hook will overlap burned/preview captions.
- Entrance-animation control greyed out with a note when the clip
re-renders on the server, where the hook is static.
- Meter the re-render: /api/clip/reframe now reserves/commits/releases
minutes exactly like a source-path /rerender — it is the same GPU work,
and it was free and uncapped.
- Re-apply captions by default (reapply_captions param to opt out): every
default clip ships with burned captions, and the reframe silently
returned caption-less files.
- Read metadata.json INSIDE the per-job lock (same _reframe_locked shape
as /rerender): the read-outside/write-inside window let a concurrent
rerender's recipe get clobbered by a stale write.
- Interplay with whole-clip framing: recipe.framing keeps forcing its
layout on the scenes the user did not hand-position (apply_crop_overrides
runs after force_strategy, so per-scene wins where named), and the
recipe is preserved through the reframe instead of being rebuilt bare.
- /rerender clears stale crop_overrides: scene indices only mean anything
against the cut they were made for, and the trim render does not apply
them — leaving them made /scenes reopen showing overrides that would
land on the wrong shots.
- /scenes: entitlement-gated (it cuts, scene-detects and encodes on every
open), serialized per job (stable output names tore under concurrent
opens), 400 on horizontal jobs, real aspect for square jobs, temp_
prefix on preview/thumbnails (kept out of the self-host S3 backup),
faststart + timeout on the preview encode.
- Tests for all of it plus the apply_crop_overrides math the PR described
but did not include (12 new, suite at 502).
Conflicts were the parallel override parameters: render_clip /
process_video_to_vertical / reframe_v2.render / perform_recut now carry
BOTH force_strategy (whole-clip framing, main) and crop_overrides
(per-scene manual framing, PR #70). The v1-fallback safety net now also
raises for force_strategy, which had the same silent-revert hole the PR
fixed for crop_overrides.
Fixes#69. The subtitle modal lets the user edit the caption text, but the
edits only traveled through the in-browser Remotion path; the FFmpeg path
(taken by every karaoke style and by any clip with server burns, i.e. all
clips with default captions) sent style params only, so the server
regenerated from the stored transcript and silently discarded the edits.
/api/subtitle now accepts an optional 'words' list (clip-relative ms, the
same shape the /transcript endpoint serves) and builds a synthetic
transcript from it, so both the SRT and karaoke ASS generators burn the
edited words verbatim. Words get Whisper's leading-space convention so the
block collector keeps their boundaries. The modal sends them only when the
text actually differs, and never on bulk apply-to-all (edits are per-clip).
Verified live: an edited 5-word line burned exactly as typed, correctly
grouped into blocks.
The reframe engine picks the crop automatically and is right most of the
time. When it is wrong it is badly wrong, and there was no way to say
"no, frame it here".
The unit is the SCENE, not the clip. A podcast cuts between a fixed close
camera and a fixed wide one, and the right crop differs per camera; scene
boundaries already are those camera changes. Scenes the user never touches
keep the automatic camera, so correcting one bad shot cannot spoil the
shots the tracker got right.
Backend:
- reframe_v2.apply_crop_overrides() replaces a scene's slice of the camera
trajectory with a constant and forces it to TRACK, so a scene the
classifier had sent to GENERAL comes back to a vertical crop. It runs
after every automatic pass, including the ALTERNATE writes, so a manual
choice always wins.
- A scene can also be split by hand: the override writes straight into
`splits`, which means the user can stack a scene the detector never
proposed, with no dependency on SPLIT_LAYOUT being enabled.
- GET /api/clip/{job}/{i}/scenes returns the scenes with a frame from the
UNCROPPED cut plus a light preview with audio, and suggests a centre from
the largest face in each shot.
- POST /api/clip/reframe re-renders with the clip's cut untouched. It is
deliberately separate from /api/clip/rerender: a scene index only means
something against a given cut, so letting framing ride along with a trim
save would move every override onto the wrong shot.
- render_clip raises instead of falling back to the v1 engine when manual
framing is present, since v1 ignores it and would silently return an
automatically framed clip.
Frontend:
- ReframeEditor lists the scenes, each with the source frame, a draggable
9:16 window, and a play button that plays that scene from the preview so
the user can hear who is talking before choosing.
- Saved overrides are loaded when the editor reopens. Without that the next
save would discard every earlier adjustment, because a re-render rebuilds
from source using only what it receives.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The scene classifier only counts faces, so a screencast-style video with a
presenter in frame gets TRACK and the crop eats the slide (the SCREENCAST/
WIDE detectors sit behind the opt-in layouts=auto flag). The clip editor now
has a framing selector that pins every scene's layout: 'full' renders the
whole source frame (WIDE: no side-crop, blurred bands), 'track' forces the
subject-tracking crop, 'auto' returns to the classifier.
Plumbed as force_strategy through reframe_v2.render -> render_clip ->
perform_recut -> /api/clip/rerender (and the recut_clip MCP tool). A
non-auto choice always re-reframes from the retained source (409 without
it) and persists in the clip's recipe, so later plain trims inherit the
look instead of silently reverting; an explicit 'auto' resets it.
Verified live: framing=full on a TRACK-cropped clip re-rendered with the
full frame visible edge to edge (125s source path), and the editor reopens
with the persisted choice preselected.
/api/process (and the process_video MCP tool) now accept optional
target_clips (1-15) and clip_min_seconds / clip_max_seconds (5-180),
surfaced in the dashboard as a collapsed 'advanced options' section.
Blank means the AI decides, keeping the default request byte-identical.
Plumbed through the same env overrides the A/B harness already reads:
CLIP_TARGET_MIN/MAX (existing) and a new clip_duration_bounds() in
clip_selection.py backing CLIP_MIN_SECONDS/MAX_SECONDS. The detail and
visual prompts take the band as template placeholders instead of the
hardcoded 15-60, and word-snapping enforces the same bounds. All three
knobs are honest targets, not guarantees: the model still returns fewer
clips when the material doesn't hold them, and the UI copy says so.
Verified live: target_clips=2 + band 8-15s on the demo video returned
exactly 2 clips of 13.3s and 13.7s (the uncontrolled run gave one 41.7s
clip); out-of-range values 400 with a named reason.
- Per-job asyncio lock around /api/clip/rerender (same pattern as
_restore_locks): concurrent saves raced on the metadata.json
read-modify-write, with the last writer silently reverting the other
clip's recipe and video_url.
- Re-run normalize_segments after snap_to_words + clamp: a segment fully
outside the canonical range used to clamp to an inverted (end < start)
window that passed within_range and died in ffmpeg as a 500; it is now a
clean 400.
Every new free user's first job fired a Telegram message, which at current
signup volume is pure noise. Clip-activity notifications now fire only for
paid users' jobs; the activation signal lives in analytics, not the ops chat.
Every clip now exposes its recipe (which source segments it was cut from)
via GET /api/clip/{job}/{i}/edl, and POST /api/clip/rerender re-renders it
from an edited segment list: fast path recuts from the already-reframed
canonical file, source path re-reframes from the retained source
(--keep-original now passed for URL jobs). Captions/subtitles/transcript
remap piecewise through recut.virtual_transcript for multi-segment clips.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Agents don't forget to come back; humans do. Make the whole pipeline
drivable without the dashboard:
- API keys (osk_...): sha256-stored tokens minted from the account page.
get_current_user_optional resolves them like a session, so metering,
entitlement, priority and job ownership apply to agents with zero
endpoint changes. Key management refuses API-key auth (a leaked key
cannot mint replacements).
- MCP server at /mcp: stateless Streamable-HTTP JSON-RPC, no SDK
dependency. Six tools (process_video, get_job_status, list_clips,
get_quota, add_subtitles, publish_clip) that call back into this same
app in-process via ASGITransport with the caller's auth headers, so
MCP can never drift from REST behavior. Cloud requires a key;
self-host stays BYOK-open.
- Completion webhooks: webhook_url (+ optional HMAC webhook_secret) on
/api/process, SSRF-checked at submit AND delivery, fired once after
the R2 archive so payloads carry durable links, survives redeploys
via the resume manifest.
- Dashboard: API keys card in the account page (create once-shown key,
list, revoke).
- Tests pin BILLING_ENABLED=0 in conftest so the suite no longer
depends on the developer's personal .env.
Four new layouts, all off by default, plus a picker that decides which one a
video gets.
- SPLIT (split_layout.py): two speakers stacked. The test is COEXISTENCE in the
same frame, not presence measured separately: BlazeFace loses faces in
profile, which is how someone sits while listening, so a presence test
rejects conversations for looking like conversations. Coexistence also
separates a two-shot from a shot/reverse-shot, where stacking would show the
same person twice.
- SCREENCAST / WIDE (screencast_layout.py): content over the presenter, or full
width when the content fills the frame and the presenter is composited on top
of it (stacking there shows the same thing twice).
- ALTERNATE (active_speaker.py): hard cuts to whoever is talking. Mouth activity
must be normalised per speaker against their own resting state; raw magnitude
scales with contrast and lighting and handed one person 90-100% of the scene.
- Punch-in (punch_in.py): a 12% push on the beats, riding the TRACK path by
widening its per-frame crop command from x-only to w/h/x/y.
layout_picker.py chooses between none/screencast/split with one Gemini call per
source video. Measured over the 48-clip corpus against hand-checked labels:
94/92/96% across three runs, 0-1 false positives out of 28, and 2 clips of 48
changing answer between runs. The key is asking for a DECISION between closed
options rather than a measurement: the four previous attempts (Canny, MSER,
coverage, width) all asked for a number and none separated a spreadsheet from a
corner scoreboard.
app.py exposes all of it per job through `layouts` on /api/process. Without that
field the pipeline behaves exactly as before.
83 new tests, 315 green.
Upload-Post's `post_mode` defaults to DIRECT_POST, so a clip went straight to
the user's TikTok feed. MEDIA_UPLOAD lands it in their drafts to finish in
TikTok's own editor instead.
Drafts are the right default for an automated pipeline: nothing reaches an
audience without the account owner seeing it, and covers, sounds and trending
hashtags are chosen inside TikTok anyway — the parts that decide whether a clip
travels are exactly the parts this cannot do from the outside.
Applied to both paths that can target TikTok (the clip publisher and the
SaaS-shorts publisher) through one constant, so they cannot drift apart.
TIKTOK_POST_MODE=DIRECT_POST restores publishing without a code change.
The UI now says so before the button is pressed, in both publishers, and leads
with the upside rather than the caveat. Without it the change reads as a bug:
someone expecting a live post, finding nothing on their profile, and concluding
the upload failed. The notice also tells them a TikTok notification is coming,
which the Upload-Post docs confirm for MEDIA_UPLOAD ("users will receive an
inbox notification"), so they know where to look.
The browser reports the funnel, but not what decides whether this product
retains: on 26-jul-2026, 491 of the 564 users who ever processed a video did it
exactly once. Every clip-quality fix that shipped that day — 1080p delivery,
captions by default, loudness normalisation — was aimed at that 87%, and
nothing in the stack could measure whether it moved.
Client-side cannot answer it. A render finishes minutes later, often after the
tab is gone, and ad-blockers eat a share of the rest. So the backend now emits
ClipsDelivered / JobFailed with the user's profileId and a `job_index` — the
count of process jobs that user has run. Counting distinct users at index 1
versus index >= 2, before and after today, answers the question directly.
Failures carry the same reason classification the Telegram alerts use, so the
"did it break or did they just not come back" split is visible too.
Fire-and-forget throughout: no config means a silent no-op (the normal state
for self-hosted), every send is a background task, and every failure is
swallowed. Analytics must never slow down or break a job.
Needs OPENPANEL_CLIENT_ID and OPENPANEL_CLIENT_SECRET in the environment — a
WRITE client, which is a different credential from the read/root client the MCP
needs. Verified against the live instance: the write path returns 200 and the
module no-ops cleanly when unconfigured.
Two bugs in the "your N clips will be deleted tomorrow" email.
The button pointed at {frontend_url}/dashboard, a route that has never existed:
the app is a single-page app routed entirely through the hash, and #app is what
opens it. Until today /dashboard fell through to the SPA fallback and quietly
showed the marketing landing, so the link looked like it worked. Now that
unknown paths return a real 404 it fails visibly. Both this and the clips-ready
email now link to /#app; the clips-ready one was passing the bare frontend URL,
which showed the landing page to anyone whose browser had not already set the
skip-landing flag.
The duplicate send is worse. De-duplication was `_warned_video_ids`, a set in
process memory, and the warning window is a full day while the sweep runs every
six hours. Any API restart inside that window re-armed the warning for everyone
already told. That is exactly what happened today: the 06:00 warning went out,
three deploys restarted the API (frontend and API share this repo, so the SEO
pushes redeployed both), the container came up at 12:36, and the sweeper's first
run six hours later at 18:36 mailed the same clips again.
Warnings are now recorded in clip_expiry_warnings, keyed by clip id, written
before the send. A new table rather than a column because the schema bootstrap
is create_all, which creates missing tables but never ALTERs one — same reason
SignupAttribution is its own table. The FK cascades from user_videos, so rows
disappear when purge_free_expired deletes the clip and no cleanup pass is needed.
Recording before sending is deliberate: a duplicate email is the failure being
fixed, while a warning row for a mail that then failed to send costs that user
one notice.
No backfill. Clips already warned about have no row yet, so the current cohort
gets one more warning after this deploys and none after that. Backfilling the
window would also silence the first warning for anyone who entered it since the
last sweep, and a missed deletion notice costs the user their clips, while a
duplicate only costs them an email.
Verified against a real Postgres: create_all builds the table, the primary key
rejects a second row for the same clip, the cascade removes warnings when the
clip is deleted, and warn_free_expiring sends exactly one email across two
sweeps plus a module reload standing in for a restart (which is what used to
produce the second email).
Captions must always be the LAST layer. Editing or hooking a clip that already
had them burned in produced `edited_subtitled_<...>`, and the next subtitle pass
stacked a second caption layer on top of the first — visibly doubled and
unreadable in a real user clip found in prod today. /api/edit and /api/hook now
derive from the clean file and put captions back afterwards, so a restyle always
has an un-captioned base to burn onto. The latent bug predates auto-captions but
shipping them by default made it the normal path. The walk-back is now one
helper instead of being open-coded in the subtitle endpoint.
Loudness was uncontrolled. A clip inherited whatever its source was mastered at,
measured across real delivered clips from -13.8 LUFS on a loud upload down to
-28 on a quiet talk, while TikTok/Reels/Shorts all normalise playback to around
-14 — so the quiet ones just sound thin in the feed. loudnorm at the clip cut,
where the audio is already being encoded, so it costs nothing. Verified to pull
both extremes to target: -29.7 -> -13.7 and -10.1 -> -13.5. AUDIO_NORMALIZE=0.
The GENERAL layout wasted the frame. Fitting a 16:9 source to full width left
it 608px tall in a 1920 frame: 32% content, 68% blurred filler. Now scaled by
height to 42%, trimming the overflow. Deliberately conservative — GENERAL is
chosen for groups and landscapes, exactly where cropping the sides cuts someone
out, so 0.55 was tried and rejected for throwing away 42% of the width. 0.42
keeps ~76%. GENERAL_CONTENT_HEIGHT_RATIO=0.32 restores the old behaviour.
The TRACK/GENERAL classifier only counted faces, so a screencast that happened
to contain one face was cropped to it — real prod clips came out with headlines
cut mid-word and unreadable. A cheap Canny pass over the side thirds (the part a
9:16 crop discards), with face boxes blanked first, now routes text-dense scenes
to GENERAL instead. GRAPHIC_DENSITY_THRESHOLD=1.0 disables it.
Clips now ship captioned, and the modal could only restyle — there was no way
back to a clean clip, so anyone who didn't want captions was stuck with them.
Adds POST /api/subtitle/remove, which points the clip at its un-captioned
original. No re-encode and no quota: the pipeline already keeps the clean file
next to the derived subtitled_<ts>_ one, so removing is choosing the other file.
It reuses the burn path's walk-back, so it undoes any number of restyles, and
running it twice is a no-op.
Verified end to end: auto-caption, restyle (burning from the clean file rather
than stacking a second layer), remove, and remove again.
Captions are what make a short readable with the sound off, and 91% of
delivered clips had none (35 subtitle jobs against 380 process jobs in the
25-jul-2026 prod audit) because they were opt-in behind a modal. Now every clip
comes out captioned and the modal becomes a re-style, not a discovery.
The look was picked by rendering four candidates on a real clip and comparing
them: white Anton uppercase, yellow active word, heavy black outline, gentle
pop. Yellow because it is the one colour that almost never occurs in footage,
so the active word reads instantly on any background. The base text stays fully
opaque — dimming it, which several caption tools do, tested worse over bright
scenes. Captured in AUTO_CAPTION_STYLE so there is one place to change it.
Two fixes fell out of rendering it for real:
- Captions sat at MarginV=25 (8.7% of frame height), underneath TikTok's and
Reels' own bottom chrome. Raised to a documented SAFE_MARGIN_V of ~15%, now
a parameter rather than a hardcoded literal.
- The pop effect scaled the active word 75->112, wide enough that any frame
caught mid-animation read as a sizing bug. Softened to 90->108.
Wiring follows the convention already used by /api/subtitle: the captioned file
is written as subtitled_<ts>_<clip>.mp4 next to the untouched original, so
re-styling from the modal replaces the captions instead of burning a second
layer over them (its existing walk-back resolves this unchanged). The places
that rebuild the canonical clip name from disk — restore after a restart, the
project reopen, the download bundle — now resolve through _canonical_clip_file
so a redeploy cannot silently serve the uncaptioned version. R2 uploads follow
video_url, so the durable library gets the captioned clip too.
Captions are applied after the watermark, never before, and any failure is
swallowed: a caption problem must not cost the user a clip they already paid
for. Silent videos have no transcript and are skipped. AUTO_CAPTIONS=0 is the
rollback lever.
Verified end to end in the container: burn produces the derived file, the app
resolves to it, the modal walks back to the clean original, silent input ships
uncaptioned, the kill switch works, and the newest styling wins.
Captions are table stakes for short-form — a clip without them barely works on
any platform — but every burn cost 2 minutes, 10% of the free monthly quota,
roughly what generating the clip cost in the first place. People skipped them:
only 9% of delivered clips had captions in the 25-jul-2026 prod audit (35
subtitle jobs against 380 process jobs).
The charge never matched the work. The normal path reads the transcript already
stored in metadata.json and runs one short FFmpeg pass — measured at 4s on CPU
for a 12s clip, 1-2s on the GPU. Charging 120s of quota for that is ~30x the
compute, and it was invisible in the UI, so users were drained without being
told. The endpoint is already gated by require_managed_entitlement, so the
charge was never what bounded abuse.
Dubbed clips keep the charge: subtitling them re-runs Whisper over the
translated audio, which is real work. The rule lives in cloud.config next to
the constant so it stays testable without importing app.
Also short-circuit reserve_managed_action on a zero-minute action rather than
writing a 0-minute ledger row on every call.
Tres jobs de prod murieron el 22-jul porque Gemini contestó 200 con el
cuerpo vacío. Eso revienta al parsear, no al llamar, así que se escapaba
del bucle de reintentos: un parpadeo de la API bastaba para perder el job.
El mismo payload funciona 5 de 5 al reintentarlo.
- gemini: el parseo pasa a estar dentro del bucle, y la respuesta vacía o
no parseable cuenta como error transitorio.
- descarga: reintento del 403 de YouTube, que casi siempre viene de que el
proxy residencial rota la IP de salida entre la extracción y la descarga
(3 de 62 descargas en 24h).
- se elimina el fallback de reframear el vídeo entero: no escribía
metadata.json, así que app.py marcaba el job como fallido igualmente
después de gastar GPU en un render que nadie llegaba a ver.
- alertas: la clasificación lee ahora las líneas de error del log en vez
de las 10 últimas, que eran ruido de progreso y hacían culpar al
subsistema equivocado (un parpadeo de Gemini se reportó como ffmpeg).
Stripe — dos huecos que faltaban:
- invoice.paid no disparaba nada: las renovaciones mensuales entraban en
silencio. Ahora 💵 'Payment received: $X' en cada cobro real (primera compra
Y renovación), con el importe y el motivo (new subscription / renewal).
- El aviso de top-up ahora incluye el importe cobrado.
- Helper _money() para formatear cents+currency ('$59.00 USD').
Clips (opción 1, alta señal para no ahogar el canal cuando crezca el free):
- _notify_clip_activity avisa por Telegram SOLO en el primer clip de un
usuario (activación) o en clips de usuarios de pago. Nada de un ping por
cada clip free. Incluye email, plan, título y nº de clips.
Verificado enviando los formatos reales al Telegram del admin.
- 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.
Un job vive solo en memoria, así que matar el contenedor a mitad de proceso
lo perdía: al usuario se le cortaba el clip. Ahora al encolar se escribe un
manifiesto mínimo (.resume.json: cmd, prioridad, user, reserva, watermark —
sin secretos, el env se reconstruye al reanudar) y en el arranque se
re-encolan los que se quedaron a medias, tras _recover_jobs_from_disk (los que
ya habían terminado de generar clips se recuperan como completados, no se
reanudan).
- Tope MAX_RESUME_ATTEMPTS=2: un vídeo que reviente el worker no puede meter
al servicio en un bucle; se rinde y se refunda por la vía de huérfanos.
- La reserva de minutos del job reanudado se conserva (no se refunda como
huérfana) para que la liquide el run reanudado.
- El manifiesto se borra en cualquier estado terminal (éxito o fallo real);
solo sobrevive si el contenedor murió a mitad, que es cuando queremos
reanudar.
Verificado en el contenedor: reanuda conservando reserva, no re-ejecuta
completados, se rinde con envenenados. Reconstruye env con la clave gestionada
sin volcar secretos a disco.
Con volumen persistente el barrido por antigüedad (1h) acota la edad de lo
guardado pero no su tamaño: una tanda de vídeos largos puede llenar el disco
dentro de la misma ventana. Se añaden topes duros (OUTPUT_MAX_GB=25,
UPLOADS_MAX_GB=15) que borran lo más antiguo hasta bajar del límite; los clips
están archivados en R2 y se rehidratan solos, así que solo cuesta una descarga.
Además el barrido saltaba a borrar output/thumbnails, que respalda un mount de
StaticFiles: borrarlo dejaba /thumbnails devolviendo 500 hasta el siguiente
arranque.
Y fuera el badge '3-Day Trial' de la landing, que ya no aplica.
1. Watermark al 40% de la altura en vez de arriba del todo: ahí caía en la
banda negra/desenfocada del 9:16, espacio muerto que se recorta sin tocar
la imagen. Un 16:9 letterboxed ocupa del 34% al 66%, así que ahora quitarla
obliga a cortar vídeo de verdad.
2. OUTPUT_DIR no es durable en prod (cada redeploy lo vacía), y los endpoints
que leen ficheros del job devolvían 404 en proyectos que el usuario sigue
viendo en su biblioteca: transcript, download-all, subtítulos, hooks,
efectos, doblaje y publicación. Nuevo _ensure_job_files() que rehidrata
desde R2 bajo demanda reutilizando el flujo de /restore. Se deja fuera el
polling de /api/status para no machacar R2.
3. download-all no encontraba ningún clip en proyectos restaurados: el
metadata.json en disco nunca lleva video_url (se inyecta solo en memoria),
así que derivaba nombres vacíos. Ahora usa el registro en memoria (que
además refleja ediciones subtitled_/hook_) y cae al nombre canónico.
Verificado en local con docker compose contra R2 real: transcript 200 con 103
palabras y ZIP de 6,2 MB con los 4 clips, sobre un proyecto sin ficheros en
disco.
- Plan free resuelto en metering (sin fila Stripe): 20 min/mes para cuentas
Google, período sintético de mes natural con reset automático
- TRIAL_DAYS=0 para nuevos checkouts; trials en curso grandfathered
- Watermark drawtext en clips free (pasada única post-render, sobrevive
subtítulos/hooks); thumbnails IA solo de pago
- Anti-abuso: 3 jobs/día por cuenta, 5 por IP, rate-limit de probes,
contador mensual de GB de proxy con alerta Telegram a 100 GB
- Clips free caducan a 7 días (purge_free_expired); purge_expired respeta
a cancelados que ahora son free
- Galería UGC pública pasa a opt-in (share_to_gallery, antes publicaba
producto+guion de todos los usuarios sin permiso)
- Emails: clips listos (con star-ask) y sin-minutos (cooldown 24h)
- Frontend: card Free en pricing, copy sin trial (landing/legal/gates),
StarBanner en resultados y TopUpModal, upsell de watermark
- New projects table (job_id, metadata_r2_key, state JSONB) — created via create_all
- archive_job also uploads the metadata JSON (transcript) and upserts the
Project row + user_videos (no more duplicate rows on re-archive)
- archive_clip_edit re-archives a clip after each server-side edit, keeping
only the pristine original + current version per clip in R2
- fix /api/edit: persist new video_url in job result + metadata.json (the
other edit endpoints already did)
- POST /api/projects/{job_id}/restore re-hydrates R2 files into output/{job_id}
(per-job lock, temp-dir download, .owner sidecar, idempotent fast path)
- GET /api/projects + PUT /api/projects/{job_id}/state (debounced Remotion
layer sync from the frontend)
- History tab groups clips by project with a reopen button; App restores
jobId/results/project state; ResultCard seeds serverVideoFile/activeLayers
from the restored state and reports changes upward
- log_view.py: whitelist-based cloud log view — transcription percentage,
clip counters, errors; no file paths, model names or pipeline internals.
Self-host (BILLING off) and DEBUG_LOGS keep the full raw output.
- transcribe_backends: emit '🎙️ Transcribing… NN% (Xs)' at 25% steps from
both parakeet and whisper paths.
- dashboard: profile selector shows connected networks instead of the
auto-generated os_<hash> id.