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.
| Prop | Meaning |
|---|---|
baseUrl | Required. A relative URL resolves against the page's URL. An absolute URL can point to another origin. |
refreshAccessToken | Optional. Returns a fresh token for a run. |
fetch | Optional. A custom fetch function. |
telemetry, onTelemetryError | Optional 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
baseUrlandfetchpair. - It always calls the newest
refreshAccessToken,telemetry, andonTelemetryErrorwithout replacing readers. Inline functions are fine. - Each hook still opens its own reader, even when hooks share a client.
- Pass
clientto a hook to use another client for that hook only. - A hook with no provider and no
clientthrows aRunlaneErrorwithconfiguration_invalidduring 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)
},
})| Option | Meaning |
|---|---|
accessToken | Token for the first connection. See tokens. |
enabled | Defaults to true. When false, opens nothing and returns empty state. |
onComplete | Called 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. |
onConnectionChange | Receives the client's connecting, open, reconnecting, and closed changes |
throttle | A positive DurationString. Groups updates into one render at the end of each window. Defaults to contractDefaults.realtime.renderThrottle. |
client | A 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>:
| Field | Meaning |
|---|---|
id, environment, taskId | The run, its environment, and its registered task, from the snapshot |
status | The newest RunStatus. A failed task is still run data. |
attempts | Started attempts, from snapshot counters or a status change |
eventSequence | The last status or metadata sequence. Stream positions are separate. |
version | The code version that started the run, when known |
output | The permitted final output, typed RunOutput<TTask> | undefined. Separate from stream parts. |
failure | The permitted failure summary. A status change without a failure clears it. |
meta | The 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,
outputisJsonValue | undefinedandmetaisJsonObject | undefined. - A task's
outputuses the output schema's input type: the stored handler return, before transforms or defaults. - Stream parts use the stream schema's parsed output type.
RunTypesdeclares 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.
| Option | Meaning |
|---|---|
accessToken, enabled, onConnectionChange, throttle, client | Same as useRun |
mode | A RunStreamMode. Defaults to RunStreamMode.Latest. |
maxParts | Most parts, and most attempt entries, to keep. A positive safe integer. Defaults to contractDefaults.realtime.clientMaxParts, up to contractDefaults.realtime.clientMaxPartsLimit. |
onData | Called for every part, in order, without throttling. Uses the newest callback. |
It returns { parts, attempts, error, isConnected, truncated, stop }:
| Field | Meaning |
|---|---|
parts | Read-only parts of the current (last) attempt, typed RunStreamPart<TTask, TName> |
attempts | Read-only list of { attempt, parts, closeReason? }, one per kept attempt. closeReason is a RunStreamCloseReason once that attempt closes. |
truncated | true once any part or attempt was dropped. It stays true for that reader, even after a new attempt resets parts. |
error, isConnected, stop | Same as useRun |
RunStreamMode
| Member | Behavior |
|---|---|
Latest | A new attempt replaces the history. attempts has at most one entry, so retries never join two answers. |
All | Keeps 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
maxPartsthrowsconfiguration_invalidduring 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_failedorrun_cursor_invalid. - Transport failures keep the client's structured error.
- Unexpected reader or callback failures become
internal_errorwith a safe message, and the original ascause. Do not showcauseto 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
| Change | Opens a new reader and clears state? |
|---|---|
runId, enabled, or the resolved client | Yes. An undefined runId opens nothing. |
Stream name, mode, or maxParts | Yes |
Provider baseUrl or fetch | Yes, for hooks that use that provider's client |
accessToken | No. It is used only for the first connection of a new reader. |
throttle | No. New render windows use the new duration. |
onComplete, onData, or onConnectionChange | No. Calls use the newest committed callback. |
Provider refreshAccessToken, telemetry, or onTelemetryError | No. 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 callsrefreshAccessToken. With neither, it connects without a bearer token, for cookie-only authorization. - Network reconnects and server rotations reuse the current token.
- A
403allows one refresh. Another403before a successful connection ends the reader. - A plain error from
refreshAccessTokenretries with backoff while the failure budget lasts. ARunlaneErrorretries only withretryable: true. Otherwise it ends the reader. - Changing a hook's
accessTokendoes not change the token of a reader that is already open.