# Build a live React interface

Use one shared session store for messages, tools, interactions, usage, and recovery.

## Install

```bash
npm install "https://wkala.okal.io/downloads/wkala-client-0.1.0.tgz" "https://wkala.okal.io/downloads/wkala-react-0.1.0.tgz"
```

The React package works with React 19 and has no Next.js, router, shadcn, or styling dependency. It uses the same validated session store as the TypeScript client. The shipped Next application uses that store with shared shadcn components.

## Connect through your backend

Your own backend supplies the authenticated `/app` routes, an HttpOnly session cookie, CSRF protection, and ownership checks. `csrfToken` below comes from that backend's authenticated identity response. It is not your Wkala service key.

The browser client defaults to same-origin `/app`, not the public API default used by server clients. The `createAppProxy` target must be your customer-backend origin only, without a path.

```tsx
"use client"
import { useState } from "react"
import { AgentClient, isTerminal } from "@wkala/client"
import { AgentProvider, useSession } from "@wkala/react"

export function AgentWorkspace({ sessionId, csrfToken }: {
  sessionId: string
  csrfToken: string
}) {
  const [client] = useState(() => new AgentClient())
  client.csrfToken = csrfToken
  return (
    <AgentProvider client={client}>
      <Execution sessionId={sessionId} />
    </AgentProvider>
  )
}

function Execution({ sessionId }: { sessionId: string }) {
  const session = useSession(sessionId)
  const [message, setMessage] = useState("")
  const [error, setError] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)
  const busy = submitting || session.runs.some(run => !isTerminal(run.status))

  async function submit() {
    setSubmitting(true)
    setError(null)
    try {
      await session.send(message, { idempotencyKey: crypto.randomUUID() })
      setMessage("")
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : "Unable to start work")
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <section>
      <p role="status">{session.connection}</p>
      {session.error && <p role="alert">{session.error.message}</p>}

      {session.messages.map(message => (
        <article key={message.id}>
          <strong>{message.role}</strong>
          {message.parts.map(part => (
            <p key={part.id}>
              {part.type === "text" ? part.text : "[attached content]"}
            </p>
          ))}
        </article>
      ))}

      {session.tools.map(tool => (
        <article key={tool.id}>
          <strong>{tool.title}: {tool.status}</strong>
          <pre>{JSON.stringify(tool.output, null, 2)}</pre>
        </article>
      ))}

      {session.interactions.some(item => item.status === "pending") && (
        <p>Input is required. Present the offered interaction to the user.</p>
      )}

      <form onSubmit={event => {
        event.preventDefault()
        void submit()
      }}>
        <label htmlFor="task">Message</label>
        <textarea
          id="task"
          value={message}
          onChange={event => setMessage(event.target.value)}
        />
        <button disabled={busy || !message.trim()}>Send message</button>
        {error && <p role="alert">{error}</p>}
      </form>
    </section>
  )
}
```

This is a small rendering example. For uncertain admission, retain the SDK error's idempotency key and retry the same request body. Do not invent a new business request automatically. The shipped `AgentPanel` implements the fuller composer, rich messages, exact approvals, typed forms, cancel controls, session settings, and plans.

## Hook surface

| Value or action | Meaning |
| --- | --- |
| `snapshot` | Complete session state, or null before hydration or after access loss |
| `connection`, `error` | Observation state, separate from run execution status |
| `messages`, `tools`, `invocations`, `interactions`, `runs` | Arrays from the same coherent state |
| `send(message, options)` | Admit one run with an idempotency identity |
| `respond(id, response)` | Submit an exact permission option, message, or typed form |
| `cancel(runId)` | Explicitly request execution cancellation |
| `reconnect()` | Resume observation without admitting work |
| `updateSetting`, `close`, `deleteSession`, `fork` | Capability-dependent session operations |

Pass `null` when there is no selected session. Multiple hooks using the same client and session share one observation connection. Rendering and StrictMode do not start runs. Unmounting removes an observer. It does not cancel a run.

## Logout and hydration

Call `client.clear()` when the application user logs out or changes identity. Unmount identity-specific UI. The neutral server snapshot contains no invented signed-in state. An authenticated SSR snapshot must come from that exact request's user. Never use a module-global authenticated store on the server.

See [Next.js](/docs/raw/nextjs?locale=en) for the same-origin proxy and optional request-scoped snapshot helper, and [approvals and questions](/docs/raw/interactions?locale=en) for explicit user input.
