> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Add a chat to your web app

> Put a chat with your agent in your Next.js app. Try it on your own machine first, then add your signed-in users so the agent can tell them apart.

Your users chat in your app, and your server talks to the agent. The browser never sees the service credential, and the agent sees each of your users as a separate person, with their own conversations.

```text theme={"theme":{"light":"github-light","dark":"github-dark"}}
browser ──► your server ─────────────────► Jaccard ─────────────► agent
            /eve/v1/*                      • checks the token
            • signs in as your service     • checks the agent's
            • names the signed-in user       callers
            • keeps each user to their
              own sessions
```

Two parts make it work:

* **A route on your server** passes the chat's requests to the agent. It holds the service credential, since every request to the agent needs a Jaccard token, and that token must stay on your server.
* **eve's `useEveAgent` hook** runs in the page. It starts the session, sends messages, and streams the replies and approval requests into React state.

Start with a chat only you can use, on your machine. Then [add your users](#add-your-users) before anyone else uses it.

## Before you start

* Your server has a service credential, listed in the agent's `callers`: see [Access](/docs/operate/access.md#give-a-service-a-credential).
* The steps use Next.js with the App Router. For other frameworks, see [Other frameworks](#other-frameworks).

## Try it on your machine

**1. Set up the app**

Create a Next.js app, then install eve at the version in the agent's `package.json`, for its React hook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npx create-next-app@latest my-chat --yes
cd my-chat
npm install eve@1.0.0 server-only
```

**2. Give your server the credential**

Add the agent's URL, from `jaccard agent get <agent>`, and the credential to the app's server environment:

```bash .env.local theme={"theme":{"light":"github-light","dark":"github-dark"}}
JACCARD_AGENT_URL=https://my-agent-acme.jaccard.app
JACCARD_TOKEN_URL=https://…/v1/oauth2/token
JACCARD_CLIENT_ID=m2m-client-live-91c2…
JACCARD_CLIENT_SECRET=…
JACCARD_ORGANIZATION=acme
```

> [!WARNING]
>
> Never give these names a `NEXT_PUBLIC_` prefix or read them in a client component: that would send the secret to every browser.

**3. Add the server helpers**

```ts lib/agent.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
// The build fails if a client component imports this file, so the credential stays on the server.
import "server-only";

const AGENT_URL = process.env.JACCARD_AGENT_URL!;
const TOKEN_URL = process.env.JACCARD_TOKEN_URL!;
const CLIENT_ID = process.env.JACCARD_CLIENT_ID!;
const CLIENT_SECRET = process.env.JACCARD_CLIENT_SECRET!;

let token: { value: string; expiresAt: number } | undefined;

// Tokens last an hour; reuse one until a minute before it expires.
async function serviceToken(): Promise<string> {
  if (token && token.expiresAt > Date.now() + 60_000) return token.value;
  const res = await fetch(TOKEN_URL, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      grant_type: "client_credentials",
    }),
  });
  if (!res.ok) throw new Error(`token request failed: ${res.status}`);
  const data = await res.json();
  token = { value: data.access_token, expiresAt: Date.now() + data.expires_in * 1000 };
  return token.value;
}

// Start a session, send a message, stop a reply, read the stream: the only calls the chat page makes.
export function isChatCall(method: string, path: string[]): boolean {
  const [route, , action] = path;
  if (route !== "session") return false;
  if (method === "GET") return path.length === 3 && action === "stream";
  return method === "POST" && (path.length <= 2 || (path.length === 3 && action === "cancel"));
}

// The fields the chat page needs. The agent accepts more, meant for services only.
export async function chatFields(req: Request, path: string[]) {
  const body = await req.json().catch(() => ({}));
  if (path[2] === "cancel") return { turnId: body.turnId };
  const { message, answers, clientContext, outputSchema, turnPolicy } = body;
  return { message, answers, clientContext, outputSchema, turnPolicy };
}

// Calls the agent as your service, and passes back the x-eve-* headers that eve's client reads.
export async function callAgent(req: Request, path: string[], body?: object): Promise<Response> {
  const res = await fetch(`${AGENT_URL}/eve/v1/${path.join("/")}${new URL(req.url).search}`, {
    method: req.method,
    headers: {
      authorization: `Bearer ${await serviceToken()}`,
      "content-type": "application/json",
      accept: req.headers.get("accept") ?? "*/*",
    },
    body: body && JSON.stringify(body),
    signal: req.signal,
  });

  const headers = new Headers();
  res.headers.forEach((value, name) => {
    if (name.startsWith("x-eve-") || ["content-type", "cache-control", "x-accel-buffering"].includes(name)) {
      headers.set(name, value);
    }
  });
  return new Response(res.body, { status: res.status, headers });
}
```

**4. Add the route the browser calls**

eve's React hook calls `/eve/v1/*` on your app's own origin. This route passes on the requests a chat makes, and nothing else:

```ts app/eve/v1/[...path]/route.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { callAgent, chatFields, isChatCall } from "@/lib/agent";

type Params = { params: Promise<{ path: string[] }> };

async function proxy(req: Request, { params }: Params) {
  const { path } = await params;
  if (!isChatCall(req.method, path)) return Response.json({ error: "Not found." }, { status: 404 });
  return callAgent(req, path, req.method === "POST" ? await chatFields(req, path) : undefined);
}

export { proxy as GET, proxy as POST };
```

**5. Add the chat page**

The page sends messages, streams the replies, and shows buttons when the agent asks the user to approve a tool, answer a question or sign in to a service:

```tsx app/page.tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
"use client";

import { useState } from "react";
import { activeTurn, openInteractions } from "eve/events";
import { useEveAgent } from "eve/react";

export default function Page() {
  const agent = useEveAgent();
  const [draft, setDraft] = useState("");
  // An answered request stays open until the agent takes the answer, so hide it once answered.
  const prompts = openInteractions(agent.view).filter((item) => item.answer === undefined);
  const working = activeTurn(agent.view) !== undefined;
  const resuming = agent.status === "resuming";

  return (
    <main className="mx-auto flex max-w-2xl flex-col gap-4 p-6">
      {agent.messages.map((message) => (
        <div key={message.id} className={message.role === "user" ? "self-end rounded-lg bg-gray-100 px-3 py-2" : "whitespace-pre-wrap"}>
          {message.parts.map((part, i) =>
            part.type === "text" ? (
              <p key={part.id ?? i}>{part.text}</p>
            ) : part.type === "tool" ? (
              <p key={part.callId} className="text-sm text-gray-500">Used {part.label}</p>
            ) : null,
          )}
        </div>
      ))}

      {/* The turn waits here until the user picks an answer. */}
      {prompts.map(({ interactionId, request }) => (
        <div key={interactionId} className="flex items-center gap-2 rounded-lg border p-3">
          <p className="flex-1">{request.signIn?.instructions ?? request.prompt}</p>
          {request.signIn?.url ? (
            <a className="rounded border px-3 py-1" href={request.signIn.url} target="_blank" rel="noreferrer">
              Sign in
            </a>
          ) : null}
          {(request.options ?? []).map((option) => (
            <button
              key={option.id}
              className="rounded border px-3 py-1"
              disabled={resuming}
              onClick={() => void agent.respond([{ interactionId, optionId: option.id }])}
            >
              {option.label}
            </button>
          ))}
        </div>
      ))}

      {agent.error ? <p className="text-red-600">{agent.error.message}</p> : null}

      <form
        className="flex gap-2"
        onSubmit={(event) => {
          event.preventDefault();
          if (!draft.trim()) return;
          void agent.send(draft.trim());
          setDraft("");
        }}
      >
        <input
          name="message"
          className="flex-1 rounded border px-3 py-2"
          value={draft}
          onChange={(event) => setDraft(event.target.value)}
          placeholder="Message the agent"
          disabled={working || resuming}
        />
        {working ? (
          <button type="button" className="rounded border px-3" onClick={() => void agent.cancel()}>
            Stop
          </button>
        ) : (
          <button type="submit" className="rounded border px-3">
            Send
          </button>
        )}
      </form>
    </main>
  );
}
```

eve's [frontend documentation](https://eve.dev/docs/guides/frontend/overview) covers the hook. For a page with markdown, tool details and a saved session, see [Use a styled chat page](#use-a-styled-chat-page).

**6. Chat with the agent**

Start the app on this machine only, then open `http://127.0.0.1:3000` and send a message:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
npx next dev -H 127.0.0.1
```

> [!WARNING]
>
> This version has no sign-in. Anyone who can reach the app chats as your service, spends your model tokens and can read every conversation. Keep it on `127.0.0.1` until you've added your users.

## Add your users

Before anyone else uses the chat, have your server name the signed-in user on each message, and let each user reach only their own sessions. Until then, the agent sees one caller, your service, so all your users share its memory, approvals and connections.

**1. Let your service speak for your users**

Add the service to `forwarders` and accept forwarded users in `agent/channels/eve.ts`, as in [Access](/docs/operate/access.md#let-a-service-call-on-behalf-of-its-users), then deploy.

**2. Add the user helpers**

`signedInUser` returns the id of whoever is signed in to your app. Use your own sign-in. This version reads a cookie, so you can test with two users before wiring it up:

```ts lib/users.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import "server-only";
import { cookies } from "next/headers";

// Replace with your app's sign-in. This test version trusts the `user` cookie set by /login.
export async function signedInUser(): Promise<string | undefined> {
  return (await cookies()).get("user")?.value;
}

// Which user started each session. Keep this in your database: it is lost on restart here.
const owners = new Map<string, string>();

export const ownerOf = (sessionId: string) => owners.get(sessionId);
export const recordOwner = (sessionId: string, userId: string) => owners.set(sessionId, userId);

export function forwardedUser(userId: string) {
  return {
    current: {
      principalId: userId,
      principalType: "user",
      authenticator: "my-app",
      issuer: "https://my-app.example.com",
      attributes: { tenant: process.env.JACCARD_ORGANIZATION! },
    },
  };
}
```

**3. Check the user on every request**

Replace the route:

```ts app/eve/v1/[...path]/route.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { callAgent, chatFields, isChatCall } from "@/lib/agent";
import { forwardedUser, ownerOf, recordOwner, signedInUser } from "@/lib/users";

type Params = { params: Promise<{ path: string[] }> };

async function proxy(req: Request, { params }: Params) {
  const userId = await signedInUser();
  if (!userId) return Response.json({ error: "Sign in first." }, { status: 401 });

  const { path } = await params;
  if (!isChatCall(req.method, path)) return Response.json({ error: "Not found." }, { status: 404 });

  // The agent only checks that the call comes from your service, so only let
  // each user reach the sessions they started.
  const sessionId = path[1];
  if (sessionId && ownerOf(sessionId) !== userId) {
    return Response.json({ error: "Not your session." }, { status: 403 });
  }

  // Messages and answers name the user. Cancel takes no other fields.
  const fields = req.method === "POST" ? await chatFields(req, path) : undefined;
  const body = fields && path[2] !== "cancel" ? { ...fields, forwardedPrincipal: forwardedUser(userId) } : fields;
  const res = await callAgent(req, path, body);

  if (req.method === "POST" && !sessionId && res.ok) {
    const created = await res.clone().json();
    recordOwner(created.sessionId, userId);
  }
  return res;
}

export { proxy as GET, proxy as POST };
```

> [!WARNING]
>
> Keep all three checks. Every request reaches the agent as your service, with your service's authority:
>
> * **Allowed calls** (`isChatCall`). Without them, a signed-in user could reach every route the agent has.
> * **Ownership** (`ownerOf`). The agent can't tell your users' sessions apart, so without it anyone signed in to your app who learns a session id can read that conversation and write to it.
> * **Body fields** (`chatFields`). The agent also accepts fields meant for services, such as a URL to send results to. Copying the browser's body would let a user set them.

If your page saves the session in the browser, as the shadcn/ui version does, remove it when a user signs out, so the next person on that browser starts their own chat.

Each message costs model tokens, so limit how many a user can send, as you would any paid API.

## Check it works

Use two users to check that the agent tells them apart and that each sees only their own conversation.

1. Add a test sign-in route, and remove it before you ship:

   ```ts app/login/route.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
   // Test-only sign-in: /login?user=alice. Remove before shipping.
   export async function GET(req: Request) {
     const user = new URL(req.url).searchParams.get("user") ?? "";
     return new Response(null, {
       status: 303,
       headers: { location: "/", "set-cookie": `user=${encodeURIComponent(user)}; Path=/; HttpOnly; SameSite=Lax` },
     });
   }
   ```

2. Give the agent a tool that reports who is calling, and deploy:

   ```ts agent/tools/whoami.ts theme={"theme":{"light":"github-light","dark":"github-dark"}}
   import { defineTool } from "eve/tools";
   import { z } from "zod";

   export default defineTool({
     description: "Return who is calling: the user's id and the service that forwarded them.",
     inputSchema: z.object({}),
     async execute(_input, ctx) {
       const current = ctx.session.auth.current;
       return {
         user: current?.principalId ?? null,
         forwardedBy: current?.attributes?.["eve:forwarded-by"] ?? null,
       };
     },
   });
   ```

3. Start the app on this machine only, since the test sign-in lets anyone who can reach it be any user: `npx next dev -H 127.0.0.1`. Open `/login?user=alice` in one browser and `/login?user=bob` in a private window, and try:

   | As | Send | Expect |
   | - | - | - |
   | alice | "Remember that my favourite colour is teal. Who am I?" | `alice` |
   | bob | "Who am I? What is my favourite colour?" | `bob`, and it doesn't know the colour |
   | alice | "What is my favourite colour?" | Teal |

4. Copy alice's session id from her browser's network panel, where it appears in the `/eve/v1/session/<id>/stream` request. In bob's window, open `/eve/v1/session/<id>/stream`: your route should answer `403` "Not your session."

## Other frameworks

For Vue or Svelte, use `useEveAgent` from `eve/vue` or `eve/svelte`, and port the route to your framework's server routes with its three checks.

A server-rendered app, such as one in Python, can skip the route and the hook, and call the agent from your server as in [Calls from your service](/docs/connect/your-service.md).

> [!WARNING]
>
> Don't use eve's framework plugins, such as `eve/next`, with an agent on Jaccard. They pass every request to the agent without your route's checks.

## Use a styled chat page

> [accordion] The shadcn/ui chat page
>
> This version renders markdown in the replies, shows each tool call with its result, and keeps the session across reloads. It adds more packages: [shadcn/ui](https://ui.shadcn.com)'s chat components and Streamdown. It uses the same route, so the checks in [Add your users](#add-your-users) still apply.
>
> Add shadcn/ui and its chat components, and Streamdown for markdown. In an app that already has shadcn/ui, start at `shadcn add`.
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> npx shadcn@latest init -d
> npx shadcn@latest add message-scroller message bubble input-group trace code-block item button
> npm install streamdown
> ```
>
> Two small changes to the generated files:
>
> * In `app/layout.tsx`, rename the font variable `--font-geist-sans` to `--font-sans`, the name shadcn/ui's styles use.
> * In `app/globals.css`, add `@source "../node_modules/streamdown/dist/*.js";` below the `@import` lines, so the replies' markdown is styled.
>
> Replace `app/page.tsx`. This page keeps the session in the browser, so a reload brings the conversation back, and **New chat** starts a new one:
>
> ```tsx app/page.tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
> "use client";
>
> import { useEffect, useRef, useState } from "react";
> import { ArrowUpIcon, PlusIcon, SquareIcon } from "lucide-react";
> import { Streamdown } from "streamdown";
> import type { ClientSessionState } from "eve/client";
> import { activeTurn, openInteractions } from "eve/events";
> import { useEveAgent } from "eve/react";
>
> import { Prompt, ToolCall } from "@/components/tool-call";
> import { Button } from "@/components/ui/button";
> import { Bubble, BubbleContent } from "@/components/ui/bubble";
> import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupTextarea } from "@/components/ui/input-group";
> import { Message, MessageContent } from "@/components/ui/message";
> import {
>   MessageScroller,
>   MessageScrollerButton,
>   MessageScrollerContent,
>   MessageScrollerItem,
>   MessageScrollerProvider,
>   MessageScrollerViewport,
> } from "@/components/ui/message-scroller";
>
> const SESSION_KEY = "agent-session";
>
> // The hook reads its options once, so load the saved session before it starts.
> export default function Page() {
>   const [saved, setSaved] = useState<ClientSessionState | null>();
>   const [chat, setChat] = useState(0);
>   useEffect(() => {
>     try {
>       setSaved(JSON.parse(localStorage.getItem(SESSION_KEY) ?? "null"));
>     } catch {
>       setSaved(null);
>     }
>   }, []);
>
>   // Forget the saved session and remount the chat, so the hook starts a new session.
>   function newChat() {
>     localStorage.removeItem(SESSION_KEY);
>     setSaved(null);
>     setChat((n) => n + 1);
>   }
>
>   return saved === undefined ? null : <Chat key={chat} saved={saved} onNewChat={newChat} />;
> }
>
> function Chat({ saved, onNewChat }: { saved: ClientSessionState | null; onNewChat: () => void }) {
>   // After New chat, the old chat can still report its session for a moment: save only from the one on screen.
>   const onScreen = useRef(true);
>   useEffect(() => {
>     onScreen.current = true;
>     return () => {
>       onScreen.current = false;
>     };
>   }, []);
>
>   const agent = useEveAgent({
>     initialSession: saved ?? undefined,
>     resume: saved !== null,
>     onSessionChange: (session) => {
>       if (onScreen.current) localStorage.setItem(SESSION_KEY, JSON.stringify(session ?? null));
>     },
>   });
>   const [draft, setDraft] = useState("");
>
>   // Requests the user still has to answer. Sign-ins show their own link and continue once the user signs in.
>   const waiting = openInteractions(agent.view).some(
>     (item) => item.request.kind !== "sign-in" && item.answer === undefined,
>   );
>   const working = activeTurn(agent.view) !== undefined;
>   const canSend = !working && agent.status !== "resuming";
>
>   function submit() {
>     if (!canSend || !draft.trim()) return;
>     void agent.send(draft.trim());
>     setDraft("");
>   }
>
>   return (
>     <main className="mx-auto flex h-dvh w-full max-w-3xl flex-col gap-3 p-4">
>       <header className="flex justify-end">
>         <Button variant="ghost" size="sm" onClick={onNewChat}>
>           <PlusIcon />
>           New chat
>         </Button>
>       </header>
>
>       <MessageScrollerProvider autoScroll>
>         <MessageScroller className="min-h-0 flex-1">
>           <MessageScrollerViewport>
>             <MessageScrollerContent>
>               {agent.messages.map((message) => (
>                 <MessageScrollerItem key={message.id} messageId={message.id} scrollAnchor={message.role === "user"}>
>                   {message.role === "user" ? (
>                     <Message align="end">
>                       <MessageContent>
>                         <Bubble align="end" variant="muted">
>                           <BubbleContent>
>                             {message.parts.map((part) => (part.type === "text" ? part.text : "")).join("")}
>                           </BubbleContent>
>                         </Bubble>
>                       </MessageContent>
>                     </Message>
>                   ) : (
>                     <Message>
>                       <MessageContent>
>                         {message.parts.map((part, i) =>
>                           part.type === "text" ? (
>                             <Streamdown key={part.id ?? i}>{part.text}</Streamdown>
>                           ) : part.type === "tool" ? (
>                             <ToolCall key={part.callId} part={part} respond={agent.respond} />
>                           ) : part.type === "interaction" ? (
>                             <Prompt key={part.interactionId} interaction={part} respond={agent.respond} />
>                           ) : null,
>                         )}
>                       </MessageContent>
>                     </Message>
>                   )}
>                 </MessageScrollerItem>
>               ))}
>             </MessageScrollerContent>
>           </MessageScrollerViewport>
>           <MessageScrollerButton />
>         </MessageScroller>
>       </MessageScrollerProvider>
>
>       {agent.error ? <p className="text-sm text-destructive">{agent.error.message}</p> : null}
>
>       <form
>         onSubmit={(event) => {
>           event.preventDefault();
>           submit();
>         }}
>       >
>         <InputGroup>
>           <InputGroupTextarea
>             value={draft}
>             onChange={(event) => setDraft(event.target.value)}
>             onKeyDown={(event) => {
>               if (event.key === "Enter" && !event.shiftKey) {
>                 event.preventDefault();
>                 submit();
>               }
>             }}
>             placeholder={waiting ? "Answer the request above first" : "Message the agent"}
>             disabled={waiting}
>           />
>           <InputGroupAddon align="block-end">
>             {working && !waiting ? (
>               <InputGroupButton className="ml-auto" size="icon-sm" aria-label="Stop" onClick={() => void agent.cancel()}>
>                 <SquareIcon />
>               </InputGroupButton>
>             ) : (
>               <InputGroupButton
>                 className="ml-auto"
>                 size="icon-sm"
>                 variant="default"
>                 type="submit"
>                 aria-label="Send"
>                 disabled={!canSend || !draft.trim()}
>               >
>                 <ArrowUpIcon />
>               </InputGroupButton>
>             )}
>           </InputGroupAddon>
>         </InputGroup>
>       </form>
>     </main>
>   );
> }
> ```
>
> Each tool call shows as a line you can open. When the agent asks the user to approve a tool or answer a question, it sends the question and its buttons, and the page shows them until the user answers:
>
> ```tsx components/tool-call.tsx theme={"theme":{"light":"github-light","dark":"github-dark"}}
> "use client";
>
> import { WrenchIcon } from "lucide-react";
> import type { Answer, Interaction } from "eve/events";
> import type { EveToolPart } from "eve/react";
>
> import { Button } from "@/components/ui/button";
> import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
> import { Item, ItemActions, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item";
> import {
>   Trace,
>   TraceCollapsible,
>   TraceCollapsibleContent,
>   TraceCollapsibleTrigger,
>   TraceIcon,
>   TraceLine,
>   TraceTitle,
> } from "@/components/ui/trace";
>
> type Respond = (answers: Answer[]) => Promise<unknown>;
>
> // The agent sends the question and its buttons; answer once, by interaction id.
> // A request stays open after an answer until the agent takes it, so hide it once answered.
> export function Prompt({ interaction, detail, respond }: { interaction: Interaction; detail?: string; respond: Respond }) {
>   const { interactionId, request } = interaction;
>   if (interaction.status !== "open" || interaction.answer !== undefined) return null;
>
>   if (request.kind === "sign-in") {
>     return (
>       <Item variant="outline" size="sm">
>         <ItemContent>
>           <ItemTitle>{request.signIn?.instructions ?? request.prompt}</ItemTitle>
>         </ItemContent>
>         {request.signIn?.url ? (
>           <ItemActions>
>             <a className="text-sm underline" href={request.signIn.url} target="_blank" rel="noreferrer">
>               Sign in
>             </a>
>           </ItemActions>
>         ) : null}
>       </Item>
>     );
>   }
>
>   return (
>     <Item variant="outline" size="sm">
>       <ItemContent>
>         <ItemTitle>{request.prompt}</ItemTitle>
>         {detail ? <ItemDescription className="font-mono">{detail}</ItemDescription> : null}
>       </ItemContent>
>       <ItemActions>
>         {(request.options ?? []).map((option, i) => (
>           <Button
>             key={option.id}
>             size="sm"
>             variant={i === 0 ? "default" : "outline"}
>             onClick={() => void respond([{ interactionId, optionId: option.id }])}
>           >
>             {option.label}
>           </Button>
>         ))}
>       </ItemActions>
>     </Item>
>   );
> }
>
> export function ToolCall({ part, respond }: { part: EveToolPart; respond: Respond }) {
>   const approval = part.interaction;
>   if (approval?.status === "open" && approval.answer === undefined) {
>     return <Prompt interaction={approval} detail={JSON.stringify(part.input)} respond={respond} />;
>   }
>
>   const running = ["streaming", "requested", "approval", "running", "blocked"].includes(part.state);
>   const failed = part.state === "failed" || part.state === "rejected";
>   const label = part.state === "rejected" ? `Denied: ${part.label}` : part.state === "completed" ? `Ran ${part.label}` : part.label;
>
>   return (
>     <Trace>
>       <TraceCollapsible>
>         <TraceCollapsibleTrigger>
>           <TraceLine status={running ? "running" : failed ? "error" : undefined}>
>             <TraceIcon>
>               <WrenchIcon />
>             </TraceIcon>
>             <TraceTitle>{label}</TraceTitle>
>           </TraceLine>
>         </TraceCollapsibleTrigger>
>         <TraceCollapsibleContent>
>           <CodeBlock size="sm">
>             <CodeBlockContent wrap className="max-h-64">
>               {JSON.stringify(part.output ?? part.error ?? part.input, null, 2)}
>             </CodeBlockContent>
>           </CodeBlock>
>         </TraceCollapsibleContent>
>       </TraceCollapsible>
>     </Trace>
>   );
> }
> ```
>
> | What you see | What to do |
> | - | - |
> | Text in a serif font | Rename `--font-geist-sans` to `--font-sans` in `app/layout.tsx`. |
> | Replies show unstyled lists and code | Add the `@source` line to `app/globals.css`. |

## Troubleshooting

| What you see | What it means | What to do |
| - | - | - |
| Your message appears but no reply, and the page shows an error | The route dropped the `x-eve-*` headers, so the hook can't read the reply. | Pass them through as `callAgent` does. |
| "The session is no longer active." | The session has ended, so it can't take more messages. | Reload the page to start a new one, or click **New chat** in the shadcn/ui version. |
| `401` "Sign in first." | `signedInUser` found no user. | Check your sign-in, or use `/login?user=…` while testing. |
| `403` "Not your session." for a user's own chat | The browser kept another user's session, or the owner record is gone, for example after a server restart with the in-memory map. | Store owners in your database. In the shadcn/ui version, click **New chat**, and remove the saved session on sign-out. |
| `401` or `403` from the agent | See [Call an agent from your service](/docs/connect/your-service.md#troubleshooting). | |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.