# React (/docs/react)



The canopy — what your visitors see and touch. The React surface
ships as two layered packages.

> **Frontend integration is a thematic island.** Five wiring
> surfaces (`react`, `server`, `api-routes`, `query`, `devtools`)
> — not a three-concept cluster. See [What lives outside the
> cluster pattern](/docs/concept-clusters#what-lives-outside-the-cluster-pattern).

| Package              | Role                                                                                                                                                                | Status                                                                                                                       |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `@pleach/react`      | Lower-level primitive hooks — runtime acquisition, message stream, event log, interrupt UI. The building blocks the higher-level facades compose internally.        | `0.1.0` in source · not on npm yet · FSL-1.1-Apache-2.0                                                                      |
| `@pleach/core/react` | Higher-level facade — `HarnessProvider`, `useHarness`, sessions, tools, sync, team, compliance, devtools. Composes the primitives into one-call-fits-most surfaces. | Back-compat shim; each `@pleach/core/react/*` module re-exports from `@pleach/react/legacy`. Shims retire at a future major. |

Use the facade when you're building a typical chat UI and want
batteries included. Drop down to the primitives when you need
to own the runtime lifecycle, the stream state machine, or the
interrupt-UI routing yourself — for example, when embedding
inside an existing app framework that already owns React tree
state.

`@pleach/react` is a real implementation, `0.1.0` in source
([not on npm yet](/docs/install#not-on-npm-yet)), under FSL-1.1-Apache-2.0 with a stable public surface. Pin
it exactly — `^0.1.0` will **not** pick up the non-caretable
`0.1.x → 1.0.0` jump (nor the `0.0.x → 0.1.0` one), matching the
pin-exact policy on the [Packages](/docs/packages) status table.

## 30-second start [#30-second-start]

Install the package alongside its peers:

```bash
npm install @pleach/react @pleach/core react react-dom
```

Acquire a runtime, then drive a turn:

```tsx
import { useState } from "react";
import { useSessionRuntime, useSessionMessageStream } from "@pleach/react";
import { createPleachRuntime } from "@pleach/core/runtime";

function Chat() {
  const { runtime, sessionId } = useSessionRuntime({
    buildRuntime: () => createPleachRuntime({ /* config */ }),
    initSession: async (rt) => rt.sessions.create(),
  });

  const { streamMessage, isStreaming } = useSessionMessageStream({
    runtime,
    sessionId,
    onEvent: (event, ctx) => {
      // optional intercept — return { handled: true } to short-circuit.
      // `ctx.accumulator` carries the post-append streaming buffer.
    },
  });

  const [input, setInput] = useState("");

  return (
    <form onSubmit={(e) => { e.preventDefault(); streamMessage({ content: input }); }}>
      <input value={input} onChange={(e) => setInput((e.target as unknown as { value: string }).value)} disabled={isStreaming} />
      {/* render the accumulator via your onEvent reducer; gate UI on isStreaming */}
    </form>
  );
}
```

`@pleach/react` does NOT ship a provider — `useSessionRuntime` owns the construct-once / cleanup-on-unmount lifecycle behind a ref, and `useSessionMessageStream` takes a single config object whose `runtime` + `sessionId` are nullable until `useSessionRuntime` resolves. Drop down to a context-based provider only when you need the legacy `@pleach/react/legacy` `HarnessProvider` facade (re-export shim for `@pleach/core/react/*`). See the [Primitives](#primitives-pleachreact) and [Facade](#facade-pleachcorereact) sections below; the [`@pleach/react` README](https://www.getpleach.com/docs/react) is the canonical surface reference.

## Peer dependency contract [#peer-dependency-contract]

`@pleach/react` declares `react` and `react-dom` as **peer** dependencies, not dependencies. Install them explicitly in the consumer app. Two copies of React in one bundle break hook calls at runtime — the peer-dep boundary is what keeps that from happening silently.

`@pleach/core` is also a peer. The hooks call into the core runtime directly, so the consumer app owns the core install and pins it to a version range the package supports. Mismatched cores produce type-level drift today and runtime drift once the wire shape evolves.

Peer-dep ranges tighten at minor bumps. Pin `@pleach/react` to an exact version in consumer apps, as above, then re-verify the declared peer ranges each time you bump it — the [Packages](/docs/packages) status table tracks current ranges per release.

### Standalone `@pleach/core` install is safe [#standalone-pleachcore-install-is-safe]

The peer-dep relationship is one-directional. `@pleach/react`
declares `@pleach/core` as a peer — the hooks call into the
core runtime, so the consumer pins core. The reverse isn't
true: `@pleach/core` can be installed without `@pleach/react`.

Server-only consumers (background workers, evaluation harnesses,
CLI tools) routinely install just `@pleach/core` and never touch
the React surface. `import "@pleach/core"` loads cleanly with
no React peer present.

The React hooks remain available at the `@pleach/core/react`
subpath. Consumers who want hooks import from that subpath and
install the `@pleach/react` peer explicitly:

```bash
# Server-only — no React peer needed
npm install @pleach/core

# UI consumer — install the peer
npm install @pleach/core @pleach/react react react-dom
```

## Surface at a glance [#surface-at-a-glance]

```typescript
// Primitives — @pleach/react (0.1.0)
import { useSessionRuntime }       from "@pleach/react/hooks/useSessionRuntime";
import { useSessionMessageStream } from "@pleach/react/hooks/useSessionMessageStream";
import { useEventLog }             from "@pleach/react/hooks/useEventLog";
import { useInterruptUI }          from "@pleach/react/hooks/useInterruptUI";
import { useRemoteTurn }           from "@pleach/react/hooks/useRemoteTurn";
import { createCorrectionDedup }   from "@pleach/react/utils/correctionDedup";
import { createStreamLock }        from "@pleach/react/utils/streamLock";

// Facade — @pleach/core/react (1.x with back-compat shim)
import {
  HarnessProvider,
  useHarness,
  useRemoteTurn,
  useHarnessContext,
  useRuntime,
  useIsEnterpriseEnabled,
  useSessionList,
  useSessionCheckpoints,
  useTools,
  useToolsByCategory,
  useTool,
  useToolValidation,
  useSyncStatus,
  useIsSynced,
  usePendingChanges,
  useTeam,
  useCompliance,
  useHarnessDevTools,
  updateDevToolsSession,
  createCorrectionDedup,
  createDefaultCorrectionDedup,
} from "@pleach/core/react";
```

**Subpath:** `@pleach/react` · **Source:** [src/](<https://www.getpleach.com/docs/react>)

## Primitives: `@pleach/react` [#primitives-pleachreact]

Five hooks plus two utils. Each one owns one substrate concern.

### `useSessionRuntime` [#usesessionruntime]

Constructs the runtime exactly once on mount, optionally binds a
session, and exposes a `ready` promise. The factory is **not**
re-invoked across renders — swap the runtime by unmounting and
remounting the owner.

```tsx
const { runtime, sessionId, ready } = useSessionRuntime({
  buildRuntime: () =>
    new SessionRuntime({
      storage: new IndexedDBAdapter({ databaseName: "pleach" }),
      tenantId,
    }),
  initSession: async (rt) => (await rt.createSession()).id,
  onError: (err) => reportToSentry(err),
});

// runtime + sessionId are null until the mount effect commits.
// `ready` resolves when both are live.
```

| Field       | Type                     | Notes                                                       |
| ----------- | ------------------------ | ----------------------------------------------------------- |
| `runtime`   | `SessionRuntime \| null` | `null` until first commit; stable identity after            |
| `sessionId` | `string \| null`         | Result of `initSession`; `null` permanently when omitted    |
| `extras`    | `TExtras \| null`        | Side artifacts when `buildRuntime` returns a wrapped result |
| `ready`     | `Promise<void>`          | Resolves after construct + bind; rejects on either failure  |

### `useSessionMessageStream` [#usesessionmessagestream]

Fires one turn at a time against the active runtime/session,
serializing concurrent calls through a per-component stream
lock. The hook drives the message-state machine; the consumer
owns the UI reduction via `onEvent`. The lock is client-side; the
runtime itself also runs [one turn at a time](/docs/session-runtime#one-turn-at-a-time-per-runtime)
across all of its sessions.

```tsx
const {
  streamMessage,
  abort,
  isStreaming,
  isReasoning,
  reasoningText,
} = useSessionMessageStream({
  runtime,
  sessionId,
  onEvent:        (event, ctx) => dispatch({ type: "STREAM_EVENT", event }),
  onTurnComplete: (ctx)        => track("turn.complete", { events: ctx.events.length }),
  onError:        (err)        => dispatch({ type: "STREAM_ERROR", err }),
});

await streamMessage({ content: "Hello" });
```

`streamMessage` resolves cleanly whether the turn returned or
aborted; errors route through `onError`, so a straight-line
`await` works without per-call `try/catch`. `abort()` cancels
the in-flight stream without firing `onError` — aborts are the
explicit cancellation path.

**Reasoning traces.** `isReasoning` is `true` while a reasoning
model streams its chain-of-thought (the `reasoning.delta`
[events](/docs/stream-events#reasoning-traces-reasoningdelta))
before the answer begins; it flips back to `false` on the first
answer delta. `reasoningText` accumulates that chain-of-thought
for the current turn — never answer content — and is retained
after the answer starts so you can render a collapsible
"thinking" disclosure. Both reset at the next turn:

```tsx
{isReasoning && <Spinner label="Thinking…" />}
{reasoningText && (
  <details>
    <summary>Thought process</summary>
    <pre>{reasoningText}</pre>
  </details>
)}
```

`content.reset` events are deduped inside a 200ms window by
default; tune via `dedupeWindowMs`. The stream-lock drain
timeout defaults to 120s; tune via `streamLockTimeoutMs`.

**Message parts.** `ctx.parts` is the in-flight message's parts: text
per lane, reasoning, and one tool part per call. It empties when the
turn's terminal `message.complete` lands. From then on
`ctx.settledParts` is the settled message's parts, including the tool
parts of the calls that started, and its answer text follows any
correction that lands after the terminal. It is `null` before the
terminal. Render the settled message's tool calls from it.

**Holding the answer.** `holdAnswerUntilTurnComplete: true` keeps the
answer out of the `TurnContext` until the turn ends. While held,
`ctx.accumulator`, `ctx.provisional` and `ctx.visibleText` are empty,
`ctx.parts` and `ctx.settledParts` carry no answer or draft text, and
`ctx.answerHeld` is `true`. From the release on, `ctx.visibleText` is the reconciled
reply, with corrections and resets applied. `onAnswerReleased(ctx)`
fires exactly once per user turn with that released context: on
`turn.completed`, an `error` event, the stream ending, a Stop or a
throw. On a Stop or a throw it is the only callback that carries the
text to paint, and that text may be the uncorrected partial. Events
still reach `onEvent` as they arrive, so paint from `ctx.visibleText`,
not from raw `message.delta` payloads. See
[Fabrication detection § Holding the answer](/docs/fabrication-detection#holding-the-answer-until-the-guards-have-run).

### `useEventLog` [#useeventlog]

A facade over a caller-owned `EventLogClient`. Returns a stable
`log(event)` callback you can pass through memo deps without
invalidating downstream callbacks every render.

```tsx
const { log, flush } = useEventLog({
  client: eventLogClient,         // or `clientRef: { current: ... }` for
                                  // refs constructed inside a `useEffect`
  onEvent: (e) => devtools.push(e),
});

log({ type: "ui.bubble.copied", messageId });
await flush();   // best-effort drain before unmount
```

Pass `client: null` while the client is being constructed —
`log` / `flush` no-op gracefully. The `clientRef` overload is
the path when construction happens inside `useEffect` and the
component doesn't re-render on the `null → populated`
transition.

### `useInterruptUI` [#useinterruptui]

Subscribes to the runtime's interrupt stream and routes each
`PendingInterrupt` to the matching plugin-contributed handler.
Plugins contribute handlers via
`pluginManager.collectInterruptUIHandlers()`; the first handler
whose `interruptType` matches wins.

```tsx
const { activeInterrupts, renderActive, resolveInterrupt, cancelInterrupt } =
  useInterruptUI({
    runtime,
    handlers: pluginManager.collectInterruptUIHandlers(),
    onInterrupt: (i)  => track("interrupt.shown", { type: i.toolCall?.name }),
    onResolve:   (id, decision) => eventLog.log({ type: "interrupt.resolved", id, decision }),
    onCancel:    (id) => eventLog.log({ type: "interrupt.cancelled", id }),
    onTimeout:   (id) => eventLog.log({ type: "interrupt.timeout", id }),
  });

return <>{renderActive()}</>;
```

The hook accepts `runtime: null` and no-ops until a runtime
arrives — pair it with `useSessionRuntime` without ordering
gymnastics.

### `useRemoteTurn` [#useremoteturn]

The browser hook for turns that run on your server: send, re-attach
after a reload, answer approvals, Stop. It needs no `HarnessProvider`,
and `@pleach/core/react` exports it too. See
[useRemoteTurn](/docs/use-remote-turn).

### Internal-but-exposed helpers [#internal-but-exposed-helpers]

`applyRoutingScaffoldCase` and `isWrappedBuildResult` are exported from the top-level `@pleach/react` barrel and from `@pleach/react/hooks` (9 exports there total) because existing host code depends on them. They are NOT part of the supported consumer API: shape may change in any 1.x minor release. Consumers building against the public surface should reach for `useSessionMessageStream` (which wraps both) rather than the raw helpers.

### Utils [#utils]

| Util                    | Signature                                                    | Use case                                                                                                                                                                                                                                                                                                                                                                |
| ----------------------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `createCorrectionDedup` | `(config) => (ts, lastTs, lastReason, newReason) => boolean` | Factory returning a predicate over **correction reasons + timestamps** (NOT content payloads). Allows when (a) outside the `windowMs` window, OR (b) the new reason has strictly higher priority than the previous reason per `priorityMap`. `createDefaultCorrectionDedup(windowMs?)` is a convenience baseline that dedupes only same-reason emits inside the window. |
| `createStreamLock`      | `() => { acquire, waitForDrain, isHeld }`                    | Factory returning a single-slot async mutex. `acquire()` returns a `{ release }` handle; `waitForDrain(timeoutMs?)` returns `{ timedOut }`; `isHeld()` is a synchronous diagnostic. Use when composing a bespoke streaming surface that wants the same drain semantics `useSessionMessageStream` uses internally.                                                       |

### Composing the primitives [#composing-the-primitives]

The three primary hooks work together — `useSessionRuntime`
owns the lifecycle, `useSessionMessageStream` owns the turn,
`useInterruptUI` owns the human-in-the-loop:

```tsx
function Chat({ tenantId }: { tenantId: string }) {
  const { runtime, sessionId } = useSessionRuntime({
    buildRuntime: () =>
      new SessionRuntime({
        storage: new IndexedDBAdapter({ databaseName: "pleach" }),
        tenantId,
      }),
    initSession: async (rt) => (await rt.createSession()).id,
  });

  const [messages, setMessages] = useState<Message[]>([]);

  const { streamMessage, isStreaming } = useSessionMessageStream({
    runtime,
    sessionId,
    onEvent: (e) => setMessages((prev) => reduceMessage(prev, e)),
  });

  const { renderActive } = useInterruptUI({
    runtime,
    handlers: interruptHandlers,
  });

  return (
    <>
      <Transcript messages={messages} />
      {renderActive()}
      <Composer
        disabled={isStreaming}
        onSend={(text) => streamMessage({ content: text })}
      />
    </>
  );
}
```

No provider, no global state — each component owns its own
runtime. Pair with a parent component that holds the runtime in
context when multiple children need to share it. Children sharing
one runtime share its turn queue, so their turns run one at a time.

## Facade: `@pleach/core/react` [#facade-pleachcorereact]

One provider mounted near the root, plus a set of focused hooks
that compose the primitives above into the typical chat-UI
surface. Hooks return stable references — safe to destructure
at the top of a component.

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

### `HarnessProvider` [#harnessprovider]

Mounts the runtime into the React tree. Every hook below requires
it as an ancestor.

```tsx
// app/page.tsx
'use client';

import { SessionRuntime, AiSdkProvider } from "@pleach/core";
import { IndexedDBAdapter } from "@pleach/core/sessions";
import { HarnessProvider } from "@pleach/core/react";
import { createOpenRouter } from "@openrouter/ai-sdk-provider";

const openrouter = createOpenRouter({ apiKey: process.env.NEXT_PUBLIC_OPENROUTER_API_KEY! });

const runtime = new SessionRuntime({
  storage:  new IndexedDBAdapter({ databaseName: "pleach" }),
  provider: new AiSdkProvider({
    model:    openrouter("anthropic/claude-sonnet-4-5"),
    maxSteps: 5,
  }),
  userId:   "user_123",
});

export function App() {
  return (
    <HarnessProvider runtime={runtime}>
      <Chat />
    </HarnessProvider>
  );
}
```

Construct the runtime once outside the React render tree (or
inside a `useMemo` with stable deps) so it isn't re-created per
render.

### Low-level escape hatches [#low-level-escape-hatches]

| Hook                       | Returns                   | Use when                                |
| -------------------------- | ------------------------- | --------------------------------------- |
| `useHarnessContext()`      | Raw context value         | Building custom hooks                   |
| `useRuntime()`             | The bare `SessionRuntime` | Imperative calls that don't have a hook |
| `useIsEnterpriseEnabled()` | `boolean`                 | Gating extension-only UI                |

Prefer the higher-level hooks below for typical UI work.

### `useHarness` [#useharness]

The primary chat hook. Returns messages, send / create / abort
helpers, and a `SyncStatus`.

```tsx
function Chat() {
  const {
    messages,
    sendMessage,
    createSession,
    abort,
    isStreaming,
    syncStatus,
    session,
  } = useHarness();

  return (
    <div>
      {messages.map((m) => (
        <Bubble key={m.id} message={m} />
      ))}
      <Composer
        onSend={(text) => sendMessage(text)}
        disabled={isStreaming}
      />
      {isStreaming && <button onClick={abort}>Stop</button>}
      <SyncPill status={syncStatus} />
    </div>
  );
}
```

| Field           | Type                                                                                                                                   |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `messages`      | `Message[]` — live transcript                                                                                                          |
| `session`       | `SessionState \| null`                                                                                                                 |
| `sendMessage`   | `(content: string, opts?) => Promise<void>`                                                                                            |
| `createSession` | `(config?) => Promise<SessionState>`                                                                                                   |
| `abort`         | `() => void`                                                                                                                           |
| `isStreaming`   | `boolean`                                                                                                                              |
| `syncStatus`    | `SyncStatus` — coarse status pill                                                                                                      |
| `parts`         | `StreamMessagePart[]` — the in-flight message's parts; empty once the turn settles. Text and reasoning parts carry an optional `id`    |
| `settledParts`  | `StreamMessagePart[] \| null` — the settled message's parts, tool parts included; `null` until the terminal and again at the next send |

`sendMessage` triggers `executeMessage` under the hood; the hook
reduces stream events into `messages` for you.

`useHarness({ holdAnswerUntilTurnComplete: true })` holds every
non-user change to `messages` as a whole, plus `streamingContent` and
the answer text in `parts` and `settledParts`, until the turn ends, so text a guard later
corrects or resets is never shown. User messages, `thinkingContent`,
`toolOutput` and `batchProgress` stay live. Show progress from
`isStreaming`. It is off by default. See
[Fabrication detection § Holding the answer](/docs/fabrication-detection#holding-the-answer-until-the-guards-have-run).

Each `sendMessage` keeps its own turn state. A send made while a turn
is still running waits behind it (the runtime runs one turn at a time)
and takes over the live view on its own first event, so the running
turn's answer, its late corrections and its settled message are left
alone. `isLoading` stays `true` until no send is running.

`createSession` or `resumeSession` while a turn runs detaches that
turn, and so does `resumeSession` of the running turn's own session,
which reloads its transcript from storage. Nothing more of the turn
reaches `messages` or the live view, anything its hold had queued is
dropped, and `isLoading` and `pendingInterrupts` clear. Every approval
the turn is waiting on, or asks for afterwards, is released unanswered,
so it finishes with the tool not run instead of holding the runtime's
turn queue and stalling your next send. That release is recorded as a
**policy** decision, never as the user's: the decision row reads
`decided_by: "policy"` with policy code `client_detached` and no
actor, and the model is told the client stopped following the turn, not
that the user declined. Outcome readers report it as `released`, not
`timeout` (see [Interrupts § Released is not timed out](/docs/interrupts#released-is-not-timed-out)). On a browser runtime the release goes through
the in-process approval bridge. Unmounting the hook while a turn runs
releases it the same way; a dev StrictMode remount does not.
`resolveInterrupt` always records the person's choice: it drops any
`decidedBy` or `policyCode` the caller passes. The turn is not stopped otherwise. It runs to its end and is saved to its
own session, where `resumeSession` shows it. To stop it, call `abort()`
**before** switching: after the switch, `abort()` and `cancelStream()`
target the runtime's active turn, which may still be the detached one.

`resolveInterrupt(id, decision)` hands the decision to
`runtime.interrupts.resolve` for the current session, or on a browser
runtime to the in-process approval bridge, which resumes the paused
turn. The interrupt leaves `pendingInterrupts` only when one of them
took the decision; if nothing did, it stays listed. `pendingInterrupts`
also shows the approvals the runtime raises on its event bus, not only
those on the turn's stream.

### Stop is a user stop [#stop-is-a-user-stop]

A Stop button is classified as a user stop
(`runtime.wasLastTurnAbortedByUser()` is `true`), not as an error,
on both of the paths a React client takes:

* **In-process** — `useHarness`'s `abort()` calls
  `runtime.abort("user")` on the runtime it drives.
* **Over the wire** — `useChat()` from `@pleach/core/quickstart/react`
  (and the deprecated `useVercelAISDKCompat` over it, whose `stop`
  delegates to `useChat().stop()`) declares its disconnect intent on every
  execute request: it sends `PLEACH_ON_DISCONNECT_HEADER` set to
  `DISCONNECT_INTENT.Stop`. `stop()` aborts that request, and
  `createPleachRoute` / `HarnessServer` read the declaration and
  abort the turn with `"user"`. Unmounting, `reset()`, and a new
  `submit()` close the same request, so they're classified the same
  way.

`useVercelAISDKCompat`, `<VercelAISDKCompat>` and `useVercelChatContext`
are deprecated. They project the AI SDK v4 `useChat` shape, not v5's
`UIMessage.parts`. Keep `useChat` from `@ai-sdk/react` and serve the turn
with `toUIMessageStreamResponse` from `@pleach/core/ai-sdk` instead.

To keep the legacy `"error"` label on a `useChat` client, pass the
header yourself in `headers`; your value overrides the hook's. A
hand-rolled `fetch` client gets the user-stop classification only if
it declares the intent — see
[SessionRuntime → Stopping a streamed turn from the client](/docs/session-runtime#stopping-a-streamed-turn-from-the-client).

### `useChat` [#usechat]

The Pleach-native hook on `@pleach/core/quickstart/react`. It posts to a
`createPleachRoute` handler and folds the `StreamEvent`s it reads back
(SSE, or NDJSON from a route that predates SSE) into a transcript. The subpath also exports `<ChatBox />`,
`UseChatDuplicateMessageError`, `PLEACH_REQUEST_ID_HEADER`,
`TOOL_OUTPUT_MAX_CHARS` and `appendCappedToolOutput`. The error class, the
header and size constants and the helper are also exported from
`@pleach/core/quickstart`, which loads without `react`; `useChat` and
`ChatBox` remain there as deprecated names that load the React subpath on
first call, in Node and SSR only.

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

const {
  messages, status, submit, stop,
  isProvisional, isReasoning, reasoningText,
  toolOutput, batchProgress,
} = useChat({ api: "/api/chat" });
```

**Returns.**

| Field                                    | Type                                               | Meaning                                                                                                                                                                                                                                                                             |
| ---------------------------------------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `messages`                               | `UseChatMessage[]`                                 | Transcript, including the in-flight assistant turn while `status === "streaming"`                                                                                                                                                                                                   |
| `status`                                 | `"idle" \| "submitting" \| "streaming" \| "error"` | Lifecycle                                                                                                                                                                                                                                                                           |
| `submit` / `stop` / `reset`              | functions                                          | Send a message, abort the stream (a user stop), clear transcript and session                                                                                                                                                                                                        |
| `clearMessages`                          | `() => void`                                       | The same function as `reset`, named for the recipes `Chatbot.reset()`. It aborts an in-flight stream first and never refuses while streaming, drops a held answer instead of flushing it, and clears the session id at once, so a `submit` in the same handler starts a new session |
| `error`                                  | `Error \| null`                                    | The last route or stream error, cleared on the next `submit`. A duplicate submit is a `UseChatDuplicateMessageError` (see below)                                                                                                                                                    |
| `pendingInterrupts` / `resolveInterrupt` |                                                    | Interrupts awaiting a decision, and the call that answers one                                                                                                                                                                                                                       |
| `isProvisional`                          | `boolean`                                          | `true` while the in-flight bubble shows the tool-loop's provisional draft rather than answer text. That bubble carries `metadata.provisional`; style it as a draft                                                                                                                  |
| `reasoningText`                          | `string`                                           | The turn's reasoning text, from `reasoning.delta` and `thinking.delta`. Never part of `messages`. Reset at the next `submit` and kept after the answer starts                                                                                                                       |
| `isReasoning`                            | `boolean`                                          | `true` while reasoning streams before the first answer delta                                                                                                                                                                                                                        |
| `toolOutput`                             | `Record<string, string>`                           | `tool.progress` output per `toolCallId`, stdout and stderr interleaved in arrival order, keeping the last 64 KB. Reset on each `submit`                                                                                                                                             |
| `batchProgress`                          | `object \| null`                                   | The latest `tool.batch_progress` of the turn                                                                                                                                                                                                                                        |
| `parts`                                  | `StreamMessagePart[]`                              | The in-flight assistant message's parts: text per lane, reasoning, and one tool part per call. Empty once the turn settles. Text and reasoning parts carry an optional `id`                                                                                                         |
| `settledParts`                           | `StreamMessagePart[] \| null`                      | The settled message's parts, including the tool parts of the calls that started, with its answer text kept in step with a later correction. `null` until the turn's terminal, and again at the next `submit` or `reset`                                                             |

The provisional draft is the tool-loop's own text, shown live until the
answer, the terminal `message.complete`, a `content.reset` or a tool
call replaces it. See
[Stream events § Delta lanes](/docs/stream-events#delta-lanes).

#### Tool parts [#tool-parts]

Each tool call is one `tool` part in `parts`, keyed by its call id. Its
`state` follows the event that last touched it:

| Event                  | Part state                                                                                          |
| ---------------------- | --------------------------------------------------------------------------------------------------- |
| `tool.delta`           | `input-streaming`, with the raw argument text so far in `inputText`                                 |
| `tool.input.discarded` | The `input-streaming` part is removed. The call will never start                                    |
| `tool.started`         | `input-available`, with the parsed `input`                                                          |
| `interrupt.requested`  | `approval-requested`, with `approval.id` set to the interrupt id                                    |
| `interrupt.resolved`   | `approval-responded` when approved, `output-denied` when denied or released unanswered              |
| `tool.completed`       | `output-available`, with `output`; `output-error` when `toolCall.status` is `"failed"` or `"error"` |
| `tool.failed`          | `output-error`, with `errorText`                                                                    |

A flat terminal (a `toolCallId` with no `toolCall` object, such as the
`SUPPRESSED:` `tool.failed` for a dropped call) settles a part
that has not settled yet and never creates one. When the turn settles,
any part still `input-streaming` is dropped. The state names follow the
AI SDK's `UIMessage` tool states. `applyStreamEvent` from
`@pleach/core` is the reducer behind `parts`, for a client that folds
the stream itself.

A text or reasoning part has an optional `id`, taken from the `partId`
of the deltas that built it, so you can use it as a render key. It is
absent when the deltas carried none. Ids are unique within a message;
see [Stream events § Part ids](/docs/stream-events#part-ids).

**Options.**

| Option                                | Meaning                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `api`                                 | Route to POST to. Defaults to `/api/chat`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `initialSessionId`, `initialMessages` | Resume a session, or seed the transcript                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `onEvent`, `onError`                  | Per-event and per-error callbacks. A throwing `onEvent` handler is logged and is not treated as a transport failure                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `headers`                             | Extra headers on each request. Your values override the hook's                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `interruptApi`                        | Resolves the URL `resolveInterrupt` posts to                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `reconnect`                           | Bounded re-send policy for a request that failed to connect, or `false` for none. Fields: `maxRetries` (default 2), `baseDelayMs` (500, doubling per attempt), `maxDelayMs` (8000), `offlineWaitMs` (30000)                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `connectivity`                        | A source with `getState()` and `subscribe()`, such as a started `ConnectivityMonitor`. While it reports offline, a re-send waits for it to report online, up to `offlineWaitMs`                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| `holdAnswerUntilTurnComplete`         | `true` keeps the reply out of `messages`, `parts` and `settledParts` until the turn ends (`turn.completed`, an error, a stop or the stream ending), so text a guard later corrects or resets is never shown. Show progress from `status`. A new `submit` while an answer is held settles it in place first. `{ releaseAfterMs }` also releases once that many milliseconds have passed since the turn's first event, checked only when an event arrives; that gives up the guarantee for longer turns. Default off. See [Fabrication detection § Holding the answer](/docs/fabrication-detection#holding-the-answer-until-the-guards-have-run) |

**Reconnecting.** The hook re-sends only a request that failed to
connect (the fetch rejected before any response), and only with
evidence the request never left: the `connectivity` source, or
`navigator.onLine` where the platform has it, reported offline at
failure time. Each re-send is preceded by a client-synthesized
`stream.reconnecting` (`phase: "connect"`) on `onEvent`. Without that
evidence, or once the budget is spent, you get `stream.disconnected`
(`phase: "connect"`) and no re-send. An established stream that drops
is never re-sent, because the server has no live rejoin and a re-send
would run the turn twice; it yields `stream.disconnected`
(`phase: "stream"`).

**Request headers.** Every execute request carries
`x-pleach-on-disconnect: stop` and `x-pleach-request-id`. The request
id is minted once per `submit` and is identical on the first send and
on any re-send, so a server can recognise a duplicate. Both headers
are custom, so a route on another origin must allow them:

```text
Access-Control-Allow-Headers: content-type, x-pleach-on-disconnect, x-pleach-request-id
```

Add any header you pass in `headers` to that list. A preflight that
omits either one fails the POST before it is sent. A same-origin route
needs nothing.

**Duplicate submits.** `createPleachRoute` keys its
[re-submit protection](/docs/api-routes#re-submitting-a-message) on
that request id. When the route answers `409` with
`code: "PLEACH_DUPLICATE_MESSAGE"`, the hook sets `error` (and calls
`onError`) with a `UseChatDuplicateMessageError`. It carries
`status: 409`, `code`, `state` (`"in_flight"` while the first
request's turn runs, `"settled"` once it was answered) and, when the
route knows it, the first turn's `turnId`. Its message text is the
same as for any other non-2xx response, and other non-2xx responses
are still a plain `Error`.

```tsx
import { useChat, UseChatDuplicateMessageError } from "@pleach/core/quickstart/react";

const { error } = useChat({ api: "/api/chat" });
if (error instanceof UseChatDuplicateMessageError && error.state === "in_flight") {
  // the first send is still running; don't treat this as a failure
}
```

### Session-list hooks [#session-list-hooks]

For sidebars, inboxes, multi-session UIs. Read-only and live —
subscribe to storage updates so you don't have to refetch.

```tsx
function Sidebar() {
  const { sessions, isLoading } = useSessionList({
    filter: { userId: currentUser.id },
    limit:  50,
  });

  if (isLoading) return <Skeleton />;

  return (
    <ul>
      {sessions.map((s) => (
        <li key={s.id}>
          <a href={`/c/${s.id}`}>{s.title ?? "Untitled"}</a>
        </li>
      ))}
    </ul>
  );
}
```

```tsx
function CheckpointPicker({ sessionId }: { sessionId: string }) {
  const checkpoints = useSessionCheckpoints(sessionId);
  return (
    <select>
      {checkpoints.map((cp) => (
        <option key={cp.id} value={cp.id}>
          {cp.stageId} — {new Date(cp.createdAt).toLocaleTimeString()}
        </option>
      ))}
    </select>
  );
}
```

### Tool hooks [#tool-hooks]

Read-only views over the registered tool registry. Do not invoke
tools — they're for command palettes, schema-driven forms, and
per-tool settings.

| Hook                      | Returns                             | Use case                                                          |
| ------------------------- | ----------------------------------- | ----------------------------------------------------------------- |
| `useTools(opts?)`         | Full tool list with optional filter | Command palette                                                   |
| `useToolsByCategory()`    | Tools grouped by category           | Settings panel sections                                           |
| `useTool(name)`           | Single tool definition              | Per-tool detail view                                              |
| `useToolValidation(name)` | `(args) => ValidationResult`        | Validate form args against the tool's JSON schema before dispatch |

```tsx
function ToolPalette() {
  const { tools } = useTools({ enabledOnly: true });
  return tools.map((t) => <ToolCard key={t.name} tool={t} />);
}

function ToolArgsForm({ toolName }: { toolName: string }) {
  const validate = useToolValidation(toolName);
  const [args, setArgs] = useState({});
  const result = validate(args);

  return (
    <form>
      <SchemaForm value={args} onChange={setArgs} />
      {!result.ok && <ValidationErrors errors={result.errors} />}
    </form>
  );
}
```

### Sync hooks [#sync-hooks]

Coarse and fine-grained views over the sync coordinator.

| Hook                   | Returns                                     | Use case                 |
| ---------------------- | ------------------------------------------- | ------------------------ |
| `useSyncStatus(opts?)` | `{ stats: SyncStats; errors: SyncError[] }` | Diagnostics panel        |
| `useIsSynced()`        | `boolean`                                   | "All changes saved" pill |
| `usePendingChanges()`  | `number`                                    | Unsaved-changes guard    |

```tsx
function SavedPill() {
  const synced = useIsSynced();
  return <span>{synced ? "Saved" : "Saving…"}</span>;
}

function NavGuard() {
  const pending = usePendingChanges();
  useBeforeUnload(pending > 0, "You have unsaved changes.");
  return null;
}
```

### `useTeam` [#useteam]

Multi-user presence + cursor info for collaborative session views.

```tsx
function PresenceBar({ sessionId }: { sessionId: string }) {
  const { members, cursors } = useTeam({ sessionId });
  return (
    <div>
      {members.map((m) => (
        <Avatar key={m.userId} user={m} active={m.lastSeenMs < 5000} />
      ))}
    </div>
  );
}
```

Pair with `useSyncStatus` for the full real-time picture.

### `useCompliance` [#usecompliance]

Per-session view over a compliance extension shaped like the
legacy `ComplianceExtensionImpl`. It returns `auditRecordCount`,
`signatures`, `exportAuditLog(format)`, `generateReport()`,
`loading`, and `error`.

<Callout type="warn" title="Backed by a deprecated model">
  `ComplianceExtensionImpl` and `SupabaseComplianceStorage` carry
  `@deprecated` in `@pleach/core`; they keep working, but new code
  shouldn't adopt them. Write audit events through `EventLogWriter`
  (`@pleach/core/eventLog`), read them with `queryAudit`, and verify
  and report with `createComplianceRuntime` (`@pleach/compliance`).
</Callout>

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

function ComplianceBadge() {
  const compliance = useCompliance({ sessionId, compliance: complianceExtension });
  return <span>audit records: {compliance.auditRecordCount}</span>;
}
```

`UseComplianceReturn` is the typed shape; treat the return as
opaque until the policy surface stabilizes for 1.0.

### Correction dedup [#correction-dedup]

`createCorrectionDedup({ priorityMap, defaultPriority, windowMs })`
returns a closure that decides whether an incoming
`content.correction` should be allowed past the dedup window. Lift
this into any consumer that fans correction events into a single
rendering surface — it's the same dedup the substrate uses
internally.

```typescript
import { createCorrectionDedup, createDefaultCorrectionDedup } from "@pleach/core/react";

const shouldAllow = createCorrectionDedup({
  priorityMap:    { "tool.input": 10, "tool.output": 5 },
  defaultPriority: 1,
  windowMs:       500,
});

// or the defaults:
const shouldAllowDefault = createDefaultCorrectionDedup();
```

`CorrectionPriorityMap`, `CorrectionDedupConfig`, and
`ShouldAllowContentCorrectionFn` are the typed surfaces.

### `useHarnessDevTools` [#useharnessdevtools]

Wires `window.__HARNESS_DEVTOOLS__` to the active runtime so you
can drive checkpoints, sync, and tool inspection from the browser
console.

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

function App() {
  if (process.env.NODE_ENV !== "production") {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    useHarnessDevTools();
  }
  return <HarnessProvider runtime={runtime}>...</HarnessProvider>;
}
```

The exposed surface:

```javascript
__HARNESS_DEVTOOLS__.session;               // SessionState
__HARNESS_DEVTOOLS__.checkpoints();         // Checkpoint[]
__HARNESS_DEVTOOLS__.rollback("cp_...");    // restore to checkpoint
__HARNESS_DEVTOOLS__.tools();               // ToolDefinition[]
__HARNESS_DEVTOOLS__.syncStatus();          // sync coordinator status
__HARNESS_DEVTOOLS__.forceSync();           // push a sync now
```

`HarnessDevToolsAPI` is exported for typing
`window.__HARNESS_DEVTOOLS__` in a `.d.ts` shim.
`updateDevToolsSession(state)` is the manual-push API for
forcing a session-state refresh into the devtools surface
from outside the React render cycle.

## Minimal end-to-end example [#minimal-end-to-end-example]

```tsx
'use client';

import { useMemo } from "react";
import { SessionRuntime } from "@pleach/core";
import { IndexedDBAdapter } from "@pleach/core/sessions";
import { IndexedDBSaver } from "@pleach/core/checkpointing";
import {
  HarnessProvider,
  useHarness,
} from "@pleach/core/react";

function App({ userId }: { userId: string }) {
  const runtime = useMemo(
    () =>
      new SessionRuntime({
        storage:      new IndexedDBAdapter({ databaseName: "pleach" }),
        checkpointer: new IndexedDBSaver({ databaseName: "pleach" }),
        userId,
      }),
    [userId],
  );

  return (
    <HarnessProvider runtime={runtime}>
      <Chat />
    </HarnessProvider>
  );
}

function Chat() {
  const { messages, sendMessage, isLoading } = useHarness();
  return (
    <>
      {messages.map((m) => (
        <p key={m.id}>{m.content}</p>
      ))}
      <button
        disabled={isLoading}
        onClick={() => sendMessage("Hello")}
      >
        Send
      </button>
    </>
  );
}
```

## Local playground — `<PleachLab>` [#local-playground--pleachlab]

The `@pleach/react/lab` subpath ships a zero-config split-pane local
playground: a render-isolated chat on the left, a live execution
visualizer on the right. Drop it on a page, hand it a runtime factory,
and watch the graph run.

```tsx
import { PleachLab } from "@pleach/react/lab";

<PleachLab buildRuntime={() => new SessionRuntime(/* … */)} />
```

The right pane visualizes execution at three depths, each folded
purely from the agnostic `StreamEvent` stream via `useLatticeState` —
no privileged hooks.

* **Stages** — the 4-stage lattice (`anchor · plan → tool loop →
  synthesize → post-turn`). The dominant stage lights; minority stages
  glow dimmer; self-loops show a `↻`.
* **Nodes** — each graph-node chip glows on `node.fired` and fades over
  the next few firings, so you see *which* node ran, not just which
  stage is active.
* **Channels** — a writer/clearer lane tickers each `channel.write`
  (version bump) and `channel.cleared` (ephemeral step-boundary reset),
  with a per-turn "hot channels" leaderboard. That's the subscription
  substrate that drives the next superstep.

Because the visualizer is `StreamEvent`-driven, the same `node.fired` /
`channel.write` / `channel.cleared` events are subscribable from any
`useChat({ onEvent })` consumer — or asserted in a headless test (see
[Testing](/docs/testing#headless-turn-driver-pleachcoretesting)). Mount
`LatticePanel` / `ChannelActivityStrip` standalone next to your own
chat UI when you don't want the full shell.

### The composable kit [#the-composable-kit]

`<PleachLab>` is a shell over individually-exported pieces. Import any
of them to build your own layout instead of the bundled split-pane.

New code should import from `@pleach/core/react/lab` — that's the
canonical home. `@pleach/react/lab` re-exports the same surface and
stays as a compatibility alias.

| Export                                                    | Kind       | Renders / returns                                                      |
| --------------------------------------------------------- | ---------- | ---------------------------------------------------------------------- |
| `PleachLab`                                               | component  | The full split-pane shell (`PleachLabProps`).                          |
| `ConversationView`, `MessageBubble`, `Composer`           | components | The chat pane — transcript, one bubble, the input box.                 |
| `ToolCallCard`, `CitationsFooter`                         | components | A tool-call result card; the per-message citations footer.             |
| `LatticePanel`                                            | component  | The stage/node/channel execution visualizer.                           |
| `ChannelActivityStrip`                                    | component  | The channel writer/clearer ticker + hot-channel leaderboard.           |
| `AuditLedgerPanel`                                        | component  | The per-turn audit-row inspector.                                      |
| `EventLogPanel`                                           | component  | The raw `StreamEvent` log.                                             |
| `CheckpointTimeline`                                      | component  | The checkpoint markers along the turn.                                 |
| `NodeChannelInspector`                                    | component  | Drill-down for a `LatticeSelection` (node ↔ channel wiring).           |
| `FamilyPicker`, `FamilyAccordion`, `FamilyExhaustedToast` | components | Family-lock UI — pick a family, browse the matrix, surface exhaustion. |
| `InfoTooltip`                                             | component  | The glossary tooltip used throughout the lab.                          |
| `useLatticeState`                                         | hook       | Folds `StreamEvent`s into lattice state (drives `LatticePanel`).       |
| `useEventLogCapture`                                      | hook       | Accumulates `CapturedEventLogRow[]` for `EventLogPanel`.               |
| `useChannelSnapshot`                                      | hook       | The current channel snapshot for `ChannelActivityStrip`.               |

The content types the components render against — `LabMessage`,
`LabRole`, `LabCitation`, `LabToolCall`, `RenderContent` — are exported
from the same barrel, so you can adapt your own message shape to them.

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

<Cards>
  <Card title="useRemoteTurn" href="/docs/use-remote-turn" description="Run turns on your server and attach the page: send, re-attach, approve, stop." />

  <Card title="HarnessServer" href="/docs/server" description="Framework-agnostic HTTP handlers — what the hooks call into when the runtime lives on a server." />

  <Card title="API routes" href="/docs/api-routes" description="The HTTP + SSE wire contract these hooks consume." />

  <Card title="Query" href="/docs/query" description="Server-side read API over persisted harness data — the RLS-bypassing counterpart to these RLS-bound hooks." />

  <Card title="DevTools" href="/docs/devtools" description="window.__HARNESS_DEVTOOLS__ — the browser-console surface useHarnessDevTools wires." />
</Cards>
