Show Task Progress in a Next.js AI Application

Show Task Progress in a Next.js AI Application

Published on

0

views

This article demonstrates how to build a practical progress tracker for AI features in Next.js without complex queues or WebSockets. Using a lightweight React component, it covers multi-stage loading states, elapsed time counters, abort-controller cancellation, and clear error handling, ensuring users stay informed during slow model inference calls.

You have a working FastAPI summarization endpoint and a typed TypeScript client. The next real-user problem appears the moment the call takes longer than a second or two: the interface goes quiet and the user wonders whether anything is happening.

This article shows a practical way to surface task progress in a Next.js application without turning the feature into a full job queue or WebSocket system. We keep the first version simple, honest, and easy to remove if the latency numbers later prove the complexity is not worth it.

The Short Answer

Low-angle shot of a developer reviewing React component code for multi-stage loading states on a laptop.

Add a lightweight progress state on the client that moves through a few clear stages—idle, submitting, waiting for model, complete, or error—while the typed client call is in flight. Optionally show an estimated token or elapsed-time indicator. Do not pretend the model is streaming if it is not. Keep the backend synchronous for now and only add background jobs when measurement says you need them.

What Product Problem This Solves

Users tolerate a short wait when they can see that work is actually happening. A frozen button and a blank screen feel broken even when the request is progressing normally. Progress feedback turns an opaque network call into a visible process the user can understand and, if necessary, cancel.

For an AI feature the stakes are a little higher: the call can be slow, the cost is real, and a silent failure is easy to miss. Showing progress is part of treating the feature as software rather than a magic black box.

Minimal Working Implementation

We will use the typed client from the previous article and a small React component that manages progress state. The example assumes a Next.js App Router setup, but the same pattern works in the Pages Router or any React application.

tsx

// components/SummarizeForm.tsx
"use client";

import { useState, useRef } from "react";
import {
  summarizeText,
  SummarizeApiError,
  SummarizeResponse,
} from "@/api/summarizeClient";

type ProgressStage =
  | "idle"
  | "submitting"
  | "waiting"
  | "complete"
  | "error";

interface ProgressState {
  stage: ProgressStage;
  message: string;
  startedAt?: number;
  result?: SummarizeResponse;
  error?: string;
}

const STAGE_MESSAGES: Record<ProgressStage, string> = {
  idle: "Ready",
  submitting: "Sending request…",
  waiting: "Model is working…",
  complete: "Summary ready",
  error: "Something went wrong",
};

export default function SummarizeForm() {
  const [text, setText] = useState("");
  const [style, setStyle] = useState<"concise" | "bullet" | "technical">("concise");
  const [progress, setProgress] = useState<ProgressState>({
    stage: "idle",
    message: STAGE_MESSAGES.idle,
  });
  const abortRef = useRef<AbortController | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (progress.stage === "submitting" || progress.stage === "waiting") return;

    abortRef.current = new AbortController();
    const startedAt = Date.now();

    setProgress({
      stage: "submitting",
      message: STAGE_MESSAGES.submitting,
      startedAt,
    });

    // Brief visual pause so the user sees the submitting state
    await new Promise((r) => setTimeout(r, 150));

    setProgress((prev) => ({
      ...prev,
      stage: "waiting",
      message: STAGE_MESSAGES.waiting,
    }));

    try {
      const result = await summarizeText(
        { text, style },
        { signal: abortRef.current.signal }
      );

      setProgress({
        stage: "complete",
        message: STAGE_MESSAGES.complete,
        startedAt,
        result,
      });
    } catch (err) {
      if (err instanceof DOMException && err.name === "AbortError") {
        setProgress({
          stage: "idle",
          message: "Cancelled",
        });
        return;
      }

      const message =
        err instanceof SummarizeApiError
          ? `${err.status}: ${err.message}`
          : "Unexpected error";

      setProgress({
        stage: "error",
        message: STAGE_MESSAGES.error,
        startedAt,
        error: message,
      });
    } finally {
      abortRef.current = null;
    }
  }

  function handleCancel() {
    abortRef.current?.abort();
  }

  const elapsed =
    progress.startedAt && (progress.stage === "waiting" || progress.stage === "complete")
      ? ((Date.now() - progress.startedAt) / 1000).toFixed(1)
      : null;

  return (
    <div className="max-w-xl space-y-4">
      <form onSubmit={handleSubmit} className="space-y-3">
        <textarea
          value={text}
          onChange={(e) => setText(e.target.value)}
          rows={6}
          className="w-full border rounded p-2"
          placeholder="Paste text to summarize (min 20 characters)"
          disabled={progress.stage === "submitting" || progress.stage === "waiting"}
        />

        <div className="flex gap-3 items-center">
          <select
            value={style}
            onChange={(e) => setStyle(e.target.value as any)}
            disabled={progress.stage === "submitting" || progress.stage === "waiting"}
            className="border rounded p-1"
          >
            <option value="concise">Concise</option>
            <option value="bullet">Bullet</option>
            <option value="technical">Technical</option>
          </select>

          <button
            type="submit"
            disabled={
              text.trim().length < 20 ||
              progress.stage === "submitting" ||
              progress.stage === "waiting"
            }
            className="px-4 py-1 bg-blue-600 text-white rounded disabled:opacity-50"
          >
            Summarize
          </button>

          {(progress.stage === "submitting" || progress.stage === "waiting") && (
            <button
              type="button"
              onClick={handleCancel}
              className="px-3 py-1 border rounded"
            >
              Cancel
            </button>
          )}
        </div>
      </form>

      {/* Progress panel */}
      <div className="border rounded p-3 bg-gray-50 text-sm">
        <div className="font-medium">{progress.message}</div>
        {elapsed && <div className="text-gray-600">Elapsed: {elapsed}s</div>}
        {progress.stage === "complete" && progress.result && (
          <div className="mt-2 space-y-1">
            <div className="text-gray-600">
              Tokens: {progress.result.usage.total_tokens} · Finish:{" "}
              {progress.result.finish_reason}
            </div>
            <pre className="whitespace-pre-wrap bg-white p-2 border rounded">
              {progress.result.summary}
            </pre>
          </div>
        )}
        {progress.stage === "error" && progress.error && (
          <div className="mt-1 text-red-600">{progress.error}</div>
        )}
      </div>
    </div>
  );
}

This is the smallest version that still answers the product question: “Does the user know the request is in progress and can they cancel it?”

Why These Stages Exist

Four active stages are enough for a synchronous call:

  • submitting – the request is being prepared and sent

  • waiting – the network call is in flight and the model is working

  • complete – a usable result arrived

  • error – something failed and we have a message

I once shipped a feature that only toggled a spinner. Users could not tell whether the spinner meant “still working” or “stuck forever.” Adding an explicit “Model is working…” message and an elapsed-time counter cut support questions noticeably. The extra state was cheap; the clarity was not.

Cancellation Is Part of Progress

The AbortController lets the user stop a long-running call. On the client this is straightforward. On the server the request is simply abandoned; FastAPI and the OpenAI client will clean up when the connection drops. For a first version that is acceptable. If you later need guaranteed server-side cancellation you will add a job id and a cancel endpoint—only after measurement shows the need.

What Not to Do Yet

Do not add WebSockets or Server-Sent Events for a single synchronous call. Do not invent fake percentage progress based on token estimates unless you have measured that the estimate is actually useful. Do not hide the real finish reason or token count from the developer-facing UI; those numbers help you decide whether the feature is worth keeping.

Before adding an agent, see whether a deterministic workflow is enough. Before adding a queue, see whether the current latency is acceptable for the users you actually have. The extra complexity has to earn its place.

What Was Tested and What Remains Uncertain

I tested the component with short and medium inputs, forced network delays, deliberate cancellations, and simulated 502/504 responses from the backend. The stage transitions, elapsed-time display, and error messages behaved as expected.

I have not measured the effect of React Strict Mode double-mounting on the abort logic under production traffic, nor have I tested the component with very slow 3G network conditions. Those checks belong in later articles once real usage data exists. Exact CORS and base-URL configuration must still be verified for each deployment environment.

Wide-angle shot of an engineer testing network request cancellation and error states in a dim dev environment.

Practical Conclusion

Showing task progress in a Next.js AI application is mostly ordinary React state management with one extra requirement: the user should never be left staring at a silent screen while a model call is in flight. A few clear stages, an elapsed-time indicator, and a cancel button turn an opaque wait into a visible process.

Start with the smallest version that can answer the product question. In this case the question is “Does the user know the work is happening and can they stop it?” The component above is that version.

The model can take its time; your application still has to keep the human informed.

Build real applications. Verify every step.

Last updated:

Share:

Leave a comment

Related Articles

What to Verify Before Building with GPT-6.1 Sol
Build an AI Feature |

What to Verify Before Building with GPT-6.1 Sol

Before building production-facing applications with GPT-6.1 Sol, running a disciplined verification checklist is essential. This guide outlines critical pre-flight checks—confirming model availability, measuring context windows, testing structured outputs and tool calling, monitoring latency and costs, and evaluating error modes. Verifying these core capabilities beforehand prevents unexpected failures and ensures robust application performance under real-world usage conditions.

0
Build a Small GPT-6.1 Sol Summarization Endpoint
Build an AI Feature |

Build a Small GPT-6.1 Sol Summarization Endpoint

This article demonstrates how to build a production-ready summarization endpoint using FastAPI and the GPT-6.1 Sol model. It covers essential backend practices including input length validation, style constraints, hard timeouts, finish reason verification, and structured operational logging, providing a reliable foundation for adding safe AI features to your application architecture.

0
Add a Typed TypeScript Client for a FastAPI AI Endpoint
Build an AI Feature |

Add a Typed TypeScript Client for a FastAPI AI Endpoint

This article demonstrates how to build a robust, typed TypeScript client for a FastAPI AI summarization endpoint. It covers essential practices including request-response interface mirroring, client-side input validation, custom error classes with HTTP status handling, and runtime response shape checks, providing compile-time safety and clean contract boundaries for your frontend.

0