Building Frontends with Coding Agents: A Specification-First Workflow That Actually Works

Building Frontends with Coding Agents: A Specification-First Workflow That Actually Works

Agentic coding tools are remarkably good at producing frontend code. Give one an empty repository and ask for a todo app and, within minutes, you may have components, styling, local persistence and tests.

That speed creates a new problem: plausible code arrives before anyone has properly defined the problem.

The result may compile and look polished while quietly containing duplicated state, inaccessible controls, brittle effects, invalid persistence assumptions or tests that confirm the implementation rather than the behaviour.

The answer is not to avoid AI-assisted development. It is to change the workflow around it. The most effective approach is specification-first: define behaviour and invariants, ask the agent to inspect its environment, implement in reviewable slices and verify the result through observable outcomes.

The weak prompt

Build a todo app in React.
Make it modern and responsive.
Add tests.

This sounds reasonable, but it leaves almost every important decision undefined:

  • Can blank tasks be created?
  • Are titles trimmed?
  • Does the app persist data?
  • What happens when persisted data is malformed?
  • Are filters stored or derived?
  • What does “responsive” mean?
  • Which testing style should be used?
  • What accessibility behaviour is required?
  • Should the agent add a state library?
  • Does the repository already have conventions?

An agent will fill those gaps. It may make good choices, but those choices will be assumptions rather than requirements.

Step 1: Write a behavioural contract

A behavioural contract is a compact description of what a user can do and what must remain true. For a todo app:

Required behaviour

1. A user can add a task by submitting the form.
2. Leading and trailing whitespace is removed.
3. Blank titles are rejected.
4. A user can toggle a task complete or incomplete.
5. A user can delete a task.
6. A user can filter by all, active or completed.
7. The active count is always calculated from the current list.
8. Todos survive a page refresh.
9. Invalid persisted data does not crash the application.
10. Core operations work with keyboard-only input.

This contract is deliberately independent of React, Vue, Svelte or Angular. It describes the product, not its implementation.

Step 2: Add engineering invariants

Invariants prevent an agent from solving the visible task in a structurally weak way:

Engineering invariants

- The complete todo list is canonical state.
- Filtered todos and counts are derived values.
- Filtering never mutates or removes source data.
- Domain transitions are pure TypeScript functions.
- Persistence is isolated from rendering logic.
- No new state-management dependency is required.
- Inputs have accessible labels.
- Toggle controls expose checked state.
- Filter controls expose selected state.
- Destructive controls have specific accessible names.
- Tests assert user-visible behaviour rather than component internals.

These constraints teach the agent what quality means in this repository.

Step 3: Make the agent inspect before editing

A coding agent should not begin by generating files from memory. It should first discover:

  • the installed framework and exact version;
  • the build system;
  • the test runner and testing utilities;
  • formatting and linting rules;
  • existing component conventions;
  • where shared types and utilities live;
  • whether the project renders on the server;
  • how similar features are structured.

A strong discovery prompt is:

Before changing code, inspect package.json, the source tree and the
closest existing feature.

Report:
- framework and version;
- rendering model;
- state conventions;
- styling conventions;
- test tooling;
- relevant scripts;
- files you propose to add or modify;
- assumptions that need validation.

Do not implement yet.

This pause is valuable. It reveals whether the agent understands the environment and gives the developer a cheap point to correct direction.

Step 4: Ask for a thin vertical slice

Do not request the complete feature in one enormous change. Begin with the smallest end-to-end behaviour:

Implement only the first vertical slice:

- render the todo page;
- add a labelled input and submit button;
- reject blank input;
- display newly added todos;
- add focused tests for those behaviours.

Do not add filtering, deletion, persistence or styling beyond the
existing project conventions.

Run the relevant checks and summarise the result.

This produces a reviewable change. Once state ownership and form behaviour are correct, add toggling and deletion. Then filtering. Then persistence. Then polish.

Small slices reduce the chance that the agent builds several later features on top of an early mistake.

Step 5: Separate domain logic from UI adapters

Framework components should coordinate rendering and user interaction. Basic transitions can remain ordinary functions:

export type Todo = {
  id: string;
  title: string;
  completed: boolean;
};

export function normaliseTitle(value: string): string {
  return value.trim();
}

export function addTodo(
  todos: Todo[],
  rawTitle: string,
  id: string
): Todo[] {
  const title = normaliseTitle(rawTitle);

  if (!title) return todos;

  return [
    ...todos,
    { id, title, completed: false }
  ];
}

export function toggleTodo(todos: Todo[], id: string): Todo[] {
  return todos.map(todo =>
    todo.id === id
      ? { ...todo, completed: !todo.completed }
      : todo
  );
}

export function deleteTodo(todos: Todo[], id: string): Todo[] {
  return todos.filter(todo => todo.id !== id);
}

The generated React, Vue, Svelte or Angular component becomes an adapter around these rules. This produces three benefits:

  1. Domain behaviour can be tested cheaply without rendering.
  2. Framework migrations affect less code.
  3. Reviewers can separate business correctness from reactive syntax.

Step 6: Be explicit about state categories

Ask the agent to classify each value:

Category Todo example Treatment
Canonical state Full todo list Stored once
UI state Selected filter, input text Stored locally
Derived state Visible todos, active count Calculated
External state Local storage Read and synchronised at a boundary

A frequent generated-code smell is storing every value separately, followed by effects that attempt to keep them synchronised. If remainingCount can be calculated from todos, it should not have its own setter.

A useful review prompt is:

List every state value in this feature.
For each one, classify it as canonical, UI, derived or external.
Identify any value that can be removed and calculated instead.

Step 7: Define persistence failure behaviour

A one-line JSON.parse(localStorage.getItem(...)) can crash the app. At minimum, loading should be defensive:

const STORAGE_KEY = "todos-v1";

export function loadTodos(storage: Storage): Todo[] {
  try {
    const parsed: unknown = JSON.parse(
      storage.getItem(STORAGE_KEY) ?? "[]"
    );

    if (!Array.isArray(parsed)) return [];

    return parsed.filter(isTodo);
  } catch {
    return [];
  }
}

function isTodo(value: unknown): value is Todo {
  if (!value || typeof value !== "object") return false;

  const todo = value as Record<string, unknown>;

  return (
    typeof todo.id === "string" &&
    typeof todo.title === "string" &&
    typeof todo.completed === "boolean"
  );
}

Dependency-injecting the Storage interface also makes the loader easier to test.

For a real application, persistence may require a versioned schema and migration strategy. The point is not to over-engineer a todo app. It is to make failure behaviour intentional.

Step 8: Make accessibility an acceptance criterion

Agents can generate accessible markup, but only when accessibility is part of “done”. Require:

  • a visible label associated with the new-task input;
  • a real form so Enter submits naturally;
  • real buttons rather than clickable generic elements;
  • checkboxes for completed state;
  • aria-pressed on filter buttons;
  • a task-specific accessible name for delete buttons;
  • a sensible focus outcome after adding or deleting;
  • a live region for a changing count only if the announcement is genuinely useful.

Then ask the agent to explain the keyboard path:

Describe how a keyboard-only user:
1. adds a task;
2. marks it complete;
3. changes the filter;
4. deletes it.

Identify any operation that depends on pointer input or an unlabeled
control, then correct it.

Step 9: Test rules before framework mechanics

Pure domain tests should cover the rules:

describe("addTodo", () => {
  it("rejects a blank title", () => {
    expect(addTodo([], "   ", "1")).toEqual([]);
  });

  it("trims the title", () => {
    expect(addTodo([], "  Ship feature  ", "1")).toEqual([
      {
        id: "1",
        title: "Ship feature",
        completed: false
      }
    ]);
  });
});

Component tests should cover user behaviour:

it("adds a todo from the keyboard", async () => {
  render(<TodoApp />);

  await user.type(
    screen.getByRole("textbox", { name: /new task/i }),
    "Write tests{enter}"
  );

  expect(
    screen.getByText("Write tests")
  ).toBeVisible();

  expect(
    screen.getByRole("textbox", { name: /new task/i })
  ).toHaveValue("");
});

The exact rendering helper changes between frameworks. The behavioural intent should not.

Step 10: Force the agent to prove its work

“Done” should include evidence:

Verification required before completion:

- run the unit and component tests;
- run the type checker;
- run linting;
- run the production build;
- report the exact commands and outcomes;
- disclose any check you could not run;
- summarise manual keyboard and persistence checks;
- list remaining assumptions.

This does not guarantee correctness. It does stop the conversation ending at “the code should work”.

Useful adversarial review prompts

State review

Assume this component has a subtle state synchronisation bug.
Try to find it. Pay particular attention to derived values,
effects, stale closures and mutation.

Accessibility review

Audit this feature against keyboard and screen-reader use.
Report issues by user impact, then make the smallest fixes.
Do not add ARIA where native HTML already provides semantics.

Persistence review

Assume localStorage contains malformed JSON, an old schema,
duplicate IDs or values with the wrong types.
Show the current behaviour and make loading fail safely.

Simplicity review

Review every abstraction, dependency and hook added by this change.
Remove anything that is not justified by the current requirements.
Prefer ordinary TypeScript and platform APIs.

Repository-fit review

Compare this change with the three closest features in the repository.
Identify differences in naming, file placement, testing, styling and
error handling. Align with local conventions unless there is a clear
reason not to.

When to let the agent choose

An agent can usually choose:

  • routine syntax consistent with the repository;
  • mechanical file organisation already established nearby;
  • basic test scaffolding;
  • type annotations inferred from an agreed model;
  • repetitive markup and styling conventions.

A human should retain ownership of:

  • product behaviour and priorities;
  • state ownership;
  • data and security boundaries;
  • accessibility acceptance criteria;
  • dependency and architecture decisions;
  • operational consequences;
  • the final judgement that the change is maintainable.

The engineering advantage is not faster typing

The obvious benefit of AI-assisted coding is speed. The deeper benefit is inexpensive exploration: an agent can prototype two state models, port a component between frameworks, generate edge cases, explain unfamiliar APIs and challenge a design before it becomes expensive.

That advantage appears only when the developer supplies a strong frame.

A vague request produces a fast guess. A behavioural contract, explicit invariants, repository inspection, thin slices and verification produce something much closer to engineering.

The goal is not to become better at asking an agent to write code.

It is to become better at defining what correct code must mean.

Comments

Popular posts from this blog

The Concept of True North in Lean Methodology: A Toyota Perspective

The Archetypes of Staff Engineers: How to Excel and When Your Business Needs One

Serverless Architectures: Simplifying Backend Development for Scalable Apps in 2025