Skip to content

feat(agent): end-to-end in-product AI agent chat - #121

Merged
gkhngyk merged 8 commits into
mainfrom
feat/agent-chat-end-to-end
May 30, 2026
Merged

gkhngyk merged 8 commits into
mainfrom
feat/agent-chat-end-to-end

Conversation

@gkhngyk

@gkhngyk gkhngyk commented May 29, 2026

Copy link
Copy Markdown
Contributor

Phase 2 of #94. Combines the backend + UI into one PR per maintainer preference — landing this gives a working agent chat at `/dashboard/agent` instead of an intermediate state with a feature flag and no surface.

What ships

  • Sidebar entry "Agent" under Brands, gated on the `ai_agent` feature flag (Growth+ on cloud, unrestricted on self-host)
  • `/dashboard/agent` chat page — conversation list on the left, chat panel on the right, "+ new chat" + delete, plan-gated render with an upgrade card for non-Growth users
  • `POST /api/agent/chat` — Vercel AI SDK streaming via Anthropic Claude Sonnet 4.6, tool-loop, per-turn token bookkeeping
  • `GET / POST /api/agent/conversations` + `GET / DELETE /api/agent/conversations/[id]` — conversation CRUD
  • Persistence: every turn replaces the conversation's messages with the full `UIMessage[]` from `toUIMessageStreamResponse({ onFinish })`; auto-titles the conversation from the first user message; trigger bumps `updated_at` for sidebar re-sort

Tool surface

The agent's tools are thin wrappers around the same MCP data fns the external MCP server exposes — `list_brands`, `get_visibility_summary`, `get_visibility_trend`, `get_competitor_comparison`, `list_citations`, `list_topics`, `list_prompts`, `list_content_opportunities`. The agent sees the exact same data Claude Desktop / Cursor users see, with the same org-ownership scoping. No data path duplication.

Why direct Anthropic, not AI Gateway

The Vercel hook recommends routing through AI Gateway. The #94 cross-cutting requirement is explicit:

LLM provider — reuse the project's multi-provider setup (OpenAI / Anthropic / Google); self-hosted instances use their own keys (BYO). Don't hardcode a provider.

Gateway is Vercel-only; self-hosters running on their own infra can't authenticate. We use `createAnthropic` directly, matching the existing `server/src/lib/ai-provider.js` pattern. Self-host operators supply their own `ANTHROPIC_API_KEY`.

System prompt

Distilled from `skills/ansvisor-aeo-coach/SKILL.md` so the in-product agent behaves like the same analyst the MCP-server users get inside Claude Desktop — just running against the same data via internal tool calls. Key rules: never invent numbers, always call a tool first, ask once if no brand is named, lead with the headline, end with one concrete next step, acknowledge tool gaps explicitly.

Cost guard

The plan flag (`ai_agent`) is the on/off switch; `aiAgentTokenQuota` is the cap. Growth gets 50,000 combined prompt + completion tokens per user per month (~65 typical turns at Claude Sonnet 4.6 averages including tool I/O); enterprise + self-host are unlimited.

The chat endpoint checks both on every request:

  • `hasFeature(plan, 'ai_agent')` → 403 if missing
  • `checkAgentQuota(user, org, plan)` → 429 if exceeded
  • After the stream finishes, `recordAgentTokenUsage` upserts the running monthly bucket

Files

File Change
`web/package.json` `@ai-sdk/anthropic`, `@ai-sdk/react`, `ai`
`web/src/lib/agent/model.ts` Single `AGENT_MODEL` export — Claude Sonnet 4.6 via direct Anthropic
`web/src/lib/agent/system-prompt.ts` Analyst persona + tool reference + rules
`web/src/lib/agent/tools.ts` 8 `tool()` defs wrapping the MCP data fns
`web/src/lib/agent/auth.ts` Dashboard session → `McpAuthContext` shape
`web/src/lib/agent/token-quota.ts` Monthly bucket check + upsert
`web/src/app/api/agent/chat/route.ts` Streaming POST, `streamText` + `toUIMessageStreamResponse`, plan + quota gates, replace-in-place message persistence, auto-title
`web/src/app/api/agent/conversations/route.ts` List + create
`web/src/app/api/agent/conversations/[id]/route.ts` Get + delete
`web/src/app/[locale]/(dashboard)/dashboard/agent/page.tsx` Client component: sidebar + chat + plan gate
`web/src/config/dashboard.ts` Sidebar nav entry, `requiredFeature: 'ai_agent'`
`web/src/components/layout/sidebar.tsx`, `web/messages/en.json` `nav.agent` translation

Out of scope (deferred)

  • Charts (Phase 3 in feat(assistant): in-product conversational AI assistant — chat with your dashboard, with charts #94) — tools return numeric data already structured for Recharts; the next PR teaches the agent to emit a chart spec and renders it inline. For now the agent answers in text, which is the explicit Phase 2 contract.
  • Polish (Phase 4) — suggested starter prompts, conversation rename, token-usage indicator, conversation export.
  • Write tools — `generate_content_brief` and `update_opportunity_status` exist on the MCP server but aren't exposed to the agent yet; they have LLM cost + side effects so they wait until we have a confirmation UX.

Verified

  • ✅ `yarn typecheck` + `yarn format:check` clean after `rm -rf .next` to clear stale generated route types
  • ✅ Smoke load locally — sidebar entry shows up under Brands; `/dashboard/agent` renders the empty state; `+ new chat` calls `POST /api/agent/conversations` and adds a sidebar row; sending a message hits `POST /api/agent/chat` and streams; refreshing the page hydrates messages from `GET /api/agent/conversations/[id]`

Refs #94.

Phase 2 of #94. Sidebar entry under Brands, /dashboard/agent route,
streaming chat backed by Anthropic Claude Sonnet 4.6, conversation
+ message persistence, monthly token quota per the plan flag landed
in PR #120.

Backend:
- web/src/lib/agent/model.ts — direct @ai-sdk/anthropic provider.
  Issue body cross-cutting requirement says "self-hosted instances
  use their own keys (BYO)"; Vercel AI Gateway would lock self-host
  out, so we mirror the existing server/src/lib/ai-provider.js
  pattern.
- web/src/lib/agent/system-prompt.ts — analyst persona distilled
  from skills/ansvisor-aeo-coach/SKILL.md (never invent numbers,
  always call a tool first, lead with the headline, end with one
  actionable next step).
- web/src/lib/agent/tools.ts — Vercel AI SDK tool defs wrapping the
  MCP data layer fns directly (list_brands, get_visibility_summary,
  get_visibility_trend, get_competitor_comparison, list_citations,
  list_topics, list_prompts, list_content_opportunities). Same
  scoping the MCP server uses; no data path duplication.
- web/src/lib/agent/auth.ts — resolves the dashboard session into
  the McpAuthContext shape so the tools can be reused as-is.
- web/src/lib/agent/token-quota.ts — monthly bucket lookup + upsert.
  Self-host / enterprise get unlimited via aiAgentTokenQuota
  undefined.

API routes:
- POST /api/agent/chat — streaming. Verifies session, conversation
  ownership, plan flag, quota; then streamText with the tool surface
  and toUIMessageStreamResponse({ originalMessages, onFinish }).
  onFinish persists the full UIMessage[] (replace-in-place per
  turn, parts kept as jsonb in tool_calls for replay), auto-titles
  the conversation from the first user message, and bumps the
  updated_at trigger so the sidebar re-sorts.
- GET /api/agent/conversations — sidebar list.
- POST /api/agent/conversations — "+ new chat".
- GET/DELETE /api/agent/conversations/[id] — load thread, drop
  thread.

UI:
- web/src/config/dashboard.ts — "Agent" sidebar entry under
  Brands, requiredFeature 'ai_agent', Sparkles icon.
- web/src/components/layout/sidebar.tsx, web/messages/en.json —
  nav.agent translation.
- /dashboard/agent — single client component with conversation
  sidebar + chat area. useChat from @ai-sdk/react with
  DefaultChatTransport pinned to /api/agent/chat. Plan-gated render
  shows an upgrade card when the user's plan doesn't include
  ai_agent. Messages render text parts inline and tool calls as a
  compact pill so the user sees which tool ran.

Refs #94.
HTML doesn't allow <button> nested inside <button>, which Next.js
surfaces as a hydration error. The sidebar's conversation row was a
real <button> (so the entire row was clickable) and the trash icon
was a nested <button> for delete — that's the disallowed pattern.

Swap the outer <button> for a <div role="button" tabIndex={0}> with
the same onClick plus a keyboard handler for Enter / Space so screen
readers + keyboard users keep the same affordance. Inner trash stays a
real <button>.
POST /api/agent/chat was returning 400 "conversationId required" on
the first message of a brand-new chat. Root cause: setActiveId is an
async React state update, so when sendMessage runs immediately after
in the same tick, prepareSendMessagesRequest reads the still-null
state from its closure and posts conversationId: null.

Two-part fix so neither path can drift again:

- activeIdRef mirrors activeId; useEffect keeps it in sync, and
  prepareSendMessagesRequest reads from the ref instead of the
  stale state closure. Covers the case where a user clicks an
  existing conversation in the sidebar and immediately types.
- onSubmit captures the resolved id into a local, updates the ref
  synchronously when it just created a new conversation, and
  passes the id via sendMessage's body option as well. Belt-and-
  suspenders: even if the ref hadn't been touched yet, the body
  argument arrives in prepareSendMessagesRequest's body param and
  the spread order lets it take priority.
streamText is single-step by default in v6 — the model fires a tool
call and ends the turn before ever seeing the result. The chat in the
test session showed exactly this: "Hangi marka için bakmamı
istersiniz?" + tool-list_brands part, then nothing. The user had to
manually re-ask before Claude (now seeing the prior tool result in
the second turn's context) answered with the brand list.

stepCountIs(20) re-runs the generation after each tool call so the
agent interprets the result and either answers or calls another tool.
20 matches the ToolLoopAgent default — plenty of headroom for the
typical 'list_brands → get_visibility_summary → answer' chain
without burning tokens forever on a pathological loop.
…omponent

The agent answers in markdown — lists, **bold**, headings, links —
but the chat bubble was rendering text parts as plain <p> with
whitespace-pre-wrap, so the user saw the raw markup characters in
the response. Reuse @/components/ui/markdown (the same component the
insights detail page uses for AI responses) for assistant text. User
messages stay plain — they're typed input, not authored markdown,
and the chat bubble contrast reads cleaner without prose styling.

Tool-call pills are unchanged.
gkhngyk added 2 commits May 29, 2026 17:29
Desktop has no top bar in the dashboard layout (the mobile nav is md:hidden),
so subtracting 3.5rem from 100vh left a ~56px gap below both the conversation
list and the message composer — looking like a phantom padding-bottom. On
mobile the same calc was 8px short (mobile nav is h-16 = 4rem, not 3.5rem).

Switch to h-[calc(100vh-4rem)] md:h-screen so the agent shell matches the
parent main element's border box on both breakpoints. -m-6 already cancels
the parent's p-6, so border-box height = main's border-box height and the
scroll content height = main's content area (no overflow on either axis).
The previous chip showed the raw AI SDK state string ('output-available')
next to the tool name — internal jargon that doesn't help a user understand
what the agent actually did. It also wasted the only interactive surface we
had on a part that carries the most debug-worthy payload of the turn.

The new ToolCallDisclosure renders the chip as a button: spinner while the
call is in-flight, wrench + chevron once it has a result. Clicking expands
an inline console-style panel with the input args and output result as
pretty-printed JSON, plus an error block if the call failed. Same pattern
Claude / ChatGPT / Cursor ship for tool runs, and it works for every tool
we already register without per-tool formatting code.
Cloud rollout for the in-product agent had two open problems: every turn
billed Ansvisor's Anthropic account, and the feature was gated to Growth+
to keep that bill bounded. Both go away with BYOK.

What's new
- Settings → Agent: org admins paste their own Anthropic key. Stored
  encrypted at rest (AES-256-GCM) in organizations; the master key lives
  in the new ANSVISOR_ENCRYPTION_KEY env, never touches Postgres. UI
  shows configured/last4/set-at metadata, never the plaintext.
- /api/settings/anthropic-key (GET / PUT / DELETE): GET surfaces only the
  display metadata (any member can read), PUT and DELETE are admin-only.
  Soft format validation on save; first chat turn is the rigorous check.
- /api/agent/chat + /api/agent/conversations now gate on 'is a key
  configured?' instead of token quota. Missing key returns 403 with
  code 'missing_anthropic_key' so the UI can route to Settings.
- web/src/lib/agent/key.ts resolves the key per request: cloud → org
  (decrypt envelope), self-host → ANTHROPIC_API_KEY env. Self-host gets
  the feature unconditionally; cloud gates on BYOK.
- model.ts is now a buildAgentModel(key) factory so streamText can be
  driven with the caller's key per turn.
- Agent page renders a KeyMissingState (CTA → Settings → Agent) when
  cloud and no key set, instead of letting the user submit and 403.

Plans
- ai_agent feature added to Starter; no longer a Growth+ gated feature
  on cloud. The real gate is BYOK.
- aiAgentTokenQuota removed entirely from PlanLimits — no Growth quota,
  no Omit gymnastics in isWithinLimit / useFeatureGate.withinLimit /
  plan-guard.enforceLimit. agent_token_usage table stays for analytics
  (recordAgentTokenUsage still writes on each turn).

Encryption
- AES-256-GCM, 12-byte IV per encryption, GCM auth tag attached. Stored
  as a JSON envelope { v, iv, tag, ct } so we can version-bump the
  scheme later. Master key validated at load — refuses to write unless
  ANSVISOR_ENCRYPTION_KEY decodes to exactly 32 bytes.

Migration
- 00010_org_anthropic_keys.sql adds anthropic_api_key_encrypted,
  anthropic_api_key_last4, anthropic_api_key_set_at,
  anthropic_api_key_set_by to organizations. set_by FK to profiles is
  ON DELETE SET NULL so dropping a profile preserves the audit trail.

Deploy notes
- Generate ANSVISOR_ENCRYPTION_KEY: 'openssl rand -base64 32'. Add it
  to web/.env locally and to Vercel env (production + preview +
  development) before the cloud rollout. Losing or rotating it makes
  saved keys unrecoverable — users will see the empty state and need
  to re-paste, no data loss otherwise.
@gkhngyk
gkhngyk merged commit 558197d into main May 30, 2026
2 checks passed
@gkhngyk
gkhngyk deleted the feat/agent-chat-end-to-end branch May 30, 2026 13:16
gkhngyk added a commit that referenced this pull request May 31, 2026
Bundles the in-product Agent epic (#120, #121), the BYOK rollout on
cloud, the MCP toolkit expansion (#109, #110, #116, #117, #118), the
insights performance fix (#114), and the invite-accept flow rebuild
(#127, #129, #130) into a tagged release.

See CHANGELOG.md for the full notes.
gkhngyk added a commit that referenced this pull request May 31, 2026
Bundles the in-product Agent epic (#120, #121), the BYOK rollout on
cloud, the MCP toolkit expansion (#109, #110, #116, #117, #118), the
insights performance fix (#114), and the invite-accept flow rebuild
(#127, #129, #130) into a tagged release.

See CHANGELOG.md for the full notes.

This branch was successfully deployed

1 active deployment
Preview — 323da6d2 Deployed May 29, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant