Long-Horizon AI Agent Coding Tested: Building a Video SaaS in Three Hours
This article reports a hands-on test of long-horizon AI agent coding, using the construction of a short-video generation SaaS platform as the experiment. Following a Spec-Driven Development (SDD) workflow of research, architecture, and development, it explains how to organize prompts into three layers of constraints, how a production-grade architecture handles six concerns from SSR frontend and REST backend to data models, row-level security, async scheduling, billing, and observability, and what breaks in practice. It closes with lessons on contract drift, duplicate task execution, sparse build feedback, and compute variability, plus recommendations for teams adopting long-horizon agents.
1. Why Long-Horizon Tasks Are the Dividing Line for AI Coding
Over the past two years, most demos of AI coding tools have stayed at the granularity of “generate a page” or “complete a function.” These tasks have short context and fast feedback, so a model with decent local code completion can already look impressive. Building a real commercial system is a fundamentally different problem: it is an engineering effort constrained by requirements, data models, API contracts, asynchronous flows, permission systems, and billing rules.
A new coding paradigm has recently emerged around agent capability, long-horizon tasks, and systems engineering. The key difference is that the model no longer just answers “how should I write this code.” Instead, it can decompose tasks autonomously around a system-level goal, maintain long-context consistency, and keep the architecture from drifting over hours of continuous execution. This article uses “build a SaaS platform that automatically generates short videos” as the experimental vehicle and applies Spec-Driven Development (SDD), enforcing a workflow of research → architecture → development, to observe how a long-horizon agent performs under real engineering constraints.
The practical motivation for this topic is clear. Content generation models are improving quickly, and cross-border e-commerce sellers and content operators have strong demand for producing marketing short videos in bulk. What they care about is not how to assemble a workflow, but ROI: cost per video, how many videos can be produced per day, and whether dedicated staff are needed for maintenance. The product goal was therefore defined as: users upload product images and basic information, and the platform automatically generates ready-to-run short videos, packaging “capability” directly as “results.”
2. Spec-Driven Development: Turning “Writing Code” into “Writing Constraints”
The most common cause of long-horizon task failure is not that the model cannot write code, but that there is no verifiable spec. In practice, I recommend organizing prompts into three layers of constraints.
The first layer is goals and boundaries. State clearly that this is a commercial SaaS, not a demo, list the capabilities that must be delivered, and declare what will not be done (for example, do not build a video generation model in-house; only integrate with general-purpose generation APIs).
The second layer is process and deliverables. Require the agent to produce documents before code at each stage:
Stage 1 Research: competitor capability matrix, user roles, core flow, risk listStage 2 Architecture: system layering diagram, data model, API contract, task state machineStage 3 Development: commit by module, each with unit/integration tests and run instructions
The third layer is acceptance criteria. Define “done” as measurable conditions, for example: a new user can submit a video generation task within 3 minutes; a failed task can be retried without deducting credits twice; all user data access is validated by row-level security policies.
This approach pushes the model’s output from “looks correct” to “verifiable,” which is the prerequisite for a long-horizon task to run for hours without drifting.
3. Architecture Design: Six Concerns of a Commercial-Grade Platform
In the architecture stage, the agent must handle six concerns at once; any oversight will be amplified into an incident after launch.
The frontend uses the App Router mode of a mainstream React server-side rendering framework, with route groups separating marketing pages from the post-login console. Server components read the session and credit balance, while client components handle only interaction and polling for status display.
The backend uses a lightweight asynchronous framework to expose REST APIs, split into three layers of resource, service, and repository to avoid piling business logic inside route handlers. The API contract comes first, described with OpenAPI, and the frontend generates type definitions from it.
The data layer uses a relational database. Core tables include users, assets, tasks, video outputs, and credit transactions. The task table must implement a state machine:
-- Task state machine exampleCREATE TABLE gen_task (id BIGSERIAL PRIMARY KEY,user_id BIGINT NOT NULL,status TEXT NOT NULL DEFAULT 'queued',cost_credit INT NOT NULL DEFAULT 0,idempotency_key TEXT UNIQUE,created_at TIMESTAMPTZ DEFAULT now());
The idempotency key prevents duplicate charges caused by duplicate submissions, which is the easiest pit to fall into in billing systems.
Permission and multi-tenant isolation use row-level security, pushing isolation down to the database layer instead of relying on the application layer to assemble where clauses:
ALTER TABLE gen_task ENABLE ROW LEVEL SECURITY;CREATE POLICY task_owner ON gen_taskUSING (user_id = current_setting('app.user_id')::BIGINT);
Asynchronous scheduling is the fourth concern. Video generation usually takes minutes and must never block the request synchronously. The approach is to return a task ID immediately after submission, have worker processes consume from a message queue, and let the frontend get progress via polling or a long-lived connection. The queue needs a retry limit and dead-letter handling to avoid poison messages repeatedly consuming compute.
The fifth concern is authentication and billing. Captcha login exchanges for a short-lived access token and a renewable refresh token. Credit deduction and task creation happen in the same database transaction and roll back on failure, guaranteeing “no generation, no charge.”
The sixth concern is observability. Logging, metrics, and alerting are general cloud capability categories. It is advisable to build dashboards for task success rate, queue time, cost per video, and failure reason distribution; the operational cost of long-horizon systems mainly comes from here.
4. Test Run and Post-Mortem
A full long-horizon run took about three hours, of which less than half was actually spent generating code; the rest went to dependency installation, build validation, and failure retries. A few typical pitfalls are worth recording.
The first is contract drift caused by context compression. API fields defined early in a long task were rewritten later. The solution is to persist the API contract and data model as separate files and require the model to re-read them at each stage instead of relying on memory.
The second is duplicate execution of asynchronous tasks. A worker process was re-queued after a timeout, causing the same task to generate twice and deduct credits twice. This was ultimately solved with an idempotency key and a conditional state machine update:
UPDATE gen_task SET status = 'running'WHERE id = :id AND status = 'queued';
If the number of affected rows is 0, it means another process has already claimed the task, so skip it directly.
The third is sparse feedback from long builds. In a multi-hour task, validating only at the end lets errors accumulate. In practice, require type checking and tests after each module is completed, cutting a long task into a series of short feedback loops.
The fourth is compute supply fluctuation. Queues lengthen noticeably during peak hours, which indicates that the architecture must treat “model invocation” as an unstable external dependency, using queues for peak shaving, timeout circuit breaking, and fallback messaging to keep the experience under control.
5. Capability Boundaries and Adoption Recommendations
Long-horizon agents do push AI coding into a new stage: they can take on architecture drafts, boilerplate code, test completion, and documentation writing, freeing developers to focus on trade-offs and acceptance. But they do not replace engineering judgment. Data consistency, cost models, compliance, and risk control still need to be set by people.
Here are three recommendations for teams about to try this. First, write the spec before the code and quantify acceptance conditions. Second, design external model calls as unreliable dependencies; idempotency, retries, and fallback are all indispensable. Third, split long tasks with short feedback to avoid error accumulation. If you need to handle higher concurrency and stricter isolation, you can combine general capabilities such as the container platform, message queue, object storage, and monitoring and alerting from Baidu AI Cloud to complete deployment and operations, so that the system produced by the long-horizon agent has genuine commercial stability.
