# Loops

**A loop is repeated rendering, not a second execution runtime.** `<Loop>` renders its body, and when the body renders `next(value)`, that renders the body again with the new value. Each iteration is nested in the one before it, so it's a [dependency](https://june.dev/docs/workflows/composition.md) like any other: it can't exist until the last one finishes.

Use it for bounded iteration, where each pass depends on the last: critique and revise, plan and check, try and repair.

```tsx
import { openai } from "june/sdk/openai";
import { Agent, Loop, Step } from "june";

export default function Tighten({ text }: { text: string }) {
  return (
    <Agent model={openai("gpt-5-mini")}>
      <Loop id="tighten" initial={text} maxIterations={3}>
        {({ value, next, stepId }) => (
          <Step id={stepId("cut")} prompt={`Cut a third of this:\n${value}`}>
            {(shorter) => next(shorter)}
          </Step>
        )}
      </Loop>
    </Agent>
  );
}
```

This runs three steps in order: `tighten:1:cut` on `text`, `tighten:2:cut` on the first result, and `tighten:3:cut` on the second.

## The body

`children` is a function that renders one iteration. It gets:

| Field           |                                                                                     |
| --------------- | ----------------------------------------------------------------------------------- |
| `value`         | `initial` on the first iteration, then whatever the last one passed to `next`       |
| `iteration`     | this iteration's number, starting at 1                                              |
| `maxIterations` | the loop's limit                                                                    |
| `next(value)`   | ends the iteration with `value`, and returns what comes after it, for you to render |
| `stepId(name)`  | a step id for this iteration: `${loopId}:${iteration}:${name}`                      |

**`next` is a render continuation, not a mutation.** Calling it changes nothing. It returns the rest of the loop, the next iteration or the loop's result, and that runs because you render it. So render it where the iteration's result is in scope, usually in the last step's function child, and render it once per iteration. An iteration that never renders `next` ends the loop there, with no result and no `complete`.

The body is rendered as a component, so it can call hooks such as [`useStep`](https://june.dev/docs/workflows/use-step.md), and it can render anything a workflow can: several steps in a chain, `<Parallel>`, another `<Agent>`, or a branch that picks a different step each time.

## `until`

Without `until`, a loop runs exactly `maxIterations` iterations. With it, the loop checks each value passed to `next` and stops as soon as one passes:

```tsx
import { openai } from "june/sdk/openai";
import { Agent, Loop, Step } from "june";

export default function Tighten({ text }: { text: string }) {
  return (
    <Agent model={openai("gpt-5-mini")}>
      <Loop
        id="tighten"
        initial={text}
        maxIterations={5}
        until={(value) => value.length <= 280}
      >
        {({ value, next, stepId }) => (
          <Step id={stepId("cut")} prompt={`Cut a third of this:\n${value}`}>
            {(shorter) => next(shorter)}
          </Step>
        )}
      </Loop>
    </Agent>
  );
}
```

- `until(value, { iteration, maxIterations })` is checked after each iteration, on that iteration's result. It isn't checked on `initial`: the first iteration always runs.
- When it's true on the last allowed iteration, the loop still ended because of `until`, and reports that.
- It runs while rendering, and React may render more than once, so keep it a pure function of its arguments.

## `complete`

`complete(value, context)` renders once the loop ends, with the final value. Its `context` has the last `iteration`, `maxIterations`, and the `reason`: `"until"`, or `"maxIterations"` when the loop ran out first. It isn't called before then, and it can render steps like any other part of the tree:

```tsx
import { openai } from "june/sdk/openai";
import { Agent, Loop, Step } from "june";

export default function Tighten({ text }: { text: string }) {
  return (
    <Agent model={openai("gpt-5-mini")}>
      <Loop
        id="tighten"
        initial={text}
        maxIterations={5}
        until={(value) => value.length <= 280}
        complete={(value, { reason }) =>
          reason === "until" ? (
            <Step id="post" prompt={`Add a hashtag to:\n${value}`} />
          ) : (
            <Step id="thread" prompt={`Split this into a thread:\n${value}`} />
          )
        }
      >
        {({ value, next, stepId }) => (
          <Step id={stepId("cut")} prompt={`Cut a third of this:\n${value}`}>
            {(shorter) => next(shorter)}
          </Step>
        )}
      </Loop>
    </Agent>
  );
}
```

The final value reaches the rest of the workflow through `complete`, the same way a step's result reaches its function child. To use it further down, render that work from `complete`.

## Step ids

[A step's id names its work for the whole run](https://june.dev/docs/workflows/step-identity.md), and a loop renders the same body several times. A fixed id would name the same step in every iteration:

```tsx
import { Loop, Step } from "june";

declare const draft: string;

// Bad: every iteration renders a step called "revise" with a different
// prompt, and the run fails: `june: step revise was rendered with two
// different definitions`.
<Loop id="refine" initial={draft} maxIterations={3}>
  {({ value, next }) => (
    <Step id="revise" prompt={`Revise:\n${value}`}>
      {(revised) => next(revised)}
    </Step>
  )}
</Loop>;

// Good: `refine:1:revise`, `refine:2:revise`, `refine:3:revise`.
<Loop id="refine" initial={draft} maxIterations={3}>
  {({ value, next, stepId }) => (
    <Step id={stepId("revise")} prompt={`Revise:\n${value}`}>
      {(revised) => next(revised)}
    </Step>
  )}
</Loop>;
```

- **`stepId` is deterministic.** It's made from the loop's `id`, the iteration number and the name you give it, so the same loop names the same steps on every run, which is what lets a [snapshot](https://june.dev/docs/workflows/resume.md) match them.
- **June doesn't rewrite ids for you.** A step in a loop has exactly the id you give it. Use `stepId` for every step in the body, including each [`useStep`](https://june.dev/docs/workflows/use-step.md).
- **Give each loop its own `id`.** Two loops with the same id make the same step ids. For a loop inside a loop, `stepId` makes a good id: see [nested loops](#nested-loops).
- **A step that should run once** for the whole loop can keep a fixed id, as long as it renders with the same definition every time. That's ordinary [id sharing](https://june.dev/docs/workflows/step-identity.md#the-rules).

## A critic and a reviser

The loop's value can be any type. Here it's an object carrying the draft and what the critic last said. A structured `critique` step scores the draft, `until` stops once the score passes, and `complete` runs one final edit on whichever draft the loop ended with:

```tsx
// refine.tsx
import { openai } from "june/sdk/openai";
import { Output, jsonSchema, type LanguageModel } from "ai";
import { Agent, Loop, Step } from "june";

/** The draft the loop carries, and what the critic last said about it. */
export interface Revision {
  draft: string;
  /** The critic's score for the last draft it read, or 0 before the first. */
  score: number;
  feedback: string;
}

const critique = Output.object({
  schema: jsonSchema<{ score: number; feedback: string }>({
    type: "object",
    properties: {
      score: { type: "number", description: "1 to 10" },
      feedback: { type: "string", description: "What to change, briefly" },
    },
    required: ["score", "feedback"],
    additionalProperties: false,
  }),
});

export default function Refine({
  brief,
  passingScore = 8,
  maxIterations = 3,
  model = openai("gpt-5-mini"),
}: {
  brief: string;
  passingScore?: number;
  maxIterations?: number;
  model?: LanguageModel;
}) {
  return (
    <Agent model={model} instructions="You write short product announcements.">
      <Step id="draft" prompt={`Write an announcement for:\n${brief}`}>
        {(draft) => (
          <Loop<Revision>
            id="refine"
            initial={{ draft, score: 0, feedback: "" }}
            maxIterations={maxIterations}
            until={({ score }) => score >= passingScore}
            complete={({ draft, score }, { iteration, reason }) => (
              <Step
                id="final"
                prompt={`Copy-edit this announcement without changing what it says. It scored ${score}/10 after ${iteration} review(s) (${reason}).\n${draft}`}
              />
            )}
          >
            {({ value, next, stepId }) => (
              <Step
                id={stepId("critique")}
                prompt={`Score this announcement from 1 to 10 against the brief, and say what to change.\nBrief: ${brief}\n${value.draft}`}
                output={critique}
              >
                {({ score, feedback }) => {
                  if (score >= passingScore) {
                    return next({ draft: value.draft, score, feedback });
                  }
                  return (
                    <Step
                      id={stepId("revise")}
                      prompt={`Revise this announcement. Feedback: ${feedback}\n${value.draft}`}
                    >
                      {(revised) => next({ draft: revised, score, feedback })}
                    </Step>
                  );
                }}
              </Step>
            )}
          </Loop>
        )}
      </Step>
    </Agent>
  );
}
```

```sh
june run refine.tsx --input '{"brief":"Announce --json for june run"}'
```

- A draft that passes skips `revise`: the body is a [branch](https://june.dev/docs/workflows/composition.md#branching), and only what renders runs.
- A draft that fails is revised and passed on with its old score, so `until` is false and the next iteration scores the revision.
- The last allowed iteration can end on a revision nobody scored. `complete` gets `reason: "maxIterations"` and decides what that means; here it edits the draft anyway.
- `<Loop<Revision>>` names the value's type. Without it, TypeScript infers the type from `initial`.

## Loop or the agent's tool loop

A `<Step>` already loops: the AI SDK's agent calls the model, runs the tools it asks for, and calls it again until it stops or the agent's `stopWhen` is met. That's a different loop, and the two compose.

|               | The agent's tool loop                           | `<Loop>`                                               |
| ------------- | ----------------------------------------------- | ------------------------------------------------------ |
| Where         | inside one [`<Step>`](https://june.dev/docs/workflows/agent-and-step.md#step) | around steps                                           |
| Who decides   | the model, by calling tools or not              | your code: `until` and what the body renders           |
| Bounded by    | the agent's `stopWhen`                          | `maxIterations`                                        |
| On the trace  | one `step` node, with its `toolCalls`           | a node for each iteration, and for each step in it     |
| In a snapshot | one entry, once the whole step finishes         | an entry for each finished step, in every iteration    |
| Context       | one growing conversation                        | each step starts fresh, with only the prompt you write |

Let the model drive when the work is open-ended tool use: read these files, search, then answer. Use `<Loop>` when the phases are yours: a critic with one set of instructions, a reviser with another, and a stopping rule you can read. A step inside a `<Loop>` still runs its own tool loop.

## With the rest of the runtime

A loop adds no execution machinery of its own, so everything else works inside it the way it does anywhere.

- **[`<Catch>`](https://june.dev/docs/workflows/recovery.md) around a loop.** When a step in a later iteration fails, the fallback replaces the whole loop. `retry()` renders it again from the first iteration: the steps that finished keep their results and don't run again, the failed step runs again, and the loop goes on from there.
- **`<Catch>` inside an iteration.** The fallback is part of that iteration, so it can render `next(value)` to carry on without the failed step's result, or another step with a `stepId` of its own.
- **[Run options](https://june.dev/docs/workflows/running.md).** `signal` and `timeout` belong to the run, and reach whichever step is in flight; there's no per-loop timeout. Iterations never overlap, whatever the `concurrency`, because each one is rendered from the last one's result. The limit counts the steps inside an iteration as it counts any others.
- **[`<Parallel>`](https://june.dev/docs/workflows/parallelism.md) inside an iteration.** Fan out inside the body, then [fan in](https://june.dev/docs/workflows/parallelism.md#fan-in) and render `next` where every result is in scope.
- **[Approvals](https://june.dev/docs/workflows/approvals.md).** A step in a loop that needs one pauses the run like any other step.

### Lists

A loop isn't for doing the same thing to every item of a list. Items that don't depend on each other are a `.map()` inside `<Parallel>`, with ids [derived from each item](https://june.dev/docs/workflows/parallelism.md#fan-out). A loop's ids are made from the iteration number, which suits work that is identified by its round, such as the second revision, and not work identified by an item.

When each item's step needs the result of the one before it, a loop can walk the list, with `maxIterations` as its length. `maxIterations` must be at least 1, so handle an empty list before rendering the loop.

### Nested loops

A loop inside a loop needs a different id in each outer iteration. Make it with the outer `stepId`, and pass the inner loop's final value to the outer `next` from `complete`:

```tsx
import { openai } from "june/sdk/openai";
import { Agent, Loop, Step } from "june";

export default function Book({ outline }: { outline: string }) {
  return (
    <Agent model={openai("gpt-5-mini")}>
      <Loop
        id="chapters"
        initial={[] as string[]}
        maxIterations={3}
        complete={(chapters) => (
          <Step
            id="blurb"
            prompt={`Write a blurb for:\n${chapters.join("\n\n")}`}
          />
        )}
      >
        {({ value: chapters, iteration, next, stepId }) => (
          <Step
            id={stepId("draft")}
            prompt={`Write chapter ${iteration} of:\n${outline}`}
          >
            {(draft) => (
              <Loop
                id={stepId("polish")}
                initial={draft}
                maxIterations={2}
                complete={(chapter) => next([...chapters, chapter])}
              >
                {(polish) => (
                  <Step
                    id={polish.stepId("edit")}
                    prompt={`Tighten this chapter:\n${polish.value}`}
                  >
                    {(edited) => polish.next(edited)}
                  </Step>
                )}
              </Loop>
            )}
          </Step>
        )}
      </Loop>
    </Agent>
  );
}
```

The inner steps are `chapters:1:polish:1:edit`, `chapters:1:polish:2:edit`, `chapters:2:polish:1:edit` and so on: no two share an id.

### Snapshots

A [snapshot](https://june.dev/docs/workflows/resume.md) has nothing about loops in it, only finished steps. That's enough. A resumed run renders the loop from its first iteration, each finished step returns its result without running, and `next` renders the following iteration, until the loop reaches the first step that hadn't finished. That one runs, and the loop carries on.

It works because the ids are deterministic and each `<Step>`'s [cache key](https://june.dev/docs/workflows/step-identity.md#what-a-steps-cache-key-covers) covers its prompt. If an early iteration's result would now be different, say because `initial` changed, the steps after it render with new prompts, no longer match their entries, and run again.

## On the trace

`<Loop>` renders three kinds of [trace](https://june.dev/docs/workflows/traces.md) node, nested the way the loop ran. Each iteration is inside what the one before it rendered, and the result is inside the last one:

```json
{
  "type": "loop",
  "props": { "id": "tighten", "maxIterations": 3 },
  "children": [
    {
      "type": "iteration",
      "props": { "iteration": 1 },
      "children": [
        {
          "type": "step",
          "props": { "id": "tighten:1:cut", "status": "done" },
          "children": [
            {
              "type": "iteration",
              "props": { "iteration": 2 },
              "children": [
                {
                  "type": "step",
                  "props": { "id": "tighten:2:cut", "status": "done" },
                  "children": [
                    {
                      "type": "loopResult",
                      "props": { "iteration": 2, "reason": "until" },
                      "children": []
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}
```

What `complete` renders is inside the `loopResult` node. The loop's values aren't on these nodes; they're in the results and prompts of the steps that made and used them.

## Why `maxIterations` is required

A loop whose only exit is a model's judgment can run until the budget does. A critic that never gives an 8, or a check that never passes, is an ordinary failure, and without a limit it costs a model call per iteration, forever. So the limit isn't optional and has no default: you choose it, where the loop is written, and the trace shows it.

It must be a positive whole number. Anything else, such as `0`, `2.5` or `Infinity`, fails the render with `june: <Loop id="refine"> needs maxIterations to be a positive whole number`, before any step runs.

Reaching the limit isn't an error. The loop ends with `reason: "maxIterations"` and `complete` decides what to do about it: use the last value, render a fallback step, or throw.

## What a loop isn't

- **A scheduler or a second runtime.** There's no loop state in the run, no `while` running outside React, and nothing new in a snapshot.
- **`break` and `continue`.** To stop early, make `until` true for the value you pass to `next`. To skip the rest of an iteration, render `next` sooner.
- **Unbounded.** There's no `maxIterations={Infinity}` and no way to raise the limit while the loop runs.
- **Parallel.** Iterations run one after another. For independent work, use [`<Parallel>`](https://june.dev/docs/workflows/parallelism.md).
- **A way to rename steps.** It doesn't scope or rewrite the ids of the steps inside it; `stepId` is a helper you call.
- **Durable.** Like the rest of a run, a loop lives in one process, and an iteration that hadn't finished [starts again](https://june.dev/docs/workflows/resume.md#what-resume-isnt) on resume.

## Next

- [Step identity](https://june.dev/docs/workflows/step-identity.md): ids, cache keys, and when a step runs.
- [Recovery](https://june.dev/docs/workflows/recovery.md): `<Catch>`, failure and retry.
- [Snapshots and resume](https://june.dev/docs/workflows/resume.md): reusing finished steps after a restart.
