Skip to Content
Runlane
ReferenceApplication API

React

Look up RunlaneProvider, useRun, useRunStream, stream modes, retention, and reader lifetime.

This page lists the exact behavior of @runlane/react. For examples, see the React hooks guides.

Install @runlane/react with @runlane/realtime. React is a peer dependency with the range ^19.0.0. Import the provider, the hooks, and their types from @runlane/react. It also re-exports the type-only frontend type helpers, including RunTypes.

An app that does not import this package gets no React dependency and no extra runtime work.

RunlaneProvider

The provider shares one client with the hooks below it. Its props are the createRunlaneClient options plus children.

PropMeaning
baseUrlRequired. A relative URL resolves against the page's URL. An absolute URL can point to another origin.
refreshAccessTokenOptional. Returns a fresh token for a run.
fetchOptional. A custom fetch function.
telemetry, onTelemetryErrorOptional client telemetry
import type { ReactNode } from 'react'

import { RunlaneProvider } from '@runlane/react'

import { fetchToken } from './tokens'

export function ProgressProvider({ children }: { children: ReactNode }) {
  return (
    <RunlaneProvider baseUrl="/api/progress" refreshAccessToken={({ runId, signal }) => fetchToken(runId, signal)}>
      {children}
    </RunlaneProvider>
  )
}
  • The provider creates one client for each baseUrl and fetch pair.
  • It always calls the newest refreshAccessToken, telemetry, and onTelemetryError without replacing readers. Inline functions are fine.
  • Each hook still opens its own reader, even when hooks share a client.
  • Pass client to a hook to use another client for that hook only.
  • A hook with no provider and no client throws a RunlaneError with configuration_invalid during render. The message describes both fixes.
  • Readers start after React commits the component. During server rendering, hooks return empty, disconnected state. They make no network requests and do not call refreshAccessToken.

useRun

useRun<TTask = undefined>(runId, options?): UseRunResult<TTask>

runId can be a plain string, a branded RunId, or undefined. undefined opens no reader.

import { useRun } from '@runlane/react'

import type { writeAnswer } from './tasks/write-answer'

const { run, error, isConnected, stop } = useRun<typeof writeAnswer>(runId, {
  accessToken,
  onComplete(run, error) {
    if (error) reportReadFailure(error)
    else showResult(run?.output)
  },
})
OptionMeaning
accessTokenToken for the first connection. See tokens.
enabledDefaults to true. When false, opens nothing and returns empty state.
onCompleteCalled once per reader: on a terminal status with (run), or on a read failure with (run, error). run can be undefined if reading fails before the snapshot.
onConnectionChangeReceives the client's connecting, open, reconnecting, and closed changes
throttleA positive DurationString. Groups updates into one render at the end of each window. Defaults to contractDefaults.realtime.renderThrottle.
clientA RunlaneClient to use instead of the provider's. Keep it stable across renders.

It returns { run, error, isConnected, stop }. run is undefined until the snapshot arrives. One reducer applies the snapshot, status changes, and top-level metadata patches in the order they arrive.

useRun subscribes with client.subscribe(runId, { streams: false }), so its connection carries no stream records. Use useRunStream for stream data. If a custom client still yields a stream record, the reducer ignores it and does not re-render.

RunRealtimeState

run has the type RunRealtimeState<TTask>:

FieldMeaning
id, environment, taskIdThe run, its environment, and its registered task, from the snapshot
statusThe newest RunStatus. A failed task is still run data.
attemptsStarted attempts, from snapshot counters or a status change
eventSequenceThe last status or metadata sequence. Stream positions are separate.
versionThe code version that started the run, when known
outputThe permitted final output, typed RunOutput<TTask> | undefined. Separate from stream parts.
failureThe permitted failure summary. A status change without a failure clears it.
metaThe permitted RunMeta<TTask>, or undefined. A patch replaces top-level keys. A nested object replaces the old value. null stays null.

Types:

  • Without a type argument, output is JsonValue | undefined and meta is JsonObject | undefined.
  • A task's output uses the output schema's input type: the stored handler return, before transforms or defaults.
  • Stream parts use the stream schema's parsed output type.
  • RunTypes declares the JSON the server sends for output, metadata, and streams, with no backend import. Interfaces and type aliases both work, with no index signature. It does not check that the types are valid JSON. The server owns validation.

onComplete:

  • receives the final state, even if a render is still pending;
  • on a terminal task failure, receives run data and no error;
  • never runs after stop(), unmount, or reader replacement;
  • always uses the newest committed callback.

useRunStream

useRunStream<TTask = undefined, TName extends RunStreamName<TTask> = RunStreamName<TTask>>(
  runId,
  name,
  options?,
): UseRunStreamResult<RunStreamPart<TTask, TName>>

The hook reads saved parts, then follows new ones, through one client.readStream() reader. Reconnects do not repeat parts. The client tracks the resume point; the hook never mixes cursors from different readers.

import { useRunStream } from '@runlane/react'

import type { writeAnswer } from './tasks/write-answer'

const { parts, attempts, error, isConnected, truncated, stop } = useRunStream<typeof writeAnswer>(runId, 'answer', {
  accessToken,
})
const text = parts.join('')

The task declares stream schemas, and the server validates each part when it is written. The hook takes no schema and does not transform parts. TTask types the names and parts. Without a type argument, names are string and parts are JsonValue. When a task has several part types, pass TName as the second type argument for an exact type. Otherwise parts are a union.

OptionMeaning
accessToken, enabled, onConnectionChange, throttle, clientSame as useRun
modeA RunStreamMode. Defaults to RunStreamMode.Latest.
maxPartsMost parts, and most attempt entries, to keep. A positive safe integer. Defaults to contractDefaults.realtime.clientMaxParts, up to contractDefaults.realtime.clientMaxPartsLimit.
onDataCalled for every part, in order, without throttling. Uses the newest callback.

It returns { parts, attempts, error, isConnected, truncated, stop }:

FieldMeaning
partsRead-only parts of the current (last) attempt, typed RunStreamPart<TTask, TName>
attemptsRead-only list of { attempt, parts, closeReason? }, one per kept attempt. closeReason is a RunStreamCloseReason once that attempt closes.
truncatedtrue once any part or attempt was dropped. It stays true for that reader, even after a new attempt resets parts.
error, isConnected, stopSame as useRun

RunStreamMode

MemberBehavior
LatestA new attempt replaces the history. attempts has at most one entry, so retries never join two answers.
AllKeeps earlier attempts within the maxParts limit. Read attempts to show the history.

Retention

maxParts limits both the total number of parts and the number of attempt entries, including empty attempts.

  • When there are too many attempt entries, the oldest attempts go first. The current attempt is always kept.
  • Within the kept attempts, the oldest parts go first. An old attempt that loses all its parts is removed.
  • Attempt starts and closes do not count as parts.
  • Any removal sets truncated.
  • An invalid maxParts throws configuration_invalid during render, before a reader opens.

See React contract values and defaults for the values.

Rendering, errors, and stopping

Rendering. Updates render at most once per throttle window, at the end of the window. A terminal status, reader close, error, stop(), and unmount render pending state at once. onData runs for every part even while a render waits. An invalid throttle throws configuration_invalid during render.

Errors. Both hooks return error as RunlaneError | undefined:

  • Invalid reader input reports validation_failed or run_cursor_invalid.
  • Transport failures keep the client's structured error.
  • Unexpected reader or callback failures become internal_error with a safe message, and the original as cause. Do not show cause to users.

isConnected turns true only after the client reports RealtimeConnectionState.Open. Connecting, reconnecting, closed, an error, and stop() set it to false. Receiving data does not change it. A normal close keeps the final data and leaves error empty.

stop() keeps the same identity across renders, even when the reader is replaced. It aborts the current reader, renders and keeps its last state, and sets isConnected to false. It never cancels the run. A later change to the reader's identity can open a new reader.

Reader lifetime

ChangeOpens a new reader and clears state?
runId, enabled, or the resolved clientYes. An undefined runId opens nothing.
Stream name, mode, or maxPartsYes
Provider baseUrl or fetchYes, for hooks that use that provider's client
accessTokenNo. It is used only for the first connection of a new reader.
throttleNo. New render windows use the new duration.
onComplete, onData, or onConnectionChangeNo. Calls use the newest committed callback.
Provider refreshAccessToken, telemetry, or onTelemetryErrorNo. Calls use the newest committed props.

Unmounting aborts the reader. Late data, errors, and connection changes from an aborted reader cannot update its replacement. This also holds for Strict Mode and for Activity hide and show cycles.

Tokens

The hooks follow the client's token rule:

  • The first connection uses accessToken. Without it, the client calls refreshAccessToken. With neither, it connects without a bearer token, for cookie-only authorization.
  • Network reconnects and server rotations reuse the current token.
  • A 403 allows one refresh. Another 403 before a successful connection ends the reader.
  • A plain error from refreshAccessToken retries with backoff while the failure budget lasts. A RunlaneError retries only with retryable: true. Otherwise it ends the reader.
  • Changing a hook's accessToken does not change the token of a reader that is already open.

On this page