Long-Horizon AI Agent Coding: Building a Video Generation SaaS in Three Hours
This article examines why long-horizon tasks—engineering work that spans hours and dozens of files—are the real dividing line for AI coding tools, based on a hands-on attempt to build a commercial video generation SaaS in about three hours. It covers the system architecture: a React App Router frontend with auth guards and resumable uploads, a Python async backend, a three-table relational schema with row-level security, an async queue-based task layer with idempotency keys, and a credit-based billing model. It also describes what the long-horizon agent actually did across requirements formalization, skeleton-first generation, self-verification, and failure recovery, along with its real limitations, and closes with reusable engineering lessons on locking down contracts early, staying runnable in small steps, building in observability, and calculating unit cost upfront.
1. Why Long-Horizon Tasks Are the Real Dividing Line for AI Coding
For the past two years, most evaluations of AI coding tools have stayed at the level of “complete a function” or “generate a page.” These tasks have short context, fast feedback, and high fault tolerance—if something is wrong, you fix a line and move on. But the complexity of real commercial software does not live in any single function. It lives in consistency across modules and across time: interface contracts must not drift, data models must not be repeatedly overturned, and async pipelines must not lose their way midway.
A long-horizon task is exactly this kind of engineering activity: work that continues for tens of minutes or even hours and spans dozens of files. It places three hard requirements on the model:
- Context coherence: architectural decisions made early are still respected dozens of steps later;
- Autonomous decomposition: the ability to break a vague goal like “build a commercial platform” into a verifiable sequence of subtasks;
- Systems perspective: not piling on features, but first thinking through boundaries, failure paths, and data flow.
These three points are precisely what separate a “demo generator” from an engineering collaborator.
2. Framing the Problem: From Teaching Methods to Delivering Results
Many technical write-ups default to outputting workflows, scripts, and configuration templates and leaving readers to assemble them. But what real business teams—especially cross-border e-commerce and content marketing teams—care about usually comes down to three things: the cost per video, how many can be produced in a day, and whether there is a one-click entry point that produces a finished clip.
This leads to an important product judgment: in the AI era, delivering a runnable result is more valuable than delivering a reusable method. So the goal of this exercise was defined as follows: a user uploads several product images, the system automatically produces short video assets ready for distribution, and the entire flow from sign-up to download is completed in the browser.
3. System Architecture: A Minimal Complete Set for Commercial Use
To be “commercially usable,” several layers have to be stood up at once. A gap in any one of them will surface under real traffic.
3.1 Frontend
The frontend uses a mainstream React server-rendering framework (a modern web framework with the App Router pattern). The focus is not on whether pages look good, but on:
- Routing and auth guards: unauthenticated users cannot reach the generation page;
- Upload experience: chunked large-file uploads, resumable transfers, retry on failure;
- Task state visualization: polling or streamed progress updates.
3.2 Backend
A Python async web framework exposes RESTful endpoints with clear responsibility boundaries:
- User and authentication service;
- Asset and project management;
- Generation task orchestration;
- Billing and credit ledger.
3.3 Data Layer
A relational database needs only three core tables to cover the main path:
-- Keep users and the credit ledger separate to avoid concurrent deduction overwritescreate table users (id uuid primary key,phone varchar(20) unique,created_at timestamptz default now());create table projects (id uuid primary key,user_id uuid references users(id),assets jsonb, -- images and script parametersstatus varchar(16), -- queued/running/succeeded/failedcreated_at timestamptz default now());create table credit_ledger (id bigserial primary key,user_id uuid references users(id),delta int, -- positive for top-up, negative for consumptionref_id uuid, -- references a project or ordercreated_at timestamptz default now());
Row-level security (RLS) is not optional here: every query must carry a user_id condition, enforced at the database layer, to prevent unauthorized reads of another user’s assets.
3.4 Async Task Layer
Video composition typically takes minutes and must never block an HTTP request. The standard approach: the endpoint only writes a task record and publishes a message to a queue; a separate worker process consumes and executes it; the frontend obtains status via polling or a long-lived connection. This layer must include an idempotency key and timeout reclamation, otherwise retries will cause duplicate charges.
Illustrative task submission logic:
@app.post("/projects")async def create_project(req: ProjectIn, user=Depends(auth)):async with pool.acquire() as conn:await conn.execute("insert into credit_ledger(user_id, delta, ref_id) values($1,-1,$2)",user.id, req.client_token) # client_token guarantees idempotencypid = await conn.fetchval("insert into projects(user_id, assets) values($1,$2) returning id",user.id, json.dumps(req.assets))await queue.publish({"project_id": str(pid)})return {"id": str(pid), "status": "queued"}
3.5 Billing and Risk Control
A credit system suits the early stage better than direct payment: top-ups create prepaid balance, consumption is deducted per clip, and the ledger table keeps everything traceable. Combined with a daily quota and anomalous-call detection, this keeps costs from spiraling.
4. What the Long-Horizon Agent Actually Did
The genuinely surprising part was not the speed of code output but the stability of its decisions. The whole process breaks down into four phases:
- Requirements formalization: translating “build a video generation website” into a module list, an endpoint list, and a table list;
- Skeleton first: generating the directory structure, dependency declarations, and environment configuration before filling in each layer;
- Self-verification: after finishing each layer, re-reading earlier agreements to check whether interface signatures and field naming have drifted;
- Failure recovery: on dependency conflicts or failed migrations, rolling back to the last runnable state instead of blindly retrying.
To be objective, long-horizon automation is not free of cost: when output volume is large, a human still needs to do an architecture review; the parts that call third-party models still require you to supply your own keys and quota; and for strongly regulated areas such as security, compliance, and payments, human confirmation cannot be skipped. Treating it as a tireless junior architect plus executor is closer to reality than treating it as a fully autonomous expert.
5. Reusable Engineering Lessons
- Lock down the contracts first: finalize interfaces and table structures before letting the tool implement in bulk; the rework rate drops noticeably;
- Stay runnable in small steps: keep the project in a bootable state every 15 minutes so you can localize which layer a problem is in;
- Build observability in: structured logs, task trace IDs, and failure reasons persisted to the database are the lifeline of a long-chain system;
- Put cost awareness first: for any generation business, calculate the per-clip cost and concurrency ceiling before discussing features.
6. Closing Thoughts
This exercise shows that the competitive focus in AI coding is shifting from single-point generation quality to long-horizon engineering reliability. For developers, the real barrier is no longer whether something can be written, but whether requirements can be described clearly and whether boundaries and failure paths can be fully defined. When machines can take on large amounts of mechanical implementation work, architectural judgment and business understanding become the scarcest capabilities of all.
