@cntyclub/agent-react
v0.36.5
Published
Embeddable AI agent chat widget for Country Club dashboards — floating button, popup panel, fullscreen Agent Mode, MCP tool approvals, and paginated result tables. Built exclusively on @cntyclub/ui-react.
Readme
@cntyclub/agent-react
Embeddable AI agent chat widget for Country Club dashboards — the frontend for the
backend's Agent Mode (agent_mode Django app). A floating button opens a popup
chat panel (desktop) or fullscreen chat (mobile); an Agent Mode button expands the
popup to fullscreen. The agent can call MCP tools on the user's behalf: read-only tools
run automatically, write tools require in-chat user approval. Tabular tool results are
rendered as paginated, searchable tables.
Built exclusively on @cntyclub/ui-react —
no custom styles or components. Light/dark mode follows the host dashboard's theme
tokens automatically.
Install
pnpm add @cntyclub/agent-react @cntyclub/ui-reactRequirements:
- React 19+
- Tailwind CSS v4 with the UI kit stylesheet + sources configured:
@import "tailwindcss";
@import "@cntyclub/ui-react/styles.css";
@source "../node_modules/@cntyclub/ui-react/src";
@source "../node_modules/@cntyclub/agent-react/src";- An Agent Mode client ID, created in the Country Club office panel (Office → AI → Agent Mode → Create Agent). The client ID identifies the agent only; the backend resolves the MCP connector, model, and system prompt from it.
- The host page's origin must be on the agent's allowed domains list — other origins get a CORS error from the backend.
- A logged-in user: every request carries the user's Country Club JWT. Users who are not signed in cannot chat.
Usage
- Create the agent config file (
lib/agent/agent-config.ts):
import { defineAgentConfig } from "@cntyclub/agent-react";
import { getAccessToken } from "@/lib/api/tokens";
export const agentConfig = defineAgentConfig({
clientId: process.env.NEXT_PUBLIC_AGENT_CLIENT_ID!,
apiBaseUrl: process.env.NEXT_PUBLIC_API_URL!,
getAccessToken,
agentName: "Assistant",
suggestions: ["Show my target companies", "List my products"],
pages: [
{
tools: ["business_target_companies_list"],
route: "/dashboard/target-companies",
title: "Target Companies",
},
{
tools: ["business_companies_get"],
route: "/dashboard/company/:id",
title: "Company",
buildRoute: (args) => (args.id ? `/dashboard/company/${args.id}` : null),
},
],
});- Mount the widget inside your authenticated layout (client component):
"use client";
import { AgentWidget } from "@cntyclub/agent-react";
import { useRouter } from "next/navigation";
import { agentConfig } from "@/lib/agent/agent-config";
export function DashboardAgent() {
const router = useRouter();
return <AgentWidget config={{ ...agentConfig, navigate: (path) => router.push(path) }} />;
}pages + navigate power page-follow: in popup mode, when the agent uses a tool
that maps to a page, the host app navigates there while the chat shows the same data.
Telling the agent where the user is (getPageContext)
Someone standing inside an event who types "customer experience?" means that event's
people. Without page context the agent has no way to know that, so it lists the user's
events and asks which one — or worse, guesses. getPageContext is read fresh on every
send and travels with the message:
getPageContext: () => {
const match = window.location.pathname.match(/\/dashboard\/events\/([^/]+)\/?([^/]*)/);
if (!match) return { page: "Events", route: window.location.pathname };
return {
page: `${match[2] || "overview"} tab`,
route: window.location.pathname,
// `focus.type` is the noun the backend uses: "event" → the agent passes event_id.
focus: { type: "event", id: match[1] },
filters: { state: "registered" }, // what the list on screen is showing
notes: ["The host is preparing the seating."],
};
},A focus becomes the subject of the turn: every tool call uses that id, and the agent is
told not to list the user's records to find it, nor to ask which one they mean. It
still asks before leaving that record.
Dashboard instructions (instructions)
Product knowledge only the host app has — what its tabs and lists are, which states and
filters exist, how answers should look, when to ask instead of guessing — belongs in
instructions. It is appended to the backend's system prompt on every turn (≤ 8000 chars,
string or a function returning one). It cannot relax the backend's privacy, scope or
approval rules: the shared-conversation privacy rule is always applied last.
Questions the agent asks
When a request is ambiguous the agent calls ask_user_question instead of guessing, and
the widget renders a question card in the transcript: one question at a time, tappable
options — a single choice or checkboxes — always plus an Other the user can type into,
Back/Next between questions and Submit on the last. The turn ends when the card
appears; submitting posts the answers as an ordinary message (so they are part of the
conversation) and locks the card, which then shows what was chosen — including after a
reload, and for everyone in a shared conversation.
Option labels are rewritten for reading before they are shown: models hand back their
own field names (vp_senior_dir, checked_in, dm_titles), and a question a person is
being asked should not look like a database column, so underscores go, known
abbreviations are spelled out ("VP senior director", "C-suite", "DM titles") and the
model's own duplicate "Other" is dropped. The wording shown is the wording sent back as
the answer.
A question with no options renders as a plain text box, so an open question ("what
are you actually trying to decide?") works the same way. The backend normalizes
whatever shape the model sent (bare strings, choices instead of options, a
hoisted multi_select) rather than dropping the question, and refuses a tool call
repeated with identical arguments — a mis-shaped ask used to retry until the
iteration cap and fill the transcript with cards nobody could answer.
Nothing to wire: AgentWidget/AgentPanel handle it. AgentQuestionCard and
formatQuestionAnswers are exported for custom shells.
Editing a generated file
A CSV the agent produced is a starting point, not a verdict, so the document card opens into an editor: the file renders as a real table, clicking a cell edits it (Tab across, Enter down), rows can be added or deleted, and Save publishes a new version and re-renders the download. Text and Markdown files open in a plain editor; DOCX and PDF stay preview + download.
Every save is a version. History lists them newest first — who saved it, when, and what changed ("2 row(s) added, 1 row(s) edited") — and Restore brings an earlier body back as a new version, so going back is itself recorded rather than erasing anything. Saving unchanged text creates nothing. In a shared conversation any participant who can post can edit, and the card in the transcript follows the file: reopen the chat later and you see the current version, not the body the agent first generated.
Nothing to wire — the card handles it (AgentPanel provides the API client via
AgentApiProvider). parseCsv / toCsv / normalizeGrid are exported if you need to
work with the same CSV round-trip elsewhere.
Finishing an interrupted answer
A streamed turn lives inside its HTTP request, so reloading the page mid-answer used to
leave the tool chips that had already run with no reply under them — wait for the turn to
finish and the same reload showed everything, which is exactly the shape of the bug. The
backend now reports resumable when a conversation's last turn is still owed an ending
(a user message with no answer, a dangling tool result, tool calls that never ran), and
opening the conversation quietly finishes it. It stays a no-op when an approval or a
question card is waiting — those are the user's move, not the agent's — and it is
attempted once per conversation per session.
When a conversation is gone
A chat that was deleted, or that the user lost access to, used to sit in the sidebar,
restore itself on load and refuse every message ("You can't post in this
conversation"). Now the backend says which it is via a code
(conversation_deleted / conversation_no_access / conversation_not_found), a
conversation the user left is no longer listed (posting in one re-joins it), and the
widget recovers on its own: it drops the dead chat, opens a fresh one, sends the
message there, and says so. The user is never left typing into a locked door.
API schema (OpenAPI)
The backend publishes a dedicated, scoped OpenAPI document for Agent Mode:
- Schema:
GET {API_BASE}/agent-mode/schema/(YAML) - Swagger UI:
{API_BASE}/agent-mode/docs/
This repo vendors that document at api-spec/agent-mode-api.yaml
and generates TypeScript types from it into src/api/schema.ts (committed). All wire
types in src/types.ts derive from the generated schema, so the client cannot drift
from the backend contract silently.
Update workflow when the backend API changes:
curl https://api.country.club/agent-mode/schema/ -o api-spec/agent-mode-api.yaml
pnpm gen:api # regenerates src/api/schema.ts
pnpm typecheck # surfaces any breaking contract changes immediatelyConsumers can also import the full typed surface for their own tooling:
import type { AgentModePaths, AgentModeComponents, AgentModeOperations } from "@cntyclub/agent-react";Mentions when the agent is closed
AgentWidget announces "X mentioned you" itself — a toast over the panel while it's
open, a chip above its own launcher while it's closed. An app that renders its own
launcher and mounts the agent only while it's open (both dashboards do) has nothing
running in the closed state, so mount the standalone watcher next to that launcher:
"use client";
import { AgentMentionAlerts } from "@cntyclub/agent-react";
export function DashboardAgentLauncher() {
const { open, setOpen } = useAgentDock();
return (
<>
<AgentMentionAlerts config={config} hidden={open} onOpen={() => setOpen(true)} />
{!open ? <button onClick={() => setOpen(true)}>…</button> : null}
</>
);
}It writes the mention's conversation/message into the URL before calling onOpen, so a
widget that mounts on open follows the link and lands on the message. Dismissals are
shared with the panel, so nothing is announced twice.
Reactions, read receipts
In a public conversation every message can be reacted to — the assistant's answers included, and the assistant is never told about it (reactions never enter the LLM context). Six emoji, fixed: ❤️ 👍 ✌️ ✅ 😁 👎. The author is notified the same way a mention notifies them, in the panel and above a closed launcher. Private conversations have no reactions.
"Seen by" avatars sit beside the timestamp of the newest message each participant has read — never under a reader's own message, capped with a "+N", and always on the timestamp's line.
Exports
AgentWidget— the complete widget (launcher + popup + fullscreen Agent Mode).AgentPanel— just the chat surface, for custom shells.AgentQuestionCard/formatQuestionAnswers— the agent's question card, for custom shells.AgentMentionAlerts— mention chips above a host app's own launcher (closed state).useAgentChat(config)— headless chat state (messages, approvals, conversations).useAgentMentions(config)— headless unread-@-mention watcher.AgentApiClient— low-level API client.buildAgentDeepLink/writeAgentDeepLink— links that open one conversation/message.defineAgentConfig, plus all public types.
Development
pnpm install # uses a link: to the sibling UI kit repo for local dev
pnpm typecheck
pnpm build # tsup → dist/
./publish.sh # publish to npm (needs NPM_TOKEN in .env)