Agentic Coding for Multimodal Content Generation SaaS: A Hands-On Long-Horizon Task Development Test

    This article examines the shift in AI coding evaluation from short-range code completion to agentic, long-horizon, and system-level engineering capabilities. Using a practical SaaS platform that turns product images and selling-point copy into vertical e-commerce short videos, it walks through the full development process: research, specification-driven development, architecture, implementation, troubleshooting, and acceptance testing. It covers asynchronous task orchestration, multi-tenant row-level security, credit-based billing, authentication, object storage delivery, observability, and common long-horizon failure modes such as context drift, over-design, environment drift, duplicate submissions, and zombie tasks. The article concludes that long-horizon AI coding succeeds when the specification keeps the objective stable, architecture precedes implementation, human owners define constraints and acceptance criteria, and managed cloud capabilities reduce operational overhead.

    Introduction: The focus of AI coding competition is shifting from “writing fast” to “thinking comprehensively”

    Historically, AI coding tools have been judged mainly by metrics such as “accurate completion” and “fast single-file generation.” These metrics measure performance in short-horizon tasks: given a function signature, an error message, or a component style, the model can produce usable code within a few hundred lines of context.

    However, production systems are rarely made of a single piece of code. A product that can be deployed commercially typically spans at least six layers: authentication, billing, task orchestration, data storage, external delivery, and security compliance. A design mistake in any one of these layers can be enough to make the system fail in production.

    As a result, the focus of evaluation is shifting:

    • Agentic capability: Can the agent autonomously call tools such as retrieval, execution, and testing, and advance work through an observe-decide-act loop instead of passively waiting for the next instruction?
    • Long-horizon task capability: When a task lasts for tens of minutes or even hours and crosses dozens of tool calls, can the agent maintain context coherence, avoid forgetting early constraints, and avoid overturning earlier design decisions in later stages?
    • Systems engineering capability: When facing an open-ended problem such as “design a commercial platform that is multi-tenant, asynchronous, and billable,” can the agent first make architectural decisions and then implement code, rather than immediately piling up functions?

    To test these capabilities, this article presents a moderately difficult practical sample: using long-horizon agentic coding to build, from scratch in several hours, a SaaS platform for “turning product images into shoppable short videos.” There are three reasons for choosing this sample:

    1. Complete chain: A minimum viable version can cover the major requirements of a commercial SaaS platform.
    2. Clear asynchronous characteristics: Video rendering is time-consuming, imposing hard requirements on task queues, state management, and progress feedback.
    3. Clear business logic: User roles, resource ownership, and billing rules can all be stated explicitly, making it suitable for testing “requirement consistency” in long-horizon tasks.

    This article reconstructs the selection logic, development methodology, architecture design, common pitfalls, and pre-launch acceptance process so that readers can assess how reusable the approach may be for their own teams.

    1. Selection logic: Sellers do not want a workflow; they want a video

    The choice of this domain comes from a product judgment that is often overlooked by engineers.

    Many technical enthusiasts prefer to build highly automated content production pipelines. They chain scriptwriting, asset composition, voice-over, background music, and other steps into a visual workflow and then share that workflow with business users. In practice, however, cross-border sellers often care about something entirely different: return on investment, or ROI. Their concerns usually reduce to three questions:

    • Unit cost: Is the cost of producing one video a few cents or a few dollars?
    • Throughput: Can the system reliably produce thousands of videos per day?
    • Onboarding barrier: Can users open a web page and produce a video with just a few clicks, without any configuration?

    For most small and medium-sized sellers, “learning a workflow” is itself an investment that requires time and trial-and-error. A tool that requires users to understand nodes, parameters, and branch logic may be highly flexible, but its usage barrier is still too high. What sellers really need is a standardized product that is “ready to use.”

    This leads to two general product principles:

    1. Deliver the result, not the method. Complex orchestration should be encapsulated inside the product. Users only need to provide product images and selling-point copy.
    2. Define success by unit output cost and daily production capacity. The technical architecture should be built around “low cost, high concurrency, and elastic scaling,” not around the number of features.

    Based on this, the minimum viable product form defined in this article is as follows:

    Dimension Design choice Reason
    Input Product images + selling-point copy Lower the usage barrier and reduce manual configuration
    Processing Script generation → image composition and transitions → voice-over and subtitles → background music → rendering and export Split stages to make retries and progress feedback easier
    Output Vertical short video + preview link Directly addresses mainstream short-video delivery scenarios
    Business model Credit pre-deduction, with automatic refund on failure Costs are measurable and risks are controllable

    It is important to note that the technical complexity of this product is not low:

    • Backend: Use an asynchronous web framework to build APIs, including request validation, error handling, and API documentation.
    • Data: Design core tables for users, tenants, assets, tasks, and credit transactions, and implement row-level isolation.
    • Scheduling: Video rendering usually takes tens of seconds to several minutes, so it must be asynchronous and support horizontal scaling across multiple instances.
    • Billing: Support mobile phone verification-code login, stateless token authentication, credit pre-deduction, and refunds.
    • Delivery: Store finished files in object storage, distribute them through time-limited access links, and configure lifecycle policies to control cost.

    Evaluated using traditional methods, this would require at least one backend engineer, one frontend engineer, and one tester collaborating for several weeks. The next question is: Can long-horizon agentic coding compress this cycle to several hours and still deliver a runnable result?

    2. Development method: Spec-driven development and a research-architecture-implementation workflow

    2.1 Why specifications must come first

    The biggest risk in long-horizon tasks is goal drift: as context continues to grow, the model gradually forgets the original constraints, later implementations may overturn earlier design decisions, or the model may add irrelevant functionality just to make the output “look complete.”

    An effective countermeasure is spec-driven development (SDD): before writing code, produce a version-controlled and reviewable specification document. All subsequent implementation is based on this document, which serves three roles at once:

    • Context anchor: Reload the specification at the beginning of each stage to reduce the probability of forgetting constraints.
    • Acceptance basis: Each requirement maps to a clear completion criterion.
    • Change baseline: When requirements change, update the specification first and then modify the code, preventing implementation from drifting away from intent.

    2.2 Breakdown of the three-stage workflow

    The task was explicitly required to follow the sequence “research → architecture → implementation.” Each stage had to produce documentation and wait for confirmation before entering the next stage.

    Stage 1: Research

    • Clarify the objective: Describe product positioning, target users, core scenarios, and business model.
    • Define boundaries: Explicitly list “non-goals,” such as no team collaboration, no multilingual support, and no custom templates in the first version.
    • Lock technical constraints: Runtime versions, database type, deployment model, and dependency management.
    • Form an acceptance checklist: Convert requirements into checkable items.

    Stage 2: Architecture

    • Module division: Split service boundaries by responsibilities such as authentication, assets, tasks, billing, and rendering.
    • Data model: Design core entities, field constraints, indexes, and foreign key relationships.
    • Interface contracts: Fix routes, request/response structures, error codes, and pagination conventions.
    • Non-functional design: Authentication scheme, multi-tenant isolation, rate-limiting policy, idempotency mechanism, state machine, and logging standards.
    • Directory structure: Define layering in advance to avoid disordered code expansion later.

    Stage 3: Implementation

    • Skeleton first, then fill in: Complete scaffolding, data access layer, business service layer, API layer, and frontend pages in order.
    • Close the loop within each module: After finishing a module, run self-checks before moving to the next module.
    • Keep aligning with the specification: When ambiguity appears, go back to the specification instead of improvising.

    The following is an example specification skeleton that can be used directly in long-horizon tasks:

    1. # Project specification: Short-video generation SaaS (excerpt)
    2. ## 1. Product objective
    3. Users upload product images and selling-point copy and generate vertical shoppable short videos with one click.
    4. Success criteria: average processing time per video < 2 minutes; support at least 50 concurrent tasks.
    5. ## 2. User roles
    6. - Anonymous visitor: can only browse sample works;
    7. - Registered user: receives trial credits after login and can submit tasks and view historical works;
    8. - Platform administrator: manages credits and views global task metrics (only minimal capabilities in the first version).
    9. ## 3. Non-goals (not included in this release)
    10. - Multi-user collaboration and team spaces;
    11. - Custom video templates;
    12. - Multilingual voice-over.
    13. ## 4. Data model
    14. user / tenant / asset / render_task / credit_ledger (see architecture document for details)
    15. ## 5. Task state machine
    16. queued → processing → succeeded | failed; processing timeout → expired
    17. ## 6. Interface conventions
    18. - Unified response structure: { code, message, data }
    19. - Error code ranges: 1xxxx authentication / 2xxxx parameters / 3xxxx business / 5xxxx internal
    20. ## 7. Security and compliance
    21. - Multi-tenant row-level isolation; API rate limiting; uploaded file type and size validation;
    22. - Asset deletion mechanism; token expiration and refresh policy.
    23. ## 8. Completion criteria
    24. - Core end-to-end flow is runnable: registration → upload → submission → polling → download;
    25. - Concurrency, duplicate submission, and timeout scenarios have test coverage;
    26. - API documentation and initialization data scripts are generated automatically.

    2.3 Context management techniques for long-horizon tasks

    In practice, the most effective approach is to “externalize” critical constraints into files:

    • Store the specification, architecture, and interface contracts as separate files, and reload them at the beginning of each stage instead of relying on the model to “remember” them.
    • Maintain a project status memo that records completed modules, pending items, and known risks, and update it before each advancement.
    • Submit change requests in a centralized manner to avoid scattered modifications that cause design forks.
    • After completing key modules, immediately run tests and static checks to expose problems early rather than discovering rework issues during integration.

    3. Architecture design: Six key points that determine whether the system is commercially viable

    Once the specification is fixed, architecture design directly determines whether the system can handle real traffic. The following six areas deserve the most attention.

    3.1 Application layering and configuration management

    Adopt a classic three-layer structure: API layer, service layer, and data access layer.

    • API layer: Only responsible for parameter validation, authentication, and response encapsulation; no business logic.
    • Service layer: Holds core business rules and transaction boundaries.
    • Data access layer: Uniformly wraps queries and ensures that all tenant-related queries go through the same entry point.

    All configuration is injected through environment variables. Database connection strings, object storage credentials, and third-party service keys must never be hard-coded or committed to version control. Dependency versions should be fixed with lock files to avoid environment drift where code runs locally but fails after deployment.

    3.2 Data model: Multi-tenancy and row-level security (RLS)

    There are two common approaches to multi-tenant design: shared tables with a tenant field, and separate databases or schemas. The former has lower cost and simpler operations but requires strict row-level isolation. The latter provides stronger isolation but makes migration and connection management more complex. In the early stage, the shared-table approach is recommended, with strict constraints enforced at the database level.

    Taking native row-level security in a relational database as an example:

    1. -- Core business tables uniformly carry a tenant field and use composite indexes.
    2. CREATE TABLE render_task (
    3. id uuid PRIMARY KEY,
    4. tenant_id uuid NOT NULL,
    5. user_id uuid NOT NULL,
    6. status text NOT NULL DEFAULT 'queued',
    7. stage text,
    8. progress smallint NOT NULL DEFAULT 0,
    9. error_code text,
    10. output_key text,
    11. created_at timestamptz NOT NULL DEFAULT now(),
    12. updated_at timestamptz NOT NULL DEFAULT now()
    13. );
    14. CREATE INDEX idx_render_task_queue ON render_task (status, created_at);
    15. CREATE INDEX idx_render_task_owner ON render_task (tenant_id, user_id, created_at DESC);
    16. -- Enable row-level security.
    17. ALTER TABLE render_task ENABLE ROW LEVEL SECURITY;
    18. -- Tenant isolation policy: only rows belonging to the tenant set for the current session are visible.
    19. CREATE POLICY tenant_isolation ON render_task
    20. USING (tenant_id = current_setting('app.tenant_id', true)::uuid);
    21. -- Credit ledger: unique idempotency key + append-only accounting.
    22. CREATE TABLE credit_ledger (
    23. id uuid PRIMARY KEY,
    24. tenant_id uuid NOT NULL,
    25. user_id uuid NOT NULL,
    26. task_id uuid,
    27. delta integer NOT NULL, -- Positive for credit in, negative for consumption.
    28. reason text NOT NULL,
    29. idem_key text NOT NULL, -- Idempotency key generated by the client.
    30. created_at timestamptz NOT NULL DEFAULT now()
    31. );
    32. CREATE UNIQUE INDEX uq_credit_idem ON credit_ledger (tenant_id, idem_key);
    33. CREATE INDEX idx_credit_user ON credit_ledger (tenant_id, user_id, created_at DESC);

    In engineering practice, four details must be handled carefully:

    1. Table owner bypass: By default, the table owner is not subject to policies. Use the force row-level security option to ensure the owner is also constrained by policies.
    2. Session variable binding: The tenant identifier must be injected within the same transaction through a local setting. It expires automatically when the transaction ends, avoiding data leakage caused by connection pool reuse.
    3. Prevent policy failure: If the current tenant identifier is missing, queries should return empty results rather than the full table, following a “default deny” principle.
    4. Background task exceptions: Cross-tenant jobs such as queue consumers and reconciliation scripts should use dedicated database roles, be explicitly declared as controlled exceptions, and be recorded in audit logs.

    At the same time, credits use append-only accounting rather than directly modifying a balance field. The balance is derived from the ledger, and every deduction has a unique idempotency key. This naturally deduplicates repeated requests and allows failed operations to be reversed through compensating ledger entries.

    3.3 Task orchestration: asynchronous queues, state machines, and result reporting

    Video rendering is a typical task that is long-running, failure-prone, and retryable. It cannot be handled synchronously inside an HTTP request. The standard approach is: the request only creates a task and returns a task identifier; a background consumer performs the work; the frontend polls or subscribes to progress.

    Define the state machine clearly: queued → processing → succeeded | failed. Tasks that time out while processing should become expired to avoid zombie tasks occupying the queue for a long time. Every state transition must record a timestamp and reason.

    Safe multi-instance claim: Use database row locks to atomically claim a task. This ensures that a long-running task is acquired by only one execution instance without relying on an additional message broker:

    1. -- Atomic claim: skip locked rows to avoid duplicate consumption by multiple instances.
    2. UPDATE render_task
    3. SET status = 'processing', updated_at = now()
    4. WHERE id = (
    5. SELECT id FROM render_task
    6. WHERE status = 'queued'
    7. ORDER BY created_at
    8. FOR UPDATE SKIP LOCKED
    9. LIMIT 1
    10. )
    11. RETURNING id, tenant_id, user_id;

    When concurrency increases and individual tasks take longer, a mature distributed task framework can be introduced, or a managed cloud message queue service can be used directly. These services provide retry, dead-letter handling, delayed delivery, and observability capabilities, significantly reducing the complexity of building scheduling in-house.

    Idempotency and safety during processing:

    • Idempotency key: When creating a task, require the client to send a unique request identifier. Enforce a unique constraint at the database layer based on “user + idempotency key” to prevent duplicate charges caused by network retries.
    • Progress feedback: Update progress percentages at each stage (script → composition → voice-over → rendering). The frontend polls a lightweight endpoint at fixed intervals. For higher real-time requirements, server-side push can be used instead.
    • Failure compensation: When rendering fails, decide whether to retry based on the stage. After the retry limit is exhausted, automatically reverse credits and mark the failure reason.

    3.4 Authentication and billing: from mobile phone to credits

    • Login: Mobile phone number + SMS verification code is the most natural login method for the target users. The server must implement code expiration control, attempt limits, and sending frequency limits by phone number/IP to prevent abuse of SMS resources.
    • Token: After successful login, issue a short-lived access token and a long-lived refresh token. The access token uses a stateless signature mechanism; the server only verifies the signature and expiration without querying the database. Refresh tokens can be stored and support active revocation.
    • Authorization: Roles distinguish anonymous users, registered users, and administrators. Resource ownership checks are uniformly completed in the service layer, forming a “double insurance” with database row-level security.
    • Billing: When a task is submitted, validate and pre-deduct credits, settle on success, and reverse credits on failure. Daily submission limits and credit balance constraints are both enforced to prevent uncontrolled costs.

    The following example demonstrates a “pre-deduction + transaction” approach (illustrative code, not tied to a specific framework API):

    1. # 1) Validate the login state and resolve tenant_id and user_id.
    2. principal = require_auth(request)
    3. # 2) Idempotency key: generated by the client and sent with the request to prevent duplicate charges.
    4. idem_key = request.headers.get("Idempotency-Key")
    5. # 3) Start a transaction: bind tenant context within the same transaction and pre-deduct credits.
    6. with unit_of_work(tenant_id=principal.tenant_id) as uow:
    7. charge_result = credit_service.hold(
    8. user_id=principal.user_id,
    9. amount=TASK_COST,
    10. idem_key=idem_key, # Unique index as a fallback; duplicate requests return the existing result.
    11. reason="render_task",
    12. )
    13. if not charge_result.ok:
    14. raise BusinessError(charge_result.code, charge_result.message)
    15. task = task_service.enqueue(
    16. tenant_id=principal.tenant_id,
    17. user_id=principal.user_id,
    18. image_keys=request.image_keys,
    19. script=request.script,
    20. )
    21. credit_service.bind_task(charge_result.ledger_id, task.id)
    22. return {"task_id": task.id, "status": task.status, "credits_left": charge_result.balance}

    3.5 Storage, delivery, and content safety

    • Upload: Product images are uploaded directly to object storage. The server issues time-limited upload credentials to avoid routing large files through the application layer.
    • Validation: The server validates file type and size again; do not rely only on frontend restrictions.
    • Access: Finished files are stored in a private object storage bucket and distributed through signed links with expiration times. Expired links must be re-requested.
    • Cleanup: Configure lifecycle rules to automatically archive or delete intermediate artifacts beyond their retention period, controlling storage costs.
    • Content compliance: Before images and videos go live, integrate content safety review, filter prohibited words in copy, and terminate tasks immediately if review fails while refunding credits.
    • Supply chain safety: Dependencies such as video encoding and audio processing must have locked versions to prevent incompatible upstream updates.

    3.6 Observability and rate limiting

    • Logging: Use unified structured logs, assign a correlation identifier to each request, and generate a task identifier when the task is created. This identifier should run through the entire chain: upload, queueing, rendering, and callback.
    • Metrics: At minimum, cover task success rate, average processing time, queue backlog, credit consumption, and failure reason distribution.
    • Alerting: Trigger alerts when queue backlog exceeds a threshold, failure rates spike, or the rendering service timeout ratio rises.
    • Rate limiting: Apply frequency limits to write endpoints such as task creation and form submission to prevent a single user from occupying all rendering resources.

    4. Pitfalls: six common problems in long-horizon tasks

    4.1 Context decay: forgetting early constraints in later stages

    Symptom: During frontend page development, the field names and error structures produced by the model are inconsistent with the specification document. Security requirements, such as upload validation, are simplified or even omitted.

    Cause: Early information occupies a smaller proportion of the context window, and attention is diluted by large amounts of code detail.

    Countermeasure: Split the specification into independent files and reload them at the beginning of each stage. List unfinished hard constraints in the project status memo, and require a comparison check against the specification whenever a change is submitted.

    4.2 Over-design: automatically expanding feature scope

    Symptom: The model spontaneously adds capabilities explicitly excluded by the specification, such as permission systems, operation audits, and multilingual support. This lengthens delivery time and increases code complexity.

    Cause: Models tend to propose “more complete” solutions, but “complete” is not equivalent to “this release’s objective.”

    Countermeasure: Explicitly list non-goals in the specification and require a change request before adding new features. During review, check only against the specification without subjective expansion.

    4.3 Environment drift: dependency version mismatch

    Symptom: Generated code uses newer syntax or framework interfaces, while the actual runtime version is lower, causing errors at startup.

    Countermeasure: Lock runtime and dependency versions during the specification stage and explicitly check versions in validation scripts. Lock all dependencies with lock files.

    4.4 Row-level security appears to fail during testing

    Symptom: Tenant isolation seems to work during local debugging, but integration testing finds that data belonging to other tenants can be read.

    Cause: There are three common root causes: the test connection belongs to the table owner and policies are not enforced; the tenant identifier is set outside the transaction; connection pool reuse leaves stale session variables from previous requests.

    Countermeasure: Uniformly encapsulate a “request-level tenant context,” inject it at transaction entry, and clear it when the transaction ends. Write dedicated tests for isolation rather than verifying it only incidentally in functional tests.

    4.5 Duplicate submission and duplicate charges

    Symptom: A user retries submission because of network jitter, resulting in two videos being generated and credits being charged twice.

    Countermeasure: The client sends an idempotency key, and the server uses a unique index as a fallback. For requests with an existing idempotency key, directly return the first result instead of returning an error or executing the task again.

    4.6 Task timeouts and “zombie tasks”

    Symptom: The rendering service exits abnormally, the task remains in the processing state, the queue becomes full, and the user sees a progress bar that does not move for a long time.

    Countermeasures:

    1. Set a heartbeat timestamp for tasks in processing. If they exceed a threshold without completing, recycle them into a retryable state.
    2. Set a maximum retry count. After the limit is exceeded, mark the task as failed and reverse credits.
    3. Add a fallback patrol job that periodically scans timed-out tasks and triggers a compensation process.

    5. Pre-launch acceptance checklist

    The output of long-horizon tasks must undergo final human review. The following checklist can be used directly before merging:

    Functional layer

    • The core end-to-end flow works: registration → login → upload → submission → polling → download;
    • Key interfaces have both success and failure test cases, and error codes match the documentation;
    • API documentation is generated and published automatically, so the frontend does not need verbal alignment on fields.

    Data and concurrency layer

    • Tenant isolation has dedicated tests: cross-tenant read, update, and delete operations return empty results or are rejected;
    • Concurrent task claiming does not produce duplicates: under load testing, only one instance enters the processing state for the same task;
    • Repeated idempotency keys do not cause secondary charges.

    Security and compliance layer

    • Uploaded files undergo triple validation: type, size, and content;
    • SMS verification code sending is rate-limited, and token expiration and refresh logic work correctly;
    • When content review fails, the task terminates correctly and credits are refunded;
    • Keys and credentials are all injected through environment variables, and no sensitive information is stored in version control.

    Operations layer

    • Structured logs contain correlation identifiers and can trace a task end to end;
    • Queue backlog, failure rate, and average processing time are observable and have alerts;
    • Storage lifecycle rules and scheduled cleanup jobs are enabled;
    • Deployment scripts can rebuild the environment with one command, and initialization data scripts can be executed repeatedly.

    6. Conclusions: what long-horizon capability really means

    After completing this practice, four judgments stand out:

    First, the core of long-horizon tasks is not “writing more,” but “not drifting off course.” During several hours of continuous work, the model must maintain a stable view of the objective: what belongs to the current release, what is explicitly excluded, and which constraints cannot be compromised. The reason specification documents work is that they externalize this view from volatile context into retrievable and persistent assets.

    Second, system-level tasks must follow “architecture first, coding later.” Directly asking the model to “write a video generation website” often produces a prototype that can be demonstrated but cannot go live. Designing the data model, state machine, interface contracts, and security policies first, then implementing module by module, produces a system that is maintainable and extensible.

    Third, humans remain responsible for quality. Models can handle most of the coding work, but boundary definition, acceptance criteria, security baselines, and cost constraints must be defined and reviewed by humans. Writing the acceptance checklist into the specification is the step with the highest return on investment in long-horizon tasks.

    Fourth, general-purpose cloud capabilities can significantly dilute long-tail costs. Managed capabilities such as object storage, message queues, content safety, logging, and monitoring alerts can be used on demand without building an operations team in-house. They allow teams to focus on business differentiation rather than repeatedly building infrastructure.

    The standard for measuring AI coding is changing: from “writing a piece of code” to “delivering a system.” When a model can steadily advance a multi-module project for several hours, the core value of developers also shifts: from writing implementations to defining problems, designing constraints, and controlling quality. Those who make this role transition earlier can turn this capability into real product competitiveness earlier.