Building an AI Image-Generation App with AI Coding Assistants: Architecture Practices

    Working inside an AI coding assistant to write a function is easy; building a complete application from scratch is not. This article walks through the architecture decisions behind an AI drawing/wallpaper mini program, showing how to move from fragment-level code generation to collaborative architecture building. It covers tech-stack selection, data contracts, cursor-based pagination for masonry feeds, direct-to-object-storage uploads, a four-stage AI creation pipeline, content moderation and cost control, a structured prompt template, and the human skills that matter most once assistants take over the boilerplate.

    1. The Real Dividing Line: From “Fragment Generation” to “Co-building Architecture”

    Early on, when writing features inside a smart coding assistant, the interaction was basically “describe a function → get a snippet → stitch and debug it yourself,” with the model acting as an advanced code-snippet generator. But when the task scales up to “build a complete application from zero,” this mode fails quickly: cross-file dependencies, data-model consistency, and exception-state coverage are not things snippet-level output can solve.

    A collaboration with real engineering value should start, in its first phase, with decisions rather than coding. Take an app like an “AI drawing wallpaper library”: if the model can first produce a complete tech-stack selection and only then start writing code, the rework rate downstream drops significantly. A typical selection result should cover four layers:

    • Frontend form: lightweight native mini program development, with three main bottom tabs (artwork feed, AI creation, personal center); no heavyweight UI framework, to keep bundle size and first-screen wait down.
    • Backend form: an integrated cloud-development model, using cloud database + cloud functions + object storage to cover most of the business, avoiding maintaining a standalone server and ops pipeline for a small project. General-purpose capabilities from platforms like Baidu AI Cloud can usually be combined this way.
    • Model capability layering: a vision-understanding model handles reading and describing images, a text model handles prompt rewriting and optimization, and an image-generation model handles image-to-image and text-to-image. The three responsibilities must stay separate; mixing them into one call makes debugging nearly impossible.
    • Data and operations: define collection partitioning, cloud-function granularity, file upload and compression strategy, and moderation and billing instrumentation.

    This selection output is essentially a technical design document. Its value lies not in “writing code fast” but in turning vague requirements into verifiable boundaries.

    2. Data Layer: Nail Down the Contract Before Implementation

    The biggest variable in generated-code quality is context consistency. If the collection structure is left to the model’s imagination, pages and cloud functions will inevitably fall out of sync. So the first step should be to have the model output the data contract first:

    1. // collections/artworks — main table for artworks/wallpapers
    2. {
    3. "_id": "auto",
    4. "title": "string",
    5. "fileId": "string", // original image in object storage
    6. "thumbFileId": "string", // thumbnail; the list fetches only this one
    7. "width": 1080, "height": 1920,
    8. "ratio": 0.5625, // used for masonry layout, stored redundantly
    9. "categoryId": "string",
    10. "tags": ["string"],
    11. "source": "upload | ai",
    12. "authorId": "string",
    13. "status": "pending | online | offline",
    14. "downloads": 0,
    15. "createdAt": 1735689600000
    16. }
    17. // collections/creations — AI creation records, for traceability and cost accounting
    18. {
    19. "_id": "auto",
    20. "userId": "string",
    21. "refFileId": "string", // reference image
    22. "analysis": { "subject": "", "style": "", "background": "" },
    23. "prompt": "string", // final submitted prompt
    24. "resultFileId": "string",
    25. "modelType": "image-gen",
    26. "latencyMs": 0,
    27. "createdAt": 1735689600000
    28. }

    Two engineering decisions here are easy to overlook. First, separating originals from thumbnails: the list page loads only the small image, otherwise the masonry feed will freeze completely on weak networks. Second, the redundant ratio field: it avoids the frontend being unable to compute a placeholder height before it has the metadata, which would cause scroll jank.

    3. Presentation Layer: Doing the Masonry Layout Correctly

    A masonry (waterfall) layout looks like a UI problem but is actually a pagination-strategy problem. Page-based pagination (page/pageSize) produces duplicates and gaps in image-list scenarios, because concurrent deletes or inserts shift the offset. The correct approach is cursor pagination:

    1. // cloud function getArtworkFeed — cursor pagination + category filter
    2. exports.main = async (event) => {
    3. const { categoryId = 'all', cursor = null, pageSize = 20 } = event;
    4. const db = getDB();
    5. const cmd = db.command;
    6. let query = db.collection('artworks').where({ status: 'online' });
    7. if (categoryId !== 'all') query = query.where({ categoryId });
    8. if (cursor) query = query.where({ _id: cmd.lt(cursor) });
    9. const { data } = await query
    10. .orderBy('_id', 'desc')
    11. .limit(Math.min(pageSize, 50))
    12. .get();
    13. return {
    14. items: data,
    15. nextCursor: data.length === pageSize ? data[data.length - 1]._id : null
    16. };
    17. };

    On the frontend, the model should wrap a reusable lazy-loading component rather than scattering scroll listeners across every page:

    1. // sketch: scroll-to-bottom load + concurrency lock + empty/error states
    2. function useFeed(fetcher) {
    3. const state = { list: [], cursor: null, loading: false, done: false, error: '' };
    4. async function loadMore() {
    5. if (state.loading || state.done) return; // concurrency lock, prevents duplicate requests
    6. state.loading = true; state.error = '';
    7. try {
    8. const { items, nextCursor } = await fetcher({ cursor: state.cursor });
    9. state.list.push(...items);
    10. state.cursor = nextCursor;
    11. state.done = !nextCursor;
    12. } catch (e) {
    13. state.error = 'Failed to load. Tap to retry.';
    14. } finally {
    15. state.loading = false;
    16. }
    17. }
    18. return { state, loadMore };
    19. }

    The key point: the model must write all four states at once — empty, loading, failure-retry, and end-of-list. Generation results that implement only the “request succeeded” branch will almost certainly break on a real device.

    4. Upload Chain: Take Heavy Traffic Off the Cloud Function

    The most common performance and cost trap in image apps is routing file streams through a cloud function. A cloud function has both an execution-time limit and is billed by invocation resource, so using it to carry binary streams is a double waste. The standard approach is direct upload with temporary credentials:

    1. // four upload steps: local compression → request temporary credential → client direct upload to object storage → callback to unlock data
    2. async function uploadArtwork(tempFilePath, meta) {
    3. const compressed = await compressImage(tempFilePath, {
    4. maxWidth: 1600, quality: 80, stripExif: true // stripExif handles both privacy and size
    5. });
    6. const { uploadUrl, fileId } = await callFn('getUploadTicket', {
    7. scene: 'artwork',
    8. contentType: 'image/jpeg',
    9. size: compressed.size
    10. });
    11. await putObject(uploadUrl, compressed); // direct upload, does not pass through the cloud function
    12. const id = await callFn('registerArtwork', { fileId, ...compressedMeta(compressed), ...meta });
    13. return id; // status = pending, awaiting moderation
    14. }

    The supporting security constraints must be spelled out by the requester in the prompt, otherwise the model tends to leave them blank: temporary credentials need to be single-use, restricted to a directory prefix and Content-Type, and limited in file size; stripExif avoids publishing a user’s geolocation along with the image — a real risk in a UGC wallpaper scenario, not an optional one.

    5. AI Creation Chain: Split One Generation into Four Stages

    A description like “upload, then tap once to generate” usually turns into a tangled, coupled block of code in the model’s hands. A practical split is a four-stage pipeline, where each stage is independently observable and retryable:

    1. async function createByImage(filePath, userInstruction) {
    2. // 1) vision understanding: produce structured descriptions across subject / style / background
    3. const analysis = await callFn('analyzeImage', { fileId });
    4. // { subject, style, background, keyElements: [] }
    5. // 2) prompt engineering: the text model rewrites the structured description + user intent into an image-model-friendly prompt
    6. const prompt = await callFn('refinePrompt', { base: analysis, instruction: userInstruction });
    7. // 3) image generation: image-to-image, carrying reference image and weight
    8. const { assetId } = await callFn('generateImage', { prompt, refFileId: analysis.fileId });
    9. // 4) persist: record source and latency, status first enters pending
    10. await callFn('finalizeCreation', { assetId, prompt, analysis, source: 'ai' });
    11. return { prompt, assetId };
    12. }

    The benefit of this split is extremely low debugging cost: if the output is off, first confirm whether the stage-2 prompt matches expectations, then look at the stage-3 model output, instead of guessing inside a several-hundred-line block.

    A three-part prompt (subject, style, background) is also more controllable than a one-shot “describe this image” — it gives users a handle to edit the prompt before generation, changing the interaction from “black-box lottery” to “tunable parameters.”

    Additional engineering constraints to fill in: an idempotency key for generation requests (to avoid duplicate billing from repeated taps), timeout and retry limits, preserving the reference image and prompt on failure for one-tap redo, and recording latency on each call for cost accounting.

    6. Content Safety and Cost: Discuss Now or Fight Fires After Launch

    • Moderation: both UGC uploads and AI generation must pass through content moderation; the state machine should at least include pending / online / offline, with a fallback path from machine review to human re-review. The default state should be invisible, not visible.
    • Cost: vision understanding, text rewriting, and image generation are billed in different units, so you must instrument the creations table; otherwise you can’t answer “which feature is burning money.” On the frontend, add a daily generation quota and a “no charge on failure” policy.
    • Performance: lists go through thumbnails + local disk cache; the detail page then loads the original image; add a cache layer for high-frequency read-only cloud functions.
    • Keys: all third-party service credentials exist only in cloud-function environment variables, and the client never touches them. The prompt must explicitly forbid hardcoded domains and keys.

    7. Making Generated Results Deliverable: A Structured Prompt Template

    More than model capability, the degree of structure in the requirement description affects the output. A reusable template:

    1. Goal: implement an "album detail page," reusing the existing artworks collection and the getArtworkFeed cloud function
    2. Inputs:
    3. - data structure: collections/artworks.json
    4. - reusable modules: components/waterfall, utils/callFn
    5. Constraints:
    6. - native mini program, no third-party UI library
    7. - first-screen images per page <= 20, list uses thumbFileId only
    8. - must cover: empty / loading / failure-retry / offline
    9. Forbidden:
    10. - hardcoded domains, AppID, or keys
    11. - unbounded render loops and unpaginated full-collection queries
    12. Delivery order:
    13. 1) output the file list and interface signatures first, wait for confirmation
    14. 2) then output the implementation code
    15. Acceptance: runs on a real device, no console errors, does not block the main thread on weak networks

    “List first, then implement” is especially important. It turns the model’s output from a one-shot black box into a two-phase, correctable process; most structural problems get caught in the first phase, rather than being discovered only after thirty files have been generated and the data layer is already wrong.

    8. Role Shift: Three Capabilities Developers Need to Reinforce

    When a coding assistant can take on most of the boilerplate, human value concentrates in three places — which are also the three places the model is least reliable:

    1. Boundary definition. What should be done, what explicitly should not, and how exceptions end — these can’t be inferred from the codebase and can only come from a person.
    2. Contract design. Once the data model, interface signatures, or state machine are wrong, the model just more efficiently amplifies the error across every file.
    3. Acceptance criteria. Runnable doesn’t mean usable. Writing real-device, weak-network, boundary-value, cost, and safety requirements into an acceptance checklist is the only reliable way to control generative output.

    The conclusion isn’t complex: the ceiling of such tools depends on the precision of the requirement description and the strictness of the acceptance criteria. Swapping “help me write a feature” for “implement to this contract and cover these four states” makes an order-of-magnitude difference in the usability of the output. What really needs to improve isn’t racing speed against the model, but the ability to translate vague intent into an executable spec.