# useRemoteTurn (/docs/use-remote-turn)



`useRemoteTurn` runs a chat turn on your server and attaches the page
to it. The page sends the turn, re-attaches after a reload, answers
approvals and stops it. Closing the tab doesn't stop the turn.

This is the recommended browser path. You provide two things: the
[turn routes](#mount-the-turn-routes) on your server, and a session id.
No `HarnessProvider` is needed. An in-process `SessionRuntime`
(`HarnessProvider`, `useSessionRuntime`) is deprecated in the browser,
and stays supported for local, test and Electron-style hosts.

**Subpath:** `@pleach/core/react`

```tsx
import { useRemoteTurn } from "@pleach/core/react";
// or
import { useRemoteTurn } from "@pleach/react";
```

The hook lives in `@pleach/core/react`. `@pleach/react` re-exports the
same symbols, also from `@pleach/react/hooks/useRemoteTurn`. Neither
package has a real release yet: see
[Not on npm yet](/docs/install#not-on-npm-yet).

## Mount the turn routes [#mount-the-turn-routes]

`createPleachTurnRoutes` serves every path the hook calls. Point the
hook at its `basePath`.

```typescript
// app/api/harness/[...path]/route.ts (Next.js)
import { createPleachTurnRoutes } from "@pleach/core/server/turns";
import { authenticate, ownsSession } from "./your-auth";
import { runtime } from "./your-runtime"; // the server's SessionRuntime

const routes = createPleachTurnRoutes({
  runtime,
  basePath: "/api/harness",
  authorize: async ({ request, sessionId }) => {
    const user = await authenticate(request);
    return user && (await ownsSession(user.id, sessionId))
      ? { actorId: user.id }
      : { refuse: 404 };
  },
});

export const { GET, POST } = routes.nextRouteHandlers();
```

`routes.nodeHttp()` covers a bare node server or a Next.js Pages Router
API route, and `routes.fetch` covers any fetch-style host. `runtime` can
also be a function that returns the runtime serving a turn. One runtime
per chat is recommended.

`authorize` is required, because core does no auth. It runs first on
every request, and on execute it is the session-ownership check. Keep
`actorId` unique per person: it is the only thing that keeps one
caller's turns and approvals from another's. An `authorize` result can
also name a `tenantId`. Use an organization or an install for it, never
a user, because each tenant gets its own frame buffers and the number
kept is bounded.

`createPleachRoutes` won't work here. Its execute leg streams unnumbered
frames (SSE without `id:`, or NDJSON if negotiated), which this client
can't re-attach to.

## Send, stream, approve and stop [#send-stream-approve-and-stop]

```tsx
import { useRemoteTurn } from "@pleach/core/react";

// Render it once the session exists: the hook throws on an empty `sessionId`.
export function Chat({ sessionId }: { sessionId: string }) {
  const turn = useRemoteTurn({ baseUrl: "/api/harness", sessionId });

  return (
    <div>
      {turn.messages.map((m) => (
        <Bubble key={m.id} message={m} />
      ))}
      {turn.isStreaming && <p>{turn.streamingContent}</p>}
      {turn.pendingInterrupts.map((i) => (
        <button key={i.id} onClick={() => turn.answerInterrupt(i.id, { approved: true })}>
          Approve {i.toolCall.name}
        </button>
      ))}
      <Composer onSend={(text) => turn.send(text)} disabled={turn.isStreaming} />
      {turn.isStreaming && <button onClick={() => turn.stop()}>Stop</button>}
    </div>
  );
}
```

`stop()` is how the page stops a turn. An unmount, a reload or a dropped
connection only detaches the reader. The turn keeps running on the
server, and its approvals stay pending.

## Re-attach after a reload [#re-attach-after-a-reload]

Persist `turnId` while the turn runs, then call `attach` on the next
load. The server replays the turn from the start of its buffer, so
`pendingInterrupts` fills from the replay and `stop()` reaches the turn.

```tsx
import { useEffect } from "react";
import { useRemoteTurn } from "@pleach/core/react";

function useResumableTurn(sessionId: string) {
  const turn = useRemoteTurn({ baseUrl: "/api/harness", sessionId });
  const storageKey = `pleach:turn:${sessionId}`; // one persisted turn per session

  // After a reload, re-attach to the turn this session left running.
  useEffect(() => {
    const saved = sessionStorage.getItem(storageKey);
    if (saved) void turn.attach(saved);
  }, [storageKey]);

  // Persist the running turn's id; forget it once the turn has ended. On the render that
  // switches sessions, `turn.turnId` still names the earlier session's turn, while
  // `turn.source` is already this session's: write the id only when it is this source's turn.
  useEffect(() => {
    if (turn.isStreaming && turn.turnId) {
      if (turn.turnId === turn.source.turnId) sessionStorage.setItem(storageKey, turn.turnId);
    } else if (!turn.isStreaming) sessionStorage.removeItem(storageKey);
  }, [storageKey, turn.isStreaming, turn.turnId]);

  return turn;
}
```

Calling `attach` again for a turn the hook already reads opens no
second reader, so a dev StrictMode double mount attaches once.

A turn that has ended is still replayed while the server holds it. Once
the server no longer holds it, or its buffer no longer starts at the
first frame, `attach` ends with a typed error and `error` is set.
Rebuild that view from your durable events.

A turn whose stream was lost isn't running in the hook, so `stop()`
doesn't reach it. `attach` it first, then stop it. Its approvals stay
listed with their nonces, so a click still answers them.

## Switching sessions [#switching-sessions]

A new `sessionId` or `baseUrl` is a session switch, so `key={sessionId}`
is optional. The earlier session's reader hangs up and nothing is
stopped. `messages`, the live view, `turnId` and `pendingInterrupts`
clear. A turn already sent on the new session stays.

## Options [#options]

Pass a `source`, or a `baseUrl` and `sessionId` for the hook to build
one. It throws without either.

| Option                        | Type                        | Purpose                                                                                                                                 |
| ----------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `source`                      | `RemoteTurnSource \| null`  | A source you built. See [Build your own source](#build-your-own-source)                                                                 |
| `baseUrl`                     | `string`                    | Where the turn routes are mounted                                                                                                       |
| `sessionId`                   | `string`                    | The session the turns run in. Must be non-empty                                                                                         |
| `fetch`                       | `RemoteTurnFetch`           | Defaults to the global `fetch`. Read at each request                                                                                    |
| `headers`                     | `RemoteTurnHeaders`         | Sent on every request, such as a bearer token. An object, or a function that returns one. Read at each request                          |
| `reattach`                    | `RemoteTurnReattachOptions` | Backoff for a dropped stream. Read when the source is built                                                                             |
| `holdAnswerUntilTurnComplete` | `AnswerHoldOption`          | Hold the answer until the turn ends. See [Holding the answer](/docs/fabrication-detection#holding-the-answer-until-the-guards-have-run) |

`reattach` takes `maxAttempts` (default 5 per drop, `0` turns re-attach
off), `baseDelayMs` (default 250, doubling per attempt) and `maxDelayMs`
(default 4000).

## Return value [#return-value]

| Field               | Type                                                        | Meaning                                                                        |
| ------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------ |
| `send`              | `(content: string) => Promise<void>`                        | Run a turn on the server                                                       |
| `attach`            | `(turnId: string) => Promise<void>`                         | Re-attach to a turn by its id                                                  |
| `stop`              | `() => void`                                                | Stop the running turns, each by its id, through the stop route                 |
| `answerInterrupt`   | `(interruptId: string, decision: ApprovalDecision) => void` | Answer an approval through the interrupt route, with the turn's one-time nonce |
| `pendingInterrupts` | `PendingInterrupt[]`                                        | Approvals waiting on an answer                                                 |
| `turnId`            | `string \| null`                                            | The turn in view, once a frame named it. Persist this to re-attach             |
| `source`            | `RemoteTurnSource`                                          | The source the hook drives                                                     |
| `messages`          | `Message[]`                                                 | The transcript                                                                 |
| `isStreaming`       | `boolean`                                                   | A turn is running in this hook                                                 |
| `streamingContent`  | `string`                                                    | Text of the in-flight turn                                                     |
| `isProvisional`     | `boolean`                                                   | `streamingContent` is a replaceable draft, not the answer                      |
| `thinkingContent`   | `string`                                                    | Reasoning text of the in-flight turn                                           |
| `parts`             | `readonly StreamMessagePart[]`                              | The in-flight message's parts; empty once the turn settles                     |
| `settledParts`      | `readonly StreamMessagePart[] \| null`                      | The settled message's parts                                                    |
| `toolOutput`        | `Record<string, string>`                                    | Progress output per `toolCallId`                                               |
| `batchProgress`     | `HarnessBatchProgress \| null`                              | The latest batch progress                                                      |
| `error`             | `Error \| null`                                             | The turn's error, including a lost stream                                      |

The live-view fields match [`useHarness`](/docs/react#useharness), which
the hook wraps.

## Limits [#limits]

The server sets these bounds, on `createPleachTurnRoutes`.

**A detached turn runs until it ends or hits its deadline.** Nobody has
to be reading. If your host can't run a turn to its end, set
`turnDeadline`, the only bound on a detached turn. Bind `keepAlive` to
the platform's `waitUntil` on a host that freezes a function once its
response is sent.

**A detached approval waits 15 minutes.** While a turn waits at an
approval and no client reads its stream, the `detachedApprovalWindowMs`
timer runs (default `900000`, `0` disables it). A reader that re-attaches
or an answer disarms it. When it fires, each pending approval is declined
by policy with code `detached_approval_window`, and the turn goes on.
The durable record is `kind: "no_answer"` with `decided_by: "policy"`
and `policy_code: "detached_approval_window"`: a policy settled it, not
the user's rejection.
With a client reading, an approval is never declined this way, however
long it waits.

**That window is an in-process timer.** A frozen function's window never
fires. On serverless, keep `keepAlive` running for at least the window,
or run your own reaper for stale approvals. Set `turnDeadline` below the
platform's maximum duration too, because the deadline caps the window.

**A settled turn is held for 5 minutes**, per server instance
(`turnStreamRetention.settledTtlMs`). After that, `attach` ends with the
typed error.

**Turns live on one instance.** A turn's frames and paused approvals
stay in the process running it, so stop, re-attach and approvals must
reach that instance. Use sticky routing by session. On a multi-instance
host, use `turnControl` for stops and approval answers and
`turnEventLog` for re-attach from another instance.

**Cross-origin hosts must allow two headers.** The client sends
`x-pleach-on-disconnect` and `last-event-id`, so list both in
`Access-Control-Allow-Headers`. Name your allowed origins rather than
using `*` on routes that accept credentials.

## Build your own source [#build-your-own-source]

`createRemoteTurnSource` is the client under the hook. Build one when
you want options the hook doesn't pass through, such as `autoContinue`
or `shouldContinue`.

```tsx
import { createRemoteTurnSource } from "@pleach/core/client";
import { useRemoteTurn } from "@pleach/core/react";

const source = createRemoteTurnSource({
  baseUrl: "/api/harness",
  sessionId: "session-1",
  autoContinue: false, // end at a park; continue it yourself with source.continue(token)
});

function Chat() {
  const turn = useRemoteTurn({ source });
  // ...
}
```

The source re-attaches when a connection drops, and continues a turn the
server parked for its deadline. A gap ends the iteration with an error
event, which `isRemoteTurnErrorEvent` from `@pleach/core/client`
identifies.

### Retrying a refused continue [#retrying-a-refused-continue]

A refused continue ends the iteration with a `continue-refused` error by default. Pass `continueRetry` to post it again. It applies to every continue the source posts, from `autoContinue` and from `source.continue(token)` alike.

```tsx
import { createRemoteTurnSource } from "@pleach/core/client";
import type { RemoteContinueRefusal } from "@pleach/core/client";

const source = createRemoteTurnSource({
  baseUrl: "/api/harness",
  sessionId: "session-1",
  continueRetry: (refusal: RemoteContinueRefusal, retries, waitedMs) => {
    if (refusal.status !== 409 || waitedMs > 60_000) return null; // give up
    return (refusal.retryAfterSeconds ?? 1) * 1000; // wait, then post again
  },
});
```

The callback receives the refusal, the retries already made for this park, and the milliseconds since its first refusal. Return a wait in milliseconds to post again. Return `null`, or any value that isn't a finite number of 0 or more, to end with `continue-refused`. A refusal carries `status`, `body` and `retryAfterSeconds`, which is the `Retry-After` header when it's a whole number of seconds, else `null`. An abort ends a wait. A Stop during a wait ends it at once and the source reads the cancelled turn's closing frames. The callback isn't asked once a Stop was requested.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="React" href="/docs/react" description="The rest of the hook surface, including useHarness and the primitives." />

  <Card title="Interrupts" href="/docs/interrupts" description="What an approval decision carries and how it is recorded." />

  <Card title="HarnessServer" href="/docs/server" description="The server handlers and route family behind these hooks." />
</Cards>
