Home » How to Build a Dry-Run Preview for AI Agent Actions in React Native
React • Technology • Top companies

How to Build a Dry-Run Preview for AI Agent Actions in React Native

Show users what an AI agent would change, let them approve the exact action, and handle stale previews and retries safely.

An AI support agent proposes a $25 refund. Before it sends anything to the payment provider, the app should show which order is affected, how much the customer would receive, and which records would change. If another support agent refunds the order while the preview is open, the original approval should fail safely.

That flow needs two separate backend operations. Preview computes the expected effects without performing the proposed action. Execute applies the specific, previously reviewed plan after checking that it remains valid. A confirmation dialog gives users a choice. A dry run gives them evidence on which to make that choice.

1. Give the AI Agent a Proposal Tool

The agent submits a structured proposal such as a refund request for an order. The application server validates it and computes the preview from current records, permissions, and business rules. Keep the execute endpoint behind a separate permission boundary, with approval coming from the signed-in user’s interaction. Treat model-generated explanations as context and server-calculated fields as the source for the review screen.

A preview may store a review record and produce audit logs. It must avoid the business side effects being previewed. In a refund workflow, that means avoiding refund creation, customer notifications, and changes to the order balance. When a provider has no simulation endpoint, use read-only inputs and label external effects as estimates or unknowns where appropriate.

2. Define the Preview and Execution Contract

EndpointRequestServer behavior
POST /agent-actions/previewProposal IDAuthorize preview access, load the proposal, read current state, and return a stored plan with its effects, warnings, expiry, and an opaque preview ID.
POST /agent-actions/executePreview IDRecheck authorization, load the stored plan, check expiry and relevant versions, and execute only the approved action. Return its current outcome on repeat calls.

Bind the preview to the proposal, relevant resource versions, authenticated actor, and tenant. A client approval carries the preview ID alone. If the amount or destination changes, the server should require a fresh preview and approval. If permissions have been revoked, refuse the action.

Use a stable operation identity for execution. A preview ID can identify retries of one approval, while a separate business operation ID prevents two previews of the same proposal from creating two refunds. Enforce that identity with a unique server-side execution record and a conditional state transition. For distinct proposals against the same order, enforce the remaining refundable balance at execution time. For external writes, reuse a stable provider idempotency key where supported and reconcile uncertain outcomes before attempting another write. An app timeout can occur after the provider has already accepted the operation. 

3. Build the React Native Review Screen

The screen below receives a typed API adapter that handles authentication, validates responses, and maps server outcomes to the result types. It keeps the preview visible during a retry and submits the same ID after a timeout. Mount the screen with key={proposalId} when switching proposals so a prior request cannot update the new proposal’s screen.

import { useRef, useState } from 'react';
import { ActivityIndicator, Button, Text, View } from 'react-native';

type Preview = {
  id: string;
  expiresAt: string;
  summary: string;
  changes: Array<{ id: string; label: string; before: string; after: string }>;
  warnings: Array<{ id: string; message: string }>;
  canExecute: boolean;
};

type ExecutionResult =
  | { status: 'completed'; receiptId: string }
  | { status: 'processing' }
  | { status: 'stale' }
  | { status: 'denied' }
  | { status: 'failed' };

type ReviewApi = {
  preview(proposalId: string): Promise<Preview>;
  execute(previewId: string): Promise<ExecutionResult>;
};

type ReviewState =
  | { status: 'idle' | 'loading' | 'preview-error' | 'stale' | 'denied' | 'failed' }
  | { status: 'ready' | 'executing' | 'uncertain'; preview: Preview }
  | { status: 'completed'; receiptId: string };

export function AgentActionReview({
  proposalId,
  api,
}: {
  proposalId: string;
  api: ReviewApi;
}) {
  const [state, setState] = useState<ReviewState>({ status: 'idle' });
  const inFlight = useRef(false);

  async function loadPreview() {
    if (inFlight.current) return;
    inFlight.current = true;
    setState({ status: 'loading' });

    try {
      const preview = await api.preview(proposalId);
      setState({ status: 'ready', preview });
    } catch {
      setState({ status: 'preview-error' });
    } finally {
      inFlight.current = false;
    }
  }

  async function execute(preview: Preview) {
    if (inFlight.current || !preview.canExecute) return;
    inFlight.current = true;
    setState({ status: 'executing', preview });

    try {
      const result = await api.execute(preview.id);
      if (result.status === 'processing') {
        setState({ status: 'uncertain', preview });
      } else {
        setState(result);
      }
    } catch {
      setState({ status: 'uncertain', preview });
    } finally {
      inFlight.current = false;
    }
  }

  if (state.status === 'loading') {
    return <ActivityIndicator accessibilityLabel="Preparing action preview" />;
  }

  if (state.status === 'completed') {
    return <Text accessibilityRole="alert">Completed. Receipt {state.receiptId}</Text>;
  }

  if (state.status === 'denied' || state.status === 'failed') {
    return (
      <Text accessibilityRole="alert">
        {state.status === 'denied'
          ? 'You cannot approve this action.'
          : 'The action failed. Contact support if it still needs to be completed.'}
      </Text>
    );
  }

  if ('preview' in state) {
    const { preview } = state;
    const executing = state.status === 'executing';
    return (
      <View>
        <Text accessibilityRole="header">Review proposed action</Text>
        <Text>{preview.summary}</Text>
        <Text>Preview expires at {new Date(preview.expiresAt).toLocaleString()}</Text>
        {preview.changes.map((change) => (
          <View key={change.id}>
            <Text>{change.label}</Text>
            <Text>Before: {change.before}</Text>
            <Text>After: {change.after}</Text>
          </View>
        ))}
        {preview.warnings.map((warning) => (
          <Text key={warning.id}>{warning.message}</Text>
        ))}
        {state.status === 'uncertain' && (
          <Text accessibilityRole="alert">
            The outcome is unknown or still processing. Retry this approval before starting another.
          </Text>
        )}
        <Button
          title={
            state.status === 'uncertain'
              ? 'Retry approved action'
              : executing
                ? 'Submitting approval…'
                : 'Approve and execute'
          }
          disabled={!preview.canExecute || executing}
          onPress={() => void execute(preview)}
        />
      </View>
    );
  }

  const message =
    state.status === 'stale'
      ? 'This preview is no longer valid. Generate a new preview to continue.'
      : state.status === 'preview-error'
        ? 'The preview could not be loaded.'
        : null;

  return (
    <View>
      {message && <Text accessibilityRole="alert">{message}</Text>}
      <Button title="Preview action" onPress={() => void loadPreview()} />
    </View>
  );
}

The review shows before and after values, warnings, and the expiry in readable text. Put long reviews inside the app’s scrollable screen layout, test alerts and focus with VoiceOver and TalkBack, and give warnings text labels so color carries no essential information. React web can use the same API and state transitions with native HTML controls. 

For execution, the API should return an existing outcome or processing state for a known approval before evaluating expiry for a new execution. This lets the original approver retrieve a result after the preview expires. If a timeout leaves acceptance uncertain, Retry approved action resends the same explicitly approved request. It can start the approved action if the first request never reached the server. A product that needs a strictly read-only status button should expose a dedicated status endpoint and label the action that retries separately.

4. What Five Companies Document About Preview and Approval

  • GeekyAnts describes AntFlow AI as a spec-driven workflow with separate implementation and verification roles. Human stakeholders retain control over approval gates and final delivery. For an app team, the transferable practice is to give reviewers a concrete, independently checked plan before they authorize a sensitive step. 
  • AWS CloudFormation change sets show which resources a stack update would affect and apply changes only when the change set is executed. The preview also has limits, so a successful plan should leave room for execution-time failure. 
  • Stripe lets teams preview upcoming invoice amounts and subscription changes before creating the invoice. It documents that exchange rates may change between preview and creation, a concrete example of why some preview values need an estimate label. 
  • Vercel documents server-side AI tool approval in the AI SDK. Its current API exposes approval through toolApproval on streamText. The approval gate can hold a tool call while a separate preview service computes a trustworthy diff. 
  • GitHub Actions can hold a deployment job for required reviewers. The job proceeds after approval and other protection rules pass. The app-design lesson is to require the approval at the execution boundary, even if the UI already shows a review step. 

5. Test the Paths That Can Invalidate an Approval

  • Preview only. Verify that creating a preview writes no business records and never calls the payment provider’s refund operation.
  • State drift. Change the remaining refundable amount after the preview. Execution should return stale, and the app should ask for a new review.
  • Permission changes. Revoke refund access after preview. The server should deny execution even if the button is still visible.
  • Duplicate taps and timeouts. Send two executions for the same approval and simulate a lost response after the provider accepts it. Verify that only one refund exists and that the app can retrieve the same outcome.
  • Competing previews. Open the same proposal on two devices and approve both. Verify that business-level deduplication prevents duplicate execution.

A useful dry-run preview lets someone identify the exact change they are authorizing. A reliable execution path applies that change once, checks that its assumptions still hold, and returns an outcome the user can verify.