Skip to content

armgit / crm

Public Imported from GitHub
0

Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.

TypeScript

feat(app): CMP-46 add the private agent builder workspace (#62)

grimf64c88fe9d3e
diff --git a/README.md b/README.md
index 73fc6934..b61dda71 100644
--- a/README.md
+++ b/README.md
@@ -319,7 +319,7 @@ short version:
| Command | |
| --- | --- |
-| `bun run dev` | Everything, in watch mode |
+| `bun run dev` | Prepare the local database, then run everything in dependency-aware watch mode |
| `bun run build` | Build all apps and packages |
| `bun run test` | Run the test suite |
| `bun run check-types` | `tsc --noEmit` everywhere |
diff --git a/apps/app/AGENTS.md b/apps/app/AGENTS.md
index 8bd0e390..643577df 100644
--- a/apps/app/AGENTS.md
+++ b/apps/app/AGENTS.md
@@ -1,5 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
+
# This is NOT the Next.js you know
-This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
+This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
+
+This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
+
<!-- END:nextjs-agent-rules -->
diff --git a/apps/app/app/(app)/[slug]/(agent-builder)/agents/[agentId]/page.tsx b/apps/app/app/(app)/[slug]/(agent-builder)/agents/[agentId]/page.tsx
new file mode 100644
index 00000000..741214ce
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/(agent-builder)/agents/[agentId]/page.tsx
@@ -0,0 +1,59 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { Suspense } from "react";
+import { TeamAgentDetail } from "@/components/agent-builder/team-agent-detail";
+import { PageShellFallback } from "@/components/page-shell";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+
+export const metadata: Metadata = { title: "Team agent" };
+
+export default function TeamAgentPage({
+ params,
+}: {
+ params: Promise<{ agentId: string }>;
+}) {
+ return (
+ <Suspense fallback={<PageShellFallback />}>
+ <PrefetchedTeamAgent params={params} />
+ </Suspense>
+ );
+}
+
+async function PrefetchedTeamAgent({
+ params,
+}: {
+ params: Promise<{ agentId: string }>;
+}) {
+ const { agentId } = await params;
+ if (agentId === "team") notFound();
+
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+ const agentQuery = trpc.agents.byId.queryOptions({ id: agentId });
+ const runsQuery = trpc.agents.history.queryOptions({
+ id: agentId,
+ limit: 50,
+ });
+ const activityQuery = trpc.agents.activity.queryOptions({
+ id: agentId,
+ limit: 100,
+ });
+
+ const [agent, runs, activity] = await Promise.all([
+ queryClient.fetchQuery(agentQuery),
+ queryClient.fetchQuery(runsQuery),
+ queryClient.fetchQuery(activityQuery),
+ ]);
+
+ return (
+ <HydrateClient>
+ <TeamAgentDetail
+ agentId={agentId}
+ initialAgent={agent}
+ initialRuns={runs}
+ initialActivity={activity}
+ />
+ </HydrateClient>
+ );
+}
diff --git a/apps/app/app/(app)/[slug]/(agent-builder)/agents/loading.tsx b/apps/app/app/(app)/[slug]/(agent-builder)/agents/loading.tsx
new file mode 100644
index 00000000..6884992b
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/(agent-builder)/agents/loading.tsx
@@ -0,0 +1,5 @@
+import { PageShellFallback } from "@/components/page-shell";
+
+export default function AgentsLoading() {
+ return <PageShellFallback />;
+}
diff --git a/apps/app/app/(app)/[slug]/(agent-builder)/agents/page.tsx b/apps/app/app/(app)/[slug]/(agent-builder)/agents/page.tsx
new file mode 100644
index 00000000..8edbb7e7
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/(agent-builder)/agents/page.tsx
@@ -0,0 +1,49 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import { TeamAgentsIndex } from "@/components/agent-builder/team-agents-index";
+import {
+ PageShell,
+ PageShellContent,
+ PageShellDescription,
+ PageShellHeader,
+ PageShellHeading,
+ PageShellLoading,
+ PageShellTitle,
+} from "@/components/page-shell";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+
+export const metadata: Metadata = { title: "Agents" };
+
+export default function AgentsPage() {
+ return (
+ <PageShell className="min-h-0">
+ <PageShellHeader>
+ <PageShellHeading>
+ <PageShellTitle>Team agents</PageShellTitle>
+ <PageShellDescription>
+ Durable automations created from private agent-builder chats.
+ </PageShellDescription>
+ </PageShellHeading>
+ </PageShellHeader>
+
+ <PageShellContent className="min-h-0">
+ <Suspense fallback={<PageShellLoading />}>
+ <PrefetchedTeamAgents />
+ </Suspense>
+ </PageShellContent>
+ </PageShell>
+ );
+}
+
+async function PrefetchedTeamAgents() {
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+ const agents = await queryClient.fetchQuery(trpc.agents.list.queryOptions());
+
+ return (
+ <HydrateClient>
+ <TeamAgentsIndex initialAgents={agents} />
+ </HydrateClient>
+ );
+}
diff --git a/apps/app/app/(app)/[slug]/(agent-builder)/chat/[chatId]/page.tsx b/apps/app/app/(app)/[slug]/(agent-builder)/chat/[chatId]/page.tsx
new file mode 100644
index 00000000..2f08c456
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/(agent-builder)/chat/[chatId]/page.tsx
@@ -0,0 +1,52 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import { AgentBuilderChat } from "@/components/agent-builder/agent-builder-chat";
+import { isSharedChatToken } from "@/lib/chat-route";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+
+export const metadata: Metadata = { title: "Agent chat" };
+
+export default function AgentChatPage({
+ params,
+}: {
+ params: Promise<{ chatId: string }>;
+}) {
+ return (
+ <Suspense fallback={<ChatFallback />}>
+ <PrefetchedAgentChat params={params} />
+ </Suspense>
+ );
+}
+
+async function PrefetchedAgentChat({
+ params,
+}: {
+ params: Promise<{ chatId: string }>;
+}) {
+ const { chatId } = await params;
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+ const sharedChat = isSharedChatToken(chatId);
+
+ if (sharedChat) {
+ await queryClient.prefetchQuery(
+ trpc.conversations.shared.queryOptions({ token: chatId }),
+ );
+ } else {
+ await queryClient.prefetchQuery(
+ trpc.conversations.builderById.queryOptions({
+ id: chatId,
+ }),
+ );
+ }
+
+ return <AgentBuilderChat conversationId={chatId} />;
+}
+
+function ChatFallback() {
+ return (
+ <main className="flex min-h-0 flex-1 items-center justify-center">
+ <span className="text-muted-foreground text-sm">Opening chat…</span>
+ </main>
+ );
+}
diff --git a/apps/app/app/(app)/[slug]/(agent-builder)/chat/page.tsx b/apps/app/app/(app)/[slug]/(agent-builder)/chat/page.tsx
new file mode 100644
index 00000000..5358a0c3
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/(agent-builder)/chat/page.tsx
@@ -0,0 +1,43 @@
+import type { Metadata } from "next";
+import { Suspense } from "react";
+import { AgentBuilderHome } from "@/components/agent-builder/agent-builder-home";
+import { requireSession } from "@/lib/session";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+
+export const metadata: Metadata = { title: "Chat" };
+
+export default function ChatPage() {
+ return (
+ <Suspense fallback={<ChatHomeFallback />}>
+ <ChatHome />
+ </Suspense>
+ );
+}
+
+async function ChatHome() {
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+
+ const [session] = await Promise.all([
+ requireSession(),
+ queryClient.prefetchQuery(
+ trpc.conversations.builderResources.queryOptions({ q: "" }),
+ ),
+ queryClient.prefetchQuery(trpc.google.status.queryOptions()),
+ ]);
+
+ return (
+ <HydrateClient>
+ <AgentBuilderHome name={session.user.name} />
+ </HydrateClient>
+ );
+}
+
+function ChatHomeFallback() {
+ return (
+ <main className="flex min-h-0 flex-1 items-center justify-center">
+ <span className="text-muted-foreground text-sm">Opening chat…</span>
+ </main>
+ );
+}
diff --git a/apps/app/app/(app)/[slug]/(agent-builder)/layout.tsx b/apps/app/app/(app)/[slug]/(agent-builder)/layout.tsx
new file mode 100644
index 00000000..229b5844
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/(agent-builder)/layout.tsx
@@ -0,0 +1,54 @@
+import { Suspense } from "react";
+import { AgentBuilderShell } from "@/components/agent-builder/agent-builder-shell";
+import { HydrateClient } from "@/lib/trpc/hydrate";
+import { getServerQueryClient, getServerTrpc } from "@/lib/trpc/server";
+
+export default function AgentBuilderLayout({
+ children,
+}: Readonly<{ children: React.ReactNode }>) {
+ return (
+ <Suspense
+ fallback={
+ <AgentBuilderShell>
+ <AgentBuilderContentFallback />
+ </AgentBuilderShell>
+ }
+ >
+ <PrefetchedAgentBuilderShell>{children}</PrefetchedAgentBuilderShell>
+ </Suspense>
+ );
+}
+
+function AgentBuilderContentFallback() {
+ return (
+ <main className="flex min-h-0 flex-1 items-center justify-center">
+ <span className="text-muted-foreground text-sm">Loading chat…</span>
+ </main>
+ );
+}
+
+async function PrefetchedAgentBuilderShell({
+ children,
+}: Readonly<{ children: React.ReactNode }>) {
+ const trpc = getServerTrpc();
+ const queryClient = getServerQueryClient();
+ const conversationsQuery = trpc.conversations.builderList.queryOptions();
+ const agentsQuery = trpc.agents.list.queryOptions();
+
+ const [conversations, agents] = await Promise.all([
+ queryClient.fetchQuery(conversationsQuery),
+ queryClient.fetchQuery(agentsQuery),
+ ]);
+ const updatedAt = Math.min(
+ queryClient.getQueryState(conversationsQuery.queryKey)?.dataUpdatedAt ?? 0,
+ queryClient.getQueryState(agentsQuery.queryKey)?.dataUpdatedAt ?? 0,
+ );
+
+ return (
+ <HydrateClient>
+ <AgentBuilderShell sidebarData={{ conversations, agents, updatedAt }}>
+ {children}
+ </AgentBuilderShell>
+ </HydrateClient>
+ );
+}
diff --git a/apps/app/app/(app)/[slug]/(agent-builder)/loading.tsx b/apps/app/app/(app)/[slug]/(agent-builder)/loading.tsx
new file mode 100644
index 00000000..6e32c15e
--- /dev/null
+++ b/apps/app/app/(app)/[slug]/(agent-builder)/loading.tsx
@@ -0,0 +1,24 @@
+import { Skeleton } from "@crm/ui/components/skeleton";
+
+export default function AgentBuilderRouteLoading() {
+ return (
+ <main className="flex min-h-0 flex-1 flex-col" aria-busy="true">
+ <header className="flex h-12 shrink-0 items-center border-b px-4 sm:px-5">
+ <Skeleton className="h-4 w-40 max-w-full" />
+ </header>
+ <div className="min-h-0 flex-1 overflow-hidden">
+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-5 px-4 py-6 sm:px-5 sm:py-9">
+ <Skeleton className="ms-auto h-16 w-2/3 max-w-[520px]" />
+ <div className="flex max-w-[640px] flex-col gap-2">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-11/12" />
+ <Skeleton className="h-4 w-8/12" />
+ </div>
+ </div>
+ </div>
+ <span role="status" className="sr-only">
+ Opening chat
+ </span>
+ </main>
+ );
+}
diff --git a/apps/app/app/api/[...path]/route.ts b/apps/app/app/api/[...path]/route.ts
index 6558d550..1b421157 100644
--- a/apps/app/app/api/[...path]/route.ts
+++ b/apps/app/app/api/[...path]/route.ts
@@ -1,17 +1,7 @@
-import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib";
import { connection } from "next/server";
+import { bufferedProxyResponse } from "@/lib/api-proxy-response";
import { API_URL } from "@/lib/env";
-function decode(buf: Buffer, encoding: string | null): Buffer {
- const enc = (encoding ?? "").toLowerCase();
- try {
- if (enc.includes("br")) return brotliDecompressSync(buf);
- if (enc.includes("gzip")) return gunzipSync(buf);
- if (enc.includes("deflate")) return inflateSync(buf);
- } catch {}
- return buf;
-}
-
async function handler(request: Request): Promise<Response> {
await connection();
@@ -79,7 +69,10 @@ async function handler(request: Request): Promise<Response> {
}
}
- if (upstream.headers.get("content-type")?.includes("text/event-stream")) {
+ if (
+ upstream.headers.get("content-type")?.includes("text/event-stream") ||
+ upstream.headers.has("content-disposition")
+ ) {
return new Response(upstream.body, {
status: upstream.status,
statusText: upstream.statusText,
@@ -87,14 +80,7 @@ async function handler(request: Request): Promise<Response> {
});
}
- const raw = Buffer.from(await upstream.arrayBuffer());
- const body = decode(raw, upstream.headers.get("content-encoding"));
-
- return new Response(new Uint8Array(body), {
- status: upstream.status,
- statusText: upstream.statusText,
- headers: responseHeaders,
- });
+ return bufferedProxyResponse(upstream, responseHeaders, request.method);
}
export {
diff --git a/apps/app/app/eve/v1/[...path]/route.ts b/apps/app/app/eve/v1/[...path]/route.ts
index eac3e293..5c7e4508 100644
--- a/apps/app/app/eve/v1/[...path]/route.ts
+++ b/apps/app/app/eve/v1/[...path]/route.ts
@@ -1,3 +1,4 @@
+import { db } from "@crm/db";
import { connection } from "next/server";
import {
AGENT_URL,
@@ -45,9 +46,47 @@ async function handler(request: Request): Promise<Response> {
const contactId = request.headers.get("x-crm-contact");
const companyId = request.headers.get("x-crm-company");
const dealId = request.headers.get("x-crm-deal");
+ const builderConversationId = request.headers.get(
+ "x-crm-builder-conversation",
+ );
+ const requestedSession = sessionFromPath(url.pathname);
headers.delete("x-crm-contact");
headers.delete("x-crm-company");
headers.delete("x-crm-deal");
+ headers.delete("x-crm-builder-conversation");
+
+ if (requestedSession) {
+ const conversation = await db.agentConversation.findUnique({
+ where: { sessionId: requestedSession },
+ select: { userId: true },
+ });
+ if (conversation && conversation.userId !== session.user.id) {
+ return Response.json(
+ { error: "Conversation not found." },
+ { status: 404 },
+ );
+ }
+ }
+
+ if (builderConversationId) {
+ const conversation = await db.agentConversation.findFirst({
+ where: {
+ id: builderConversationId,
+ userId: session.user.id,
+ kind: "BUILDER",
+ },
+ select: { sessionId: true },
+ });
+ if (
+ !conversation ||
+ (requestedSession && conversation.sessionId !== requestedSession)
+ ) {
+ return Response.json(
+ { error: "Conversation not found." },
+ { status: 404 },
+ );
+ }
+ }
headers.set(
"authorization",
@@ -120,3 +159,8 @@ export {
function cuid(value: string | null): string | undefined {
return value && /^[a-z0-9]{20,32}$/.test(value) ? value : undefined;
}
+
+function sessionFromPath(pathname: string): string | null {
+ const match = pathname.match(/\/eve\/v1\/session\/([^/]+)/);
+ return match?.[1] ? decodeURIComponent(match[1]) : null;
+}
diff --git a/apps/app/components/agent-builder/agent-builder-chat.tsx b/apps/app/components/agent-builder/agent-builder-chat.tsx
new file mode 100644
index 00000000..89d5fe03
--- /dev/null
+++ b/apps/app/components/agent-builder/agent-builder-chat.tsx
@@ -0,0 +1,1505 @@
+"use client";
+
+import Add from "@carbon/icons-react/es/Add";
+import Application from "@carbon/icons-react/es/Application";
+import ArrowRight from "@carbon/icons-react/es/ArrowRight";
+import Building from "@carbon/icons-react/es/Building";
+import Checkmark from "@carbon/icons-react/es/Checkmark";
+import CheckmarkFilled from "@carbon/icons-react/es/CheckmarkFilled";
+import Copy from "@carbon/icons-react/es/Copy";
+import Partnership from "@carbon/icons-react/es/Partnership";
+import Play from "@carbon/icons-react/es/Play";
+import Renew from "@carbon/icons-react/es/Renew";
+import Reply from "@carbon/icons-react/es/Reply";
+import ThumbsDown from "@carbon/icons-react/es/ThumbsDown";
+import ThumbsUp from "@carbon/icons-react/es/ThumbsUp";
+import User from "@carbon/icons-react/es/User";
+import WarningAlt from "@carbon/icons-react/es/WarningAlt";
+import {
+ AsyncButtonContent,
+ useAsyncAction,
+} from "@crm/ui/components/async-action";
+import { Button } from "@crm/ui/components/button";
+import { Icon } from "@crm/ui/components/icon";
+import { Markdown } from "@crm/ui/components/markdown";
+import { Reasoning } from "@crm/ui/components/reasoning";
+import { Skeleton } from "@crm/ui/components/skeleton";
+import { useMountEffect } from "@crm/ui/hooks/use-mount-effect";
+import { cn } from "@crm/ui/lib/utils";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { Client, type MessageStreamEvent } from "eve/client";
+import type { EveMessage, EveMessageInputRequest } from "eve/react";
+import Link from "next/link";
+import { type ReactNode, useState } from "react";
+import { toast } from "sonner";
+import {
+ AgentClarificationComposer,
+ type ClarificationResponse,
+} from "@/components/agent-clarification-composer";
+import { LocalDateTime } from "@/components/local-date-time";
+import {
+ consumeBuilderCommand,
+ hasCreateAgentCommand,
+} from "@/lib/agent-builder";
+import {
+ builderConversationIsWorking,
+ completedBuilderSteps,
+ displayedArtifactVersionId,
+ latestCompletedArtifactVersionId,
+ reviewVersionId,
+} from "@/lib/agent-builder-state";
+import {
+ type AgentTurnFailure,
+ conversationTimeline,
+ dealListResultOf,
+ eventStreamSettled,
+ latestTurnFailure,
+ mergeDealListResultPages,
+ messagesFromEvents,
+ pendingQuestion,
+ splitMarkdownTable,
+ toTranscript,
+} from "@/lib/agent-transcript";
+import { isSharedChatToken } from "@/lib/chat-route";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+import { useWorkspaceUrl } from "@/lib/use-workspace-url";
+import { AgentCodeWorkspace } from "./agent-code-workspace";
+import { AgentComposer, type BuilderPrompt } from "./agent-composer";
+import {
+ ChatAttachmentChip,
+ ChatCommandChip,
+ ChatReferenceChip,
+} from "./chat-chips";
+import { DealListResultTable } from "./deal-list-result";
+import { DeleteChatAction } from "./delete-chat-action";
+import { ShareChatDialog } from "./share-chat-dialog";
+
+type Conversation = RouterOutputs["conversations"]["builderById"];
+type SharedConversation = RouterOutputs["conversations"]["shared"];
+
+const BUILDER_STEPS = ["Scope", "Instructions", "Manifest", "Review"] as const;
+type DraftVersion = {
+ id: string;
+ status: string;
+ manifest: unknown;
+};
+
+type BuilderSubmission = {
+ id: string;
+ createdAt: string;
+ commandType: "CHAT" | "CREATE_AGENT";
+ message: unknown;
+ status: string;
+ errorMessage: string | null;
+};
+
+export function AgentBuilderChat({
+ conversationId,
+}: {
+ conversationId: string;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const sharedChat = isSharedChatToken(conversationId);
+ const [liveStream, setLiveStream] = useState<{
+ key: string;
+ events: readonly MessageStreamEvent[];
+ } | null>(null);
+ const conversation = useQuery({
+ ...trpc.conversations.builderById.queryOptions({ id: conversationId }),
+ enabled: !sharedChat,
+ refetchInterval: (query) => {
+ const data = query.state.data;
+ return data && builderConversationNeedsPolling(data) ? 2500 : false;
+ },
+ });
+ const shared = useQuery({
+ ...trpc.conversations.shared.queryOptions({ token: conversationId }),
+ enabled: sharedChat,
+ refetchInterval: (query) =>
+ sharedConversationNeedsPolling(query.state.data) ? 5000 : false,
+ });
+ const events = useQuery({
+ ...trpc.conversations.events.queryOptions({
+ id: conversationId,
+ limit: 5000,
+ }),
+ enabled: !sharedChat && Boolean(conversation.data?.sessionId),
+ refetchInterval: (query) =>
+ conversation.data &&
+ (builderConversationNeedsPolling(conversation.data) ||
+ !eventStreamSettled(query.state.data ?? []))
+ ? 2500
+ : false,
+ });
+ const submit = useMutation(
+ trpc.conversations.submitBuilder.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.conversations.builderById.pathKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.conversations.builderList.pathKey(),
+ }),
+ ]);
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+ const answerQuestion = useMutation(
+ trpc.conversations.answerBuilderQuestion.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.conversations.builderById.pathKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.conversations.builderList.pathKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.conversations.events.pathKey(),
+ }),
+ ]);
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+ const markRead = useMutation(
+ trpc.conversations.markRead.mutationOptions({
+ onSuccess: () =>
+ queryClient.invalidateQueries({
+ queryKey: trpc.conversations.builderList.pathKey(),
+ }),
+ }),
+ );
+
+ if (sharedChat && shared.isPending) {
+ return <ChatLoading />;
+ }
+
+ if (sharedChat) {
+ if (shared.data) return <SharedAgentChat conversation={shared.data} />;
+
+ return <ChatUnavailable shared />;
+ }
+
+ if (conversation.isPending) return <ChatLoading />;
+
+ if (conversation.isError) {
+ return <ChatUnavailable />;
+ }
+
+ const data = conversation.data;
+ const submissions = data.submissions as BuilderSubmission[];
+ const persistedEvents = (events.data ??
+ []) as unknown as MessageStreamEvent[];
+ const streamKey =
+ data.sessionId && builderConversationIsWorking(data)
+ ? `${data.sessionId}:${submissions.at(-1)?.id ?? "initial"}`
+ : null;
+ const transcriptEvents =
+ streamKey && liveStream?.key === streamKey
+ ? liveStream.events
+ : persistedEvents;
+ const agentMessages = messagesFromEvents(transcriptEvents);
+ const timeline = conversationTimeline(
+ submissions,
+ transcriptEvents,
+ agentMessages,
+ );
+ const answeredQuestionIds = questionResponseIds(submissions);
+ const waitingQuestion = pendingQuestion(agentMessages);
+ const question =
+ waitingQuestion &&
+ !hasQueuedQuestionResponse(submissions, waitingQuestion.requestId)
+ ? waitingQuestion
+ : null;
+ const failure = latestTurnFailure(transcriptEvents);
+ const creatingAgent = hasCreateAgentCommand(submissions);
+ const working = builderConversationIsWorking(data) && !failure;
+ const reviewVersion = reviewVersionId(data);
+ const artifactVersion = displayedArtifactVersionId(data, working);
+ const retryPrompt = retryPromptOf(submissions.at(-1));
+ const send = async (
+ prompt: BuilderPrompt,
+ clientRequestId = crypto.randomUUID(),
+ ) => {
+ await submit.mutateAsync({
+ id: conversationId,
+ clientRequestId,
+ ...prompt,
+ });
+ };
+
+ return (
+ <main
+ className="flex min-h-0 flex-1 flex-col"
+ onPointerEnter={() => {
+ if (
+ data.lastAssistantAt &&
+ (!data.lastReadAt ||
+ new Date(data.lastAssistantAt) > new Date(data.lastReadAt)) &&
+ !markRead.isPending
+ ) {
+ markRead.mutate({ id: conversationId });
+ }
+ }}
+ >
+ {streamKey && data.sessionId ? (
+ <BuilderEventFollower
+ key={streamKey}
+ conversationId={conversationId}
+ sessionId={data.sessionId}
+ onSnapshot={(snapshot) =>
+ setLiveStream({ key: streamKey, events: snapshot })
+ }
+ onEvent={(event) =>
+ setLiveStream((current) => ({
+ key: streamKey,
+ events:
+ current?.key === streamKey
+ ? appendEvent(current.events, event)
+ : [event],
+ }))
+ }
+ />
+ ) : null}
+ <ChatHeader
+ conversation={data}
+ working={working}
+ creatingAgent={creatingAgent}
+ />
+
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 sm:gap-5 sm:px-5 sm:py-9">
+ {timeline.map((item) =>
+ item.kind === "submission" ? (
+ <UserSubmission
+ key={item.id}
+ submission={item.submission}
+ failed={item.submission.status === "FAILED"}
+ error={item.submission.errorMessage}
+ />
+ ) : (
+ <AssistantMessage
+ key={item.id}
+ conversation={data}
+ message={item.message}
+ answeredQuestionIds={answeredQuestionIds}
+ />
+ ),
+ )}
+
+ {working && creatingAgent ? (
+ <BuildingAgentCard
+ conversationId={conversationId}
+ sessionId={data.sessionId}
+ artifacts={data.builderArtifacts}
+ startedAt={submissions.at(-1)?.createdAt ?? null}
+ />
+ ) : null}
+
+ {creatingAgent && data.builderArtifacts.length > 0 ? (
+ <AgentCodeWorkspace
+ artifacts={data.builderArtifacts}
+ working={working}
+ versionId={artifactVersion}
+ />
+ ) : null}
+
+ {!working &&
+ failure &&
+ creatingAgent &&
+ !reviewVersion &&
+ data.agent?.status !== "LIVE" ? (
+ <BuilderFailureCard
+ failure={failure}
+ creatingAgent
+ retrying={submit.isPending}
+ onRetry={retryPrompt ? () => send(retryPrompt) : null}
+ />
+ ) : null}
+
+ {!working && failure && !creatingAgent ? (
+ <BuilderFailureCard
+ failure={failure}
+ creatingAgent={false}
+ retrying={submit.isPending}
+ onRetry={retryPrompt ? () => send(retryPrompt) : null}
+ />
+ ) : null}
+
+ {creatingAgent && !working && reviewVersion ? (
+ <ReviewAgentCard conversation={data} versionId={reviewVersion} />
+ ) : null}
+
+ {creatingAgent && data.agent?.status === "LIVE" && !reviewVersion ? (
+ <DeployedAgentCard
+ conversation={data}
+ onFollowUp={(message) =>
+ send({
+ commandType: "CHAT",
+ message,
+ resources: [],
+ attachments: [],
+ })
+ }
+ />
+ ) : null}
+ </div>
+ </div>
+
+ <div className="min-h-0 shrink overflow-y-auto overscroll-contain border-t px-4 py-3 sm:px-5">
+ <div className="mx-auto w-full max-w-3xl">
+ {question ? (
+ <AgentClarificationComposer
+ key={question.requestId}
+ question={question}
+ pending={answerQuestion.isPending}
+ onSubmit={async (response: ClarificationResponse) => {
+ await answerQuestion.mutateAsync({
+ id: conversationId,
+ clientRequestId: crypto.randomUUID(),
+ ...response,
+ });
+ }}
+ />
+ ) : (
+ <AgentComposer mode="chat" disabled={working} onSubmit={send} />
+ )}
+ </div>
+ </div>
+ </main>
+ );
+}
+
+function BuilderEventFollower({
+ conversationId,
+ sessionId,
+ onSnapshot,
+ onEvent,
+}: {
+ conversationId: string;
+ sessionId: string;
+ onSnapshot: (events: readonly MessageStreamEvent[]) => void;
+ onEvent: (event: MessageStreamEvent) => void;
+}) {
+ useMountEffect(() => {
+ const controller = new AbortController();
+ const session = new Client({
+ headers: { "x-crm-builder-conversation": conversationId },
+ host: "",
+ }).session({ sessionId, streamIndex: 0 });
+
+ const follow = async () => {
+ const snapshot = await session.snapshot({ signal: controller.signal });
+ if (controller.signal.aborted) return;
+ onSnapshot(snapshot.events);
+
+ for await (const event of session.stream({
+ startIndex: snapshot.session.streamIndex,
+ signal: controller.signal,
+ })) {
+ if (controller.signal.aborted) return;
+ onEvent(event);
+ }
+ };
+
+ void follow().catch((error: unknown) => {
+ if (!controller.signal.aborted) {
+ console.error(error);
+ }
+ });
+
+ return () => controller.abort();
+ });
+
+ return null;
+}
+
+function appendEvent(
+ events: readonly MessageStreamEvent[],
+ event: MessageStreamEvent,
+): readonly MessageStreamEvent[] {
+ return events.some((candidate) => candidate.meta.id === event.meta.id)
+ ? events
+ : [...events, event];
+}
+
+function SharedAgentChat({
+ conversation,
+}: {
+ conversation: SharedConversation;
+}) {
+ const submissions =
+ conversation.submissions as unknown as BuilderSubmission[];
+ const events = conversation.events as unknown as MessageStreamEvent[];
+ const messages = messagesFromEvents(events);
+ const timeline = conversationTimeline(submissions, events, messages);
+ const answeredQuestionIds = questionResponseIds(submissions);
+ const working = events.length > 0 && !eventStreamSettled(events);
+ const artifactVersion = working
+ ? null
+ : latestCompletedArtifactVersionId(conversation.builderArtifacts);
+
+ return (
+ <main className="flex min-h-0 flex-1 flex-col">
+ <header className="flex h-12 shrink-0 items-center gap-3 border-b px-5">
+ <h1 className="min-w-0 flex-1 truncate font-medium text-sm">
+ {conversation.agent?.name ?? conversation.title ?? "Agent builder"}
+ </h1>
+ <span className="text-muted-foreground text-xs">Read-only</span>
+ </header>
+
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 sm:gap-5 sm:px-5 sm:py-9">
+ <div className="rounded-lg border bg-card px-4 py-3 text-sm">
+ <p className="font-medium">Shared by {conversation.ownerName}</p>
+ <p className="mt-1 text-muted-foreground text-xs">
+ You can read this builder chat, but only its owner can continue or
+ change it.
+ </p>
+ </div>
+
+ {timeline.map((item) =>
+ item.kind === "submission" ? (
+ <UserSubmission
+ key={item.id}
+ submission={item.submission}
+ failed={item.submission.status === "FAILED"}
+ error={item.submission.errorMessage}
+ />
+ ) : (
+ <AssistantMessage
+ key={item.id}
+ conversation={null}
+ message={item.message}
+ answeredQuestionIds={answeredQuestionIds}
+ />
+ ),
+ )}
+
+ {conversation.builderArtifacts.length > 0 ? (
+ <AgentCodeWorkspace
+ artifacts={conversation.builderArtifacts}
+ working={working}
+ versionId={artifactVersion}
+ />
+ ) : null}
+ </div>
+ </div>
+ </main>
+ );
+}
+
+function ChatHeader({
+ conversation,
+ working,
+ creatingAgent,
+}: {
+ conversation: Conversation;
+ working: boolean;
+ creatingAgent: boolean;
+}) {
+ const workspaceUrl = useWorkspaceUrl();
+ const title =
+ (creatingAgent ? conversation.agent?.name : null) ??
+ conversation.title ??
+ "Agent chat";
+
+ return (
+ <header className="flex h-12 shrink-0 items-center gap-2 border-b px-4 sm:gap-2.5 sm:pr-4 sm:pl-5">
+ <div className="flex min-w-0 flex-1 items-center gap-2 sm:gap-3">
+ <h1 className="truncate font-medium text-sm">{title}</h1>
+ <span className="hidden shrink-0 text-muted-foreground text-xs sm:inline">
+ Private
+ </span>
+ {working ? (
+ <span className="flex shrink-0 items-center gap-2 text-muted-foreground text-xs">
+ <Icon
+ icon={Renew}
+ className="size-3.5 animate-spin text-ring"
+ motion="none"
+ />
+ <span className="sr-only">Working in background</span>
+ <span aria-hidden="true" className="hidden sm:inline">
+ Working in background
+ </span>
+ </span>
+ ) : null}
+ </div>
+ <Button asChild variant="ghost" size="icon-sm">
+ <Link href={workspaceUrl("/chat")} aria-label="Start a new chat">
+ <Icon icon={Add} />
+ </Link>
+ </Button>
+ <ShareChatDialog conversationId={conversation.id} title={title} />
+ <DeleteChatAction
+ conversationId={conversation.id}
+ title={title}
+ trigger="menu"
+ returnToChatList
+ />
+ </header>
+ );
+}
+
+function UserSubmission({
+ submission,
+ failed,
+ error,
+}: {
+ submission: BuilderSubmission;
+ failed: boolean;
+ error: string | null;
+}) {
+ const message = builderMessageOf(submission.message);
+ const command =
+ submission.commandType === "CREATE_AGENT"
+ ? consumeBuilderCommand(message.text)
+ : null;
+ const text = command?.body ?? message.text;
+ const response = inputResponseOf(submission.message);
+
+ return (
+ <div className="flex min-w-0 w-full justify-end">
+ <div
+ className={cn(
+ "flex w-fit min-w-0 max-w-full flex-col gap-2 rounded-md bg-muted px-3 py-2.5 text-sm leading-5 sm:max-w-[620px] sm:px-3.5 sm:py-3",
+ response &&
+ "max-w-sm gap-1.5 border-ring border-r-2 bg-muted/70 py-2 sm:max-w-sm sm:py-2.5",
+ )}
+ >
+ {response ? (
+ <div className="flex items-center gap-1.5 text-muted-foreground text-xs">
+ <Icon icon={Reply} className="size-3.5" />
+ <span>Answer to follow-up</span>
+ </div>
+ ) : null}
+ {submission.commandType === "CREATE_AGENT" ? (
+ <div className="flex flex-wrap gap-1">
+ <ChatCommandChip label="Create agent" icon={Application} />
+ </div>
+ ) : null}
+ <p className="wrap-break-word">{text}</p>
+ {message.resources.length > 0 || message.attachments.length > 0 ? (
+ <div className="flex flex-wrap gap-1 pt-1">
+ {message.resources.map((resource) => (
+ <ChatReferenceChip
+ key={`${resource.kind}:${resource.id}`}
+ resource={resource}
+ icon={RESOURCE_ICONS[resource.kind]}
+ />
+ ))}
+ {message.attachments.map((attachment) => (
+ <ChatAttachmentChip
+ key={`${attachment.name}:${attachment.size}`}
+ attachment={attachment}
+ />
+ ))}
+ </div>
+ ) : null}
+ {failed ? (
+ <p className="mt-2 text-destructive text-xs">
+ {error ?? "This message could not be sent."}
+ </p>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+function AssistantMessage({
+ conversation,
+ message,
+ answeredQuestionIds,
+}: {
+ conversation: Conversation | null;
+ message: EveMessage;
+ answeredQuestionIds: ReadonlySet<string>;
+}) {
+ const [transcript] = toTranscript([message]);
+ if (!transcript || transcript.mine) return null;
+
+ const textParts: string[] = [];
+ for (const item of transcript.items) {
+ if (item.kind === "said") textParts.push(item.text);
+ }
+ const markdown = textParts.join("\n\n");
+ const activity = transcript.items.filter(
+ (item) => item.kind === "reasoned" || item.kind === "did",
+ );
+ const reasoningCount = activity.filter(
+ (item) => item.kind === "reasoned",
+ ).length;
+ const toolCount = activity.filter((item) => item.kind === "did").length;
+ const dealResults = mergeDealListResultPages(
+ activity.flatMap((item) => {
+ if (item.kind !== "did" || item.tool !== "list_deals") return [];
+ const result = dealListResultOf(item.output);
+ return result ? [result] : [];
+ }),
+ );
+ const dealMarkdown =
+ dealResults.length > 0 ? splitMarkdownTable(markdown) : null;
+ const streaming =
+ message.metadata?.status === "streaming" ||
+ activity.some(
+ (item) =>
+ (item.kind === "reasoned" && item.streaming) ||
+ (item.kind === "did" && item.pending),
+ );
+ const reasoningLabel =
+ reasoningCount > 0 && toolCount > 0
+ ? "Reasoning and activity"
+ : reasoningCount > 0
+ ? "Reasoning"
+ : "Activity";
+
+ return (
+ <div className="flex w-full min-w-0 max-w-[640px] flex-col gap-2">
+ {activity.length > 0 ? (
+ <Reasoning isStreaming={streaming} label={reasoningLabel}>
+ <div className="flex flex-col gap-3">
+ {activity.map((item) => {
+ if (item.kind === "reasoned") {
+ return (
+ <Markdown key={item.id} className="wrap-break-word leading-5">
+ {item.text}
+ </Markdown>
+ );
+ }
+
+ return (
+ <div key={item.id} className="flex min-w-0 items-start gap-2">
+ {item.pending ? (
+ <Icon
+ icon={Renew}
+ className="size-3.5 animate-spin"
+ motion="none"
+ />
+ ) : item.tone === "warning" ? (
+ <Icon icon={WarningAlt} className="size-3.5 text-warning" />
+ ) : (
+ <Icon icon={Checkmark} className="size-3.5 text-ring" />
+ )}
+ <span className="min-w-0 wrap-break-word">{item.label}</span>
+ </div>
+ );
+ })}
+ </div>
+ </Reasoning>
+ ) : null}
+ {dealMarkdown ? (
+ <>
+ {dealMarkdown.before ? (
+ <Markdown className="wrap-break-word text-sm leading-5">
+ {dealMarkdown.before}
+ </Markdown>
+ ) : null}
+ {dealResults.map((result) => (
+ <DealListResultTable
+ key={JSON.stringify(result.criteria)}
+ result={result}
+ />
+ ))}
+ {dealMarkdown.after ? (
+ <Markdown className="wrap-break-word text-sm leading-5">
+ {dealMarkdown.after}
+ </Markdown>
+ ) : null}
+ {transcript.items.map((item) =>
+ item.kind === "asked" &&
+ (conversation === null ||
+ answeredQuestionIds.has(item.question.requestId)) ? (
+ <FollowUpTranscriptItem
+ key={item.id}
+ question={item.question}
+ answered={answeredQuestionIds.has(item.question.requestId)}
+ />
+ ) : null,
+ )}
+ </>
+ ) : (
+ transcript.items.map((item) => {
+ if (item.kind === "said") {
+ const text = item.text;
+ if (!text) return null;
+
+ return (
+ <Markdown
+ key={item.id}
+ className="wrap-break-word text-sm leading-5"
+ >
+ {text}
+ </Markdown>
+ );
+ }
+
+ if (item.kind === "asked") {
+ return conversation === null ||
+ answeredQuestionIds.has(item.question.requestId) ? (
+ <FollowUpTranscriptItem
+ key={item.id}
+ question={item.question}
+ answered={answeredQuestionIds.has(item.question.requestId)}
+ />
+ ) : null;
+ }
+
+ return null;
+ })
+ )}
+ {markdown ? (
+ conversation ? (
+ <ResponseActions
+ conversation={conversation}
+ messageId={transcript.id}
+ markdown={markdown}
+ />
+ ) : (
+ <CopyResponseAction markdown={markdown} />
+ )
+ ) : null}
+ </div>
+ );
+}
+
+function FollowUpTranscriptItem({
+ question,
+ answered,
+}: {
+ question: EveMessageInputRequest;
+ answered: boolean;
+}) {
+ return (
+ <div className="w-full max-w-sm border-ring/50 border-l-2 bg-muted/40 px-3 py-2.5">
+ <div className="flex items-center justify-between gap-3 text-xs">
+ <span className="font-medium">Follow-up</span>
+ <span className="text-muted-foreground">
+ {answered ? "Answered" : "Waiting for your answer"}
+ </span>
+ </div>
+ <Markdown className="mt-1.5 wrap-break-word text-sm leading-5">
+ {question.prompt}
+ </Markdown>
+ </div>
+ );
+}
+
+function CopyResponseAction({ markdown }: { markdown: string }) {
+ return (
+ <div className="flex h-7 items-center">
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Copy response as Markdown"
+ onClick={() => {
+ void navigator.clipboard.writeText(markdown);
+ toast.success("Response copied as Markdown.");
+ }}
+ >
+ <Icon icon={Copy} />
+ </Button>
+ </div>
+ );
+}
+
+function ResponseActions({
+ conversation,
+ messageId,
+ markdown,
+}: {
+ conversation: Conversation;
+ messageId: string;
+ markdown: string;
+}) {
+ const trpc = useTRPC();
+ const initial = conversation.feedback.find(
+ (item) => item.messageId === messageId,
+ )?.rating;
+ const [rating, setRating] = useState<"UP" | "DOWN" | null>(initial ?? null);
+ const rate = useMutation(
+ trpc.conversations.rateBuilderResponse.mutationOptions({
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const choose = (next: "UP" | "DOWN") => {
+ const value = rating === next ? null : next;
+ setRating(value);
+ rate.mutate({ id: conversation.id, messageId, rating: value });
+ };
+
+ return (
+ <div className="flex h-7 items-center gap-0.5">
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Copy response as Markdown"
+ onClick={() => {
+ void navigator.clipboard.writeText(markdown);
+ toast.success("Response copied as Markdown.");
+ }}
+ >
+ <Icon icon={Copy} />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Rate response helpful"
+ aria-pressed={rating === "UP"}
+ className={cn(rating === "UP" && "bg-muted text-foreground")}
+ onClick={() => choose("UP")}
+ >
+ <Icon icon={ThumbsUp} />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ aria-label="Rate response not helpful"
+ aria-pressed={rating === "DOWN"}
+ className={cn(rating === "DOWN" && "bg-muted text-foreground")}
+ onClick={() => choose("DOWN")}
+ >
+ <Icon icon={ThumbsDown} />
+ </Button>
+ </div>
+ );
+}
+
+function BuildingAgentCard({
+ conversationId,
+ sessionId,
+ artifacts,
+ startedAt,
+}: {
+ conversationId: string;
+ sessionId: string | null;
+ artifacts: Conversation["builderArtifacts"];
+ startedAt: string | null;
+}) {
+ const completed = completedBuilderSteps(artifacts, startedAt, sessionId);
+ const stop = useAsyncAction({
+ action: async () => {
+ if (!sessionId) return;
+ const response = await fetch(`/eve/v1/session/${sessionId}/cancel`, {
+ method: "POST",
+ headers: { "x-crm-builder-conversation": conversationId },
+ });
+ if (!response.ok) throw new Error(await response.text());
+ },
+ onSuccess: () => toast.success("Stop requested."),
+ onError: () => toast.error("The agent could not be stopped. Try again."),
+ });
+
+ return (
+ <div className="w-full max-w-sm">
+ <div className="overflow-hidden rounded-lg bg-muted/40">
+ <div className="flex items-center gap-3 px-4 pt-4 pb-2">
+ <Icon
+ icon={Renew}
+ className="size-3.5 animate-spin text-ring"
+ motion="none"
+ />
+ <span className="min-w-0 flex-1 font-medium text-sm">
+ Building the agent
+ </span>
+ <span className="font-mono text-muted-foreground text-xs">
+ {completed} of 4
+ </span>
+ </div>
+ <ol
+ className="flex flex-col gap-1 px-3 py-3"
+ aria-label="Agent creation"
+ >
+ {BUILDER_STEPS.map((label, index) => {
+ const done = index < completed;
+ const active =
+ index === completed && completed < BUILDER_STEPS.length;
+
+ return (
+ <li
+ key={label}
+ className={cn(
+ "flex min-h-9 min-w-0 items-center gap-3 rounded-md px-2.5 py-2",
+ active && "bg-background",
+ )}
+ aria-current={active ? "step" : undefined}
+ >
+ <span
+ className={cn(
+ "flex size-5 shrink-0 items-center justify-center text-[11px]",
+ (done || active) && "text-ring",
+ !done && !active && "text-muted-foreground",
+ )}
+ >
+ {done ? (
+ <Icon icon={Checkmark} className="size-3.5" />
+ ) : active ? (
+ <Icon
+ icon={Renew}
+ className="size-3.5 animate-spin"
+ motion="none"
+ />
+ ) : (
+ index + 1
+ )}
+ </span>
+ <span
+ className={cn(
+ "min-w-0 flex-1 wrap-break-word text-xs",
+ !done && !active && "text-muted-foreground",
+ )}
+ >
+ {label}
+ </span>
+ <span className="shrink-0 text-muted-foreground text-[11px]">
+ {done ? "Done" : active ? "Working" : "Queued"}
+ </span>
+ </li>
+ );
+ })}
+ </ol>
+ <footer className="flex min-h-12 items-center gap-3 bg-background/55 px-4 py-2.5">
+ <p className="min-w-0 flex-1 text-pretty text-muted-foreground text-xs">
+ Runs in the background
+ </p>
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={!sessionId || stop.pending}
+ aria-busy={stop.pending}
+ onClick={() => stop.run()}
+ >
+ <AsyncButtonContent
+ status={stop.status}
+ pendingLabel="Stopping"
+ successLabel="Stopping"
+ errorLabel="Try again"
+ >
+ Stop
+ </AsyncButtonContent>
+ </Button>
+ </footer>
+ </div>
+ </div>
+ );
+}
+
+function BuilderFailureCard({
+ failure,
+ creatingAgent,
+ retrying,
+ onRetry,
+}: {
+ failure: AgentTurnFailure;
+ creatingAgent: boolean;
+ retrying: boolean;
+ onRetry: (() => void) | null;
+}) {
+ const message =
+ failure.kind === "rate-limit"
+ ? "Vercel AI Gateway rate-limited this model before it could start. Try again in a moment or add AI Gateway credits in Vercel."
+ : failure.kind === "restricted"
+ ? "This model requires paid AI Gateway credits. Add credits in Vercel, then try again."
+ : failure.kind === "credits"
+ ? "Vercel AI Gateway has no available credits. Add credits in Vercel, then try again."
+ : "The builder could not finish this request. Try again.";
+
+ return (
+ <div
+ role="alert"
+ className="flex flex-col items-stretch gap-3 rounded-lg border border-destructive/30 bg-card px-4 py-3 sm:flex-row sm:items-start"
+ >
+ <div className="flex min-w-0 flex-1 items-start gap-3">
+ <Icon icon={WarningAlt} className="mt-0.5 size-4 text-destructive" />
+ <div className="min-w-0 flex-1">
+ <p className="font-medium text-sm">
+ {creatingAgent ? "Agent creation stopped" : "Response stopped"}
+ </p>
+ <p className="mt-0.5 text-pretty text-muted-foreground text-xs leading-5">
+ {message}
+ </p>
+ </div>
+ </div>
+ {onRetry ? (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={retrying}
+ aria-busy={retrying}
+ onClick={onRetry}
+ >
+ <AsyncButtonContent
+ status={retrying ? "pending" : "idle"}
+ pendingLabel="Retrying"
+ >
+ Try again
+ </AsyncButtonContent>
+ </Button>
+ ) : null}
+ </div>
+ );
+}
+
+function ReviewAgentCard({
+ conversation,
+ versionId,
+}: {
+ conversation: Conversation;
+ versionId: string;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const version = conversation.createdVersions.find(
+ (candidate) => candidate.id === versionId,
+ ) as DraftVersion | undefined;
+ const agent = conversation.agent;
+ const manifest = manifestOf(version?.manifest);
+ const deploy = useMutation(
+ trpc.agents.deploy.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.conversations.builderById.pathKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.conversations.builderList.pathKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.agents.list.pathKey(),
+ }),
+ ]);
+ toast.success("Agent deployed to the team.");
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ if (!version || !agent) return null;
+
+ return (
+ <div className="flex flex-col gap-5">
+ <p className="max-w-[640px] text-pretty text-sm leading-5">
+ I’ve drafted the agent. Its files and configuration stay private to you
+ until you deploy it.
+ </p>
+ <div className="overflow-hidden rounded-lg border bg-card">
+ <div className="border-b px-4 py-3 sm:px-5 sm:py-4">
+ <h2 className="wrap-break-word font-medium text-sm">
+ {manifest.name ?? agent.name}
+ </h2>
+ <p className="mt-0.5 wrap-break-word text-pretty text-muted-foreground text-xs">
+ {manifest.description ??
+ agent.description ??
+ "A durable agent for your team."}
+ </p>
+ </div>
+ <ReviewRow label="Trigger" value={manifest.trigger} />
+ <ReviewRow label="Looks at" value={manifest.looksAt} />
+ <ReviewRow label="Action" value={manifest.action} />
+ <ReviewRow label="Access" value={manifest.access} />
+ <p className="border-t px-4 py-2 text-pretty text-muted-foreground text-xs sm:px-5">
+ The sandbox has no network access. CRM and connected data are
+ available only through the listed tools, and credentials stay in the
+ app runtime.
+ </p>
+ <div className="flex min-h-14 flex-col items-stretch gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:px-5">
+ <p className="text-pretty text-muted-foreground text-xs">
+ Deploying approves this version, scope, and its listed actions for
+ the whole team.
+ </p>
+ <div className="flex flex-wrap justify-end gap-1 sm:shrink-0">
+ <Button
+ variant="ghost"
+ onClick={() =>
+ document
+ .querySelector<HTMLTextAreaElement>(
+ 'textarea[aria-label="Message the agent builder"]',
+ )
+ ?.focus()
+ }
+ >
+ Change details
+ </Button>
+ <Button
+ disabled={deploy.isPending}
+ aria-busy={deploy.isPending}
+ onClick={() =>
+ deploy.mutate({
+ id: agent.id,
+ versionId: version.id,
+ clientRequestId: crypto.randomUUID(),
+ })
+ }
+ >
+ <AsyncButtonContent
+ status={
+ deploy.isPending
+ ? "pending"
+ : deploy.isError
+ ? "error"
+ : deploy.isSuccess
+ ? "success"
+ : "idle"
+ }
+ pendingLabel="Deploying"
+ successLabel="Deployed"
+ errorLabel="Try again"
+ >
+ Deploy agent
+ </AsyncButtonContent>
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function ReviewRow({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="flex min-h-8 flex-col items-start gap-0.5 border-b px-4 py-2 last:border-b-0 sm:flex-row sm:items-center sm:gap-4 sm:px-5 sm:py-1.5">
+ <span className="text-muted-foreground text-xs sm:w-[104px] sm:shrink-0">
+ {label}
+ </span>
+ <span className="min-w-0 flex-1 wrap-break-word font-medium text-sm">
+ {value}
+ </span>
+ </div>
+ );
+}
+
+function DeployedAgentCard({
+ conversation,
+ onFollowUp,
+}: {
+ conversation: Conversation;
+ onFollowUp: (message: string) => Promise<void>;
+}) {
+ const trpc = useTRPC();
+ const workspaceUrl = useWorkspaceUrl();
+ const queryClient = useQueryClient();
+ const agent = conversation.agent;
+ const run = useMutation(
+ trpc.agents.runNow.mutationOptions({
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: trpc.agents.history.pathKey(),
+ });
+ toast.success("Agent run queued.");
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+ const runAction = useAsyncAction({
+ action: () =>
+ run.mutateAsync({
+ id: agent?.id ?? "",
+ clientRequestId: crypto.randomUUID(),
+ }),
+ });
+
+ if (!agent) return null;
+ const nextRun = agent.triggers.find((trigger) => trigger.enabled)?.nextRunAt;
+
+ return (
+ <div className="flex flex-col gap-[18px]">
+ <div className="space-y-1">
+ <p className="text-sm leading-5">{agent.name} is live.</p>
+ <p className="text-muted-foreground text-sm leading-5">
+ I created the Eve agent, applied its bounded CRM and integration
+ access, and scheduled its first run.
+ </p>
+ </div>
+ <div className="overflow-hidden rounded-lg border bg-card">
+ <div className="flex flex-col items-start gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:gap-4 sm:px-5 sm:py-4">
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
+ <Icon icon={CheckmarkFilled} className="size-3.5 text-ring" />
+ <h2 className="min-w-0 wrap-break-word font-medium text-sm">
+ {agent.name}
+ </h2>
+ <span className="text-muted-foreground text-xs">Live</span>
+ </div>
+ <p className="wrap-break-word text-muted-foreground text-xs">
+ Team agent · created by {agent.createdBy.name}
+ </p>
+ </div>
+ <Button asChild variant="outline" size="sm">
+ <Link href={workspaceUrl(`/agents/${agent.id}`)}>Open agent</Link>
+ </Button>
+ </div>
+ <div className="grid border-b sm:grid-cols-3">
+ <DeployedStat
+ label="Next run"
+ value={
+ nextRun ? (
+ <LocalDateTime
+ date={nextRun}
+ options={{
+ weekday: "short",
+ hour: "numeric",
+ minute: "2-digit",
+ timeZoneName: "short",
+ }}
+ />
+ ) : (
+ "Manual only"
+ )
+ }
+ />
+ <DeployedStat
+ label="Execution"
+ value="Eve runtime · isolated sandbox"
+ />
+ <DeployedStat
+ label="Available to"
+ value="Everyone on the team"
+ last
+ />
+ </div>
+ <div className="flex min-h-12 flex-col items-start gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:px-5 sm:py-2">
+ <p className="text-pretty text-muted-foreground text-xs">
+ The chat remains private. The agent is now team-owned.
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={runAction.pending}
+ aria-busy={runAction.pending}
+ onClick={() => runAction.run()}
+ >
+ <AsyncButtonContent
+ status={runAction.status}
+ pendingLabel="Queueing"
+ successLabel="Queued"
+ errorLabel="Try again"
+ >
+ <Icon icon={Play} data-icon="inline-start" />
+ Run now
+ </AsyncButtonContent>
+ </Button>
+ </div>
+ </div>
+
+ <div>
+ <p className="flex h-7 items-center text-muted-foreground text-sm">
+ Suggested follow-ups
+ </p>
+ {["Run it once now", "Add another teammate to the notification"].map(
+ (suggestion) => (
+ <button
+ key={suggestion}
+ type="button"
+ onClick={() => void onFollowUp(suggestion)}
+ className="flex w-full items-center gap-3 border-t py-2.5 text-left outline-none hover:bg-muted/50 focus-visible:bg-muted/50"
+ >
+ <span className="min-w-0 flex-1 wrap-break-word text-sm">
+ {suggestion}
+ </span>
+ <Icon
+ icon={ArrowRight}
+ className="size-4 text-muted-foreground"
+ />
+ </button>
+ ),
+ )}
+ </div>
+ </div>
+ );
+}
+
+function DeployedStat({
+ label,
+ value,
+ last = false,
+}: {
+ label: string;
+ value: ReactNode;
+ last?: boolean;
+}) {
+ return (
+ <div
+ className={cn(
+ "flex min-w-0 flex-col justify-center gap-1 px-4 py-3 sm:px-5",
+ !last && "border-b sm:border-r sm:border-b-0",
+ )}
+ >
+ <span className="text-muted-foreground text-xs">{label}</span>
+ <span className="min-w-0 wrap-break-word font-medium text-sm sm:truncate">
+ {value}
+ </span>
+ </div>
+ );
+}
+
+function ChatLoading() {
+ return (
+ <main className="flex min-h-0 flex-1 flex-col" aria-busy="true">
+ <header className="flex h-12 shrink-0 items-center border-b px-5">
+ <Skeleton className="h-4 w-40" />
+ </header>
+ <div className="min-h-0 flex-1 overflow-hidden">
+ <div className="mx-auto flex w-full max-w-3xl flex-col gap-5 px-4 py-6 sm:px-5 sm:py-9">
+ <Skeleton className="ml-auto h-16 w-2/3 max-w-[520px]" />
+ <div className="flex max-w-[640px] flex-col gap-2">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-11/12" />
+ <Skeleton className="h-4 w-8/12" />
+ </div>
+ </div>
+ </div>
+ <span role="status" className="sr-only">
+ Loading chat
+ </span>
+ </main>
+ );
+}
+
+function ChatUnavailable({ shared = false }: { shared?: boolean }) {
+ const workspaceUrl = useWorkspaceUrl();
+
+ return (
+ <main className="flex flex-1 items-center justify-center p-8">
+ <div className="max-w-md text-center">
+ <h1 className="font-medium text-lg">Chat unavailable</h1>
+ <p className="mt-2 text-muted-foreground text-sm">
+ {shared
+ ? "This shared chat no longer exists or is not available."
+ : "This chat does not exist or you do not have access to it."}
+ </p>
+ <Button asChild variant="outline" className="mt-5">
+ <Link href={workspaceUrl("/chat")}>Start a new chat</Link>
+ </Button>
+ </div>
+ </main>
+ );
+}
+
+const RESOURCE_ICONS = {
+ integration: Application,
+ company: Building,
+ contact: User,
+ deal: Partnership,
+} as const;
+
+function builderMessageOf(message: unknown) {
+ const row = recordOf(message);
+ return {
+ text: typeof row.text === "string" ? row.text : "Message unavailable",
+ resources: Array.isArray(row.resources)
+ ? (row.resources as BuilderPrompt["resources"])
+ : [],
+ attachments: Array.isArray(row.attachments)
+ ? (row.attachments as BuilderPrompt["attachments"])
+ : [],
+ };
+}
+
+function hasQueuedQuestionResponse(
+ submissions: BuilderSubmission[],
+ requestId: string,
+): boolean {
+ return submissions.some((submission) => {
+ if (submission.status === "FAILED" || submission.status === "CANCELLED") {
+ return false;
+ }
+
+ return inputResponseOf(submission.message)?.requestId === requestId;
+ });
+}
+
+function questionResponseIds(
+ submissions: readonly BuilderSubmission[],
+): ReadonlySet<string> {
+ return new Set(
+ submissions.flatMap((submission) => {
+ if (submission.status === "FAILED" || submission.status === "CANCELLED") {
+ return [];
+ }
+
+ const response = inputResponseOf(submission.message);
+ return response ? [response.requestId] : [];
+ }),
+ );
+}
+
+function inputResponseOf(message: unknown): { requestId: string } | null {
+ const response = recordOf(recordOf(message).inputResponse);
+ return typeof response.requestId === "string" && response.requestId
+ ? { requestId: response.requestId }
+ : null;
+}
+
+function retryPromptOf(
+ submission: BuilderSubmission | undefined,
+): BuilderPrompt | null {
+ if (!submission) return null;
+ const row = recordOf(submission.message);
+ if (Object.keys(recordOf(row.inputResponse)).length > 0) return null;
+ if (typeof row.text !== "string" || !row.text.trim()) return null;
+
+ return {
+ commandType: submission.commandType,
+ message: row.text,
+ resources: Array.isArray(row.resources)
+ ? (row.resources as BuilderPrompt["resources"])
+ : [],
+ attachments: Array.isArray(row.attachments)
+ ? (row.attachments as BuilderPrompt["attachments"])
+ : [],
+ };
+}
+
+function builderConversationNeedsPolling(conversation: Conversation): boolean {
+ return builderConversationIsWorking(conversation);
+}
+
+function sharedConversationNeedsPolling(
+ conversation: SharedConversation | undefined,
+): boolean {
+ if (!conversation?.events.length) return false;
+
+ return !eventStreamSettled(conversation.events);
+}
+
+function manifestOf(value: unknown) {
+ const manifest = recordOf(value);
+ const trigger = recordOf(manifest.trigger);
+ const dataScope = recordOf(manifest.dataScope);
+ const actions = Array.isArray(manifest.actions)
+ ? manifest.actions.map(recordOf)
+ : [];
+ const access = Array.isArray(manifest.access)
+ ? manifest.access.filter((item): item is string => typeof item === "string")
+ : [];
+
+ return {
+ name:
+ typeof manifest.name === "string" && manifest.name.trim()
+ ? manifest.name.trim()
+ : null,
+ description:
+ typeof manifest.description === "string" && manifest.description.trim()
+ ? manifest.description.trim()
+ : null,
+ trigger: textOf(trigger.summary, "Manual or configured schedule"),
+ looksAt: textOf(dataScope.summary, "CRM records in the approved scope"),
+ action: textOf(actions[0]?.summary, "Perform the requested team action"),
+ access: access.length > 0 ? access.join(" · ") : "Bounded CRM read access",
+ };
+}
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
+
+function textOf(value: unknown, fallback: string): string {
+ return typeof value === "string" && value.trim() ? value : fallback;
+}
diff --git a/apps/app/components/agent-builder/agent-builder-home.tsx b/apps/app/components/agent-builder/agent-builder-home.tsx
new file mode 100644
index 00000000..0f4ac4c1
--- /dev/null
+++ b/apps/app/components/agent-builder/agent-builder-home.tsx
@@ -0,0 +1,99 @@
+"use client";
+
+import ArrowRight from "@carbon/icons-react/es/ArrowRight";
+import { Icon } from "@crm/ui/components/icon";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import { useTRPC } from "@/lib/trpc/client";
+import { useWorkspaceUrl } from "@/lib/use-workspace-url";
+import { AgentComposer, type BuilderComposerPrompt } from "./agent-composer";
+
+const SUGGESTIONS = [
+ "Brief every deal owner before a renewal call",
+ "Flag deals with no activity for 14 days",
+ "Hand new customers from Sales to Onboarding",
+];
+
+export function AgentBuilderHome({ name }: { name: string }) {
+ const router = useRouter();
+ const workspaceUrl = useWorkspaceUrl();
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const [initialPrompt, setInitialPrompt] = useState("");
+ const create = useMutation(
+ trpc.conversations.createBuilder.mutationOptions({
+ onSuccess: async ({ id }) => {
+ await queryClient.invalidateQueries({
+ queryKey: trpc.conversations.builderList.pathKey(),
+ });
+ router.push(workspaceUrl(`/chat/${id}`));
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const submit = async (
+ prompt: BuilderComposerPrompt,
+ clientRequestId: string,
+ ) => {
+ await create.mutateAsync({
+ ...prompt,
+ clientRequestId,
+ });
+ };
+
+ return (
+ <main className="relative flex min-h-0 flex-1 flex-col items-center justify-center overflow-y-auto px-4 pt-14 pb-20 sm:px-6 sm:pt-12 sm:pb-28">
+ <div className="flex w-full max-w-3xl flex-col items-center gap-3 pb-6 text-center">
+ <h1 className="text-balance font-medium text-2xl tracking-tight sm:text-3xl">
+ What can I help with, {firstName(name)}?
+ </h1>
+ <p className="max-w-xl text-balance text-muted-foreground text-sm">
+ Ask about your CRM, tag a record or integration, or describe an agent
+ to build to automate a task.
+ </p>
+ </div>
+
+ <div className="w-full max-w-3xl">
+ <AgentComposer
+ key={initialPrompt}
+ mode="home"
+ initialPrompt={initialPrompt}
+ onSubmit={submit}
+ />
+ <p className="flex h-8 items-center px-px text-muted-foreground text-xs">
+ Chats and agent drafts stay private to you. Deploying an agent makes
+ it available to the whole team.
+ </p>
+
+ <div className="pt-1">
+ <p className="flex h-7 items-center text-muted-foreground text-xs">
+ Suggested agents
+ </p>
+ {SUGGESTIONS.map((suggestion) => (
+ <button
+ key={suggestion}
+ type="button"
+ onClick={() => setInitialPrompt(`/Create agent ${suggestion}`)}
+ className="flex h-[42px] w-full items-center border-t text-left outline-none transition-colors hover:bg-muted/50 focus-visible:bg-muted/50"
+ >
+ <span className="min-w-0 flex-1 font-medium text-sm">
+ {suggestion}
+ </span>
+ <Icon
+ icon={ArrowRight}
+ className="size-4 text-muted-foreground"
+ />
+ </button>
+ ))}
+ </div>
+ </div>
+ </main>
+ );
+}
+
+function firstName(name: string): string {
+ return name.trim().split(/\s+/)[0] || "there";
+}
diff --git a/apps/app/components/agent-builder/agent-builder-shell.tsx b/apps/app/components/agent-builder/agent-builder-shell.tsx
new file mode 100644
index 00000000..ff2f2e47
--- /dev/null
+++ b/apps/app/components/agent-builder/agent-builder-shell.tsx
@@ -0,0 +1,46 @@
+import { Skeleton } from "@crm/ui/components/skeleton";
+import { AgentBuilderSidebar } from "./agent-builder-sidebar";
+
+type SidebarData = React.ComponentProps<
+ typeof AgentBuilderSidebar
+>["initialData"];
+
+export function AgentBuilderShell({
+ children,
+ sidebarData,
+}: {
+ children: React.ReactNode;
+ sidebarData?: SidebarData;
+}) {
+ return (
+ <div className="flex min-h-0 min-w-0 flex-1">
+ {sidebarData ? (
+ <AgentBuilderSidebar
+ className="hidden w-[213px] flex-none border-r md:flex"
+ initialData={sidebarData}
+ />
+ ) : (
+ <AgentBuilderSidebarFallback />
+ )}
+ <div className="flex min-w-0 flex-1 flex-col">{children}</div>
+ </div>
+ );
+}
+
+function AgentBuilderSidebarFallback() {
+ return (
+ <aside
+ aria-busy="true"
+ className="hidden w-[213px] flex-none flex-col border-r p-4 md:flex"
+ >
+ <div className="flex h-7 items-center pl-2 font-medium text-xs">
+ Chats
+ </div>
+ <div className="mt-3 space-y-2 px-2" aria-hidden="true">
+ <Skeleton className="h-2.5 w-16" />
+ <Skeleton className="h-7 w-full" />
+ <Skeleton className="h-7 w-full" />
+ </div>
+ </aside>
+ );
+}
diff --git a/apps/app/components/agent-builder/agent-builder-sidebar.tsx b/apps/app/components/agent-builder/agent-builder-sidebar.tsx
new file mode 100644
index 00000000..5b9dd957
--- /dev/null
+++ b/apps/app/components/agent-builder/agent-builder-sidebar.tsx
@@ -0,0 +1,250 @@
+"use client";
+
+import Add from "@carbon/icons-react/es/Add";
+import Bot from "@carbon/icons-react/es/Bot";
+import CheckmarkFilled from "@carbon/icons-react/es/CheckmarkFilled";
+import CircleFilled from "@carbon/icons-react/es/CircleFilled";
+import Renew from "@carbon/icons-react/es/Renew";
+import { Button } from "@crm/ui/components/button";
+import { Icon } from "@crm/ui/components/icon";
+import { cn } from "@crm/ui/lib/utils";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import Link from "next/link";
+import { usePathname } from "next/navigation";
+import { type ChatDateGroup, chatDateGroup } from "@/lib/chat-date-group";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+import { useHydrated } from "@/lib/use-hydrated";
+import { useWorkspaceUrl } from "@/lib/use-workspace-url";
+import { DeleteChatAction } from "./delete-chat-action";
+
+type Conversation = RouterOutputs["conversations"]["builderList"][number];
+type TeamAgent = RouterOutputs["agents"]["list"][number];
+type SidebarData = {
+ conversations: Conversation[];
+ agents: TeamAgent[];
+ updatedAt: number;
+};
+
+export function AgentBuilderSidebar({
+ className,
+ onNavigate,
+ initialData,
+}: {
+ className?: string;
+ onNavigate?: () => void;
+ initialData?: SidebarData;
+}) {
+ const pathname = usePathname();
+ const workspaceUrl = useWorkspaceUrl();
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const hydrated = useHydrated();
+ const conversations = useQuery({
+ ...trpc.conversations.builderList.queryOptions(),
+ initialData: initialData?.conversations,
+ initialDataUpdatedAt: initialData?.updatedAt,
+ refetchInterval: (query) =>
+ query.state.data?.some((conversation) => conversation.state === "working")
+ ? 2500
+ : 30_000,
+ });
+ const agents = useQuery({
+ ...trpc.agents.list.queryOptions(),
+ initialData: initialData?.agents,
+ initialDataUpdatedAt: initialData?.updatedAt,
+ refetchInterval: 60_000,
+ });
+ const markRead = useMutation(
+ trpc.conversations.markRead.mutationOptions({
+ onSuccess: () =>
+ queryClient.invalidateQueries({
+ queryKey: trpc.conversations.builderList.pathKey(),
+ }),
+ }),
+ );
+
+ const showData = Boolean(initialData) || hydrated;
+ const groupNow =
+ initialData && !hydrated
+ ? initialData.updatedAt
+ : conversations.dataUpdatedAt;
+ const groups = groupConversations(
+ showData ? (conversations.data ?? []) : [],
+ showData ? groupNow : 0,
+ );
+ const teamAgents = showData ? (agents.data ?? []) : [];
+
+ return (
+ <aside className={cn("min-h-0 min-w-0 flex-col p-4 font-sans", className)}>
+ <div className="flex h-7 shrink-0 items-center justify-between pl-2">
+ <span className="font-medium text-xs">Chats</span>
+ <Button asChild variant="ghost" size="icon-xs">
+ <Link
+ href={workspaceUrl("/chat")}
+ aria-label="New agent chat"
+ onClick={onNavigate}
+ >
+ <Icon icon={Add} />
+ </Link>
+ </Button>
+ </div>
+
+ <nav aria-label="Agent chats" className="min-h-0 flex-1 overflow-y-auto">
+ {groups.map((group) => (
+ <div key={group.label}>
+ <div className="flex h-8 items-end pb-1 pl-2 font-medium text-[11px] text-muted-foreground uppercase tracking-[0.08em]">
+ {group.label}
+ </div>
+ {group.items.map((conversation) => {
+ const href = workspaceUrl(`/chat/${conversation.id}`);
+ const active = pathname === href;
+ const title = conversation.title ?? "Untitled chat";
+ return (
+ <div
+ key={conversation.id}
+ className="group relative flex h-7 min-w-0 items-center"
+ >
+ <Link
+ href={href}
+ aria-current={active ? "page" : undefined}
+ onClick={() => {
+ if (conversation.unread) {
+ markRead.mutate({ id: conversation.id });
+ }
+ onNavigate?.();
+ }}
+ className={cn(
+ "flex h-7 min-w-0 flex-1 items-center gap-3 rounded-sm pr-8 pl-2 text-xs outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/60",
+ active && "bg-muted font-medium",
+ !active &&
+ conversation.state === "idle" &&
+ "text-muted-foreground",
+ )}
+ >
+ <ConversationState state={conversation.state} />
+ <span className="min-w-0 flex-1 truncate">{title}</span>
+ </Link>
+ <DeleteChatAction
+ conversationId={conversation.id}
+ title={title}
+ trigger="close"
+ returnToChatList={active}
+ onDeleted={active ? onNavigate : undefined}
+ className="absolute right-1 opacity-100 transition-opacity duration-150 [@media(hover:hover)]:pointer-events-none [@media(hover:hover)]:translate-x-1 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-focus-within:pointer-events-auto [@media(hover:hover)]:group-focus-within:translate-x-0 [@media(hover:hover)]:group-focus-within:opacity-100 [@media(hover:hover)]:group-hover:pointer-events-auto [@media(hover:hover)]:group-hover:translate-x-0 [@media(hover:hover)]:group-hover:opacity-100 motion-safe:transition-[opacity,translate] motion-reduce:translate-x-0"
+ />
+ </div>
+ );
+ })}
+ </div>
+ ))}
+
+ {groups.length === 0 ? (
+ <p className="px-2 py-3 text-muted-foreground text-xs">
+ No chats in the last 7 days.
+ </p>
+ ) : null}
+
+ <TeamAgents
+ agents={teamAgents}
+ pathname={pathname}
+ onNavigate={onNavigate}
+ />
+ </nav>
+ </aside>
+ );
+}
+
+function TeamAgents({
+ agents,
+ pathname,
+ onNavigate,
+}: {
+ agents: TeamAgent[];
+ pathname: string;
+ onNavigate?: () => void;
+}) {
+ const workspaceUrl = useWorkspaceUrl();
+
+ return (
+ <div className="mt-3 border-t pt-1">
+ <Link
+ href={workspaceUrl("/agents")}
+ onClick={onNavigate}
+ className="flex h-8 items-end gap-2 rounded-sm px-2 pb-1 font-medium text-[11px] text-muted-foreground uppercase tracking-[0.08em] outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"
+ >
+ <span className="min-w-0 flex-1">Team agents</span>
+ <span className="shrink-0 font-mono">{agents.length}</span>
+ </Link>
+ {agents.map((agent) => {
+ const href = workspaceUrl(`/agents/${agent.id}`);
+ const active = pathname === href;
+ return (
+ <Link
+ key={agent.id}
+ href={href}
+ aria-current={active ? "page" : undefined}
+ onClick={onNavigate}
+ className={cn(
+ "flex h-7 items-center gap-3 rounded-sm px-2 text-xs outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring/60",
+ active ? "bg-muted font-medium" : "text-muted-foreground",
+ )}
+ >
+ <span className="flex size-5 shrink-0 items-center justify-center">
+ <Icon icon={Bot} className="size-3.5" />
+ </span>
+ <span className="min-w-0 flex-1 truncate">{agent.name}</span>
+ </Link>
+ );
+ })}
+ </div>
+ );
+}
+
+function ConversationState({ state }: { state: Conversation["state"] }) {
+ if (state === "working") {
+ return (
+ <span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground">
+ <Icon icon={Renew} className="size-3.5 animate-spin" motion="none" />
+ </span>
+ );
+ }
+
+ if (state === "unread") {
+ return (
+ <span className="flex size-5 shrink-0 items-center justify-center text-ring">
+ <Icon icon={CircleFilled} className="size-3.5" motion="none" />
+ </span>
+ );
+ }
+
+ if (state === "deployed") {
+ return (
+ <span className="flex size-5 shrink-0 items-center justify-center text-ring">
+ <Icon icon={CheckmarkFilled} className="size-3.5" motion="none" />
+ </span>
+ );
+ }
+
+ return null;
+}
+
+function groupConversations(conversations: Conversation[], now: number) {
+ if (!now) return [];
+
+ const labels: ChatDateGroup[] = ["Today", "Yesterday", "Last 7 days"];
+ const items: Record<ChatDateGroup, Conversation[]> = {
+ Today: [],
+ Yesterday: [],
+ "Last 7 days": [],
+ };
+
+ for (const conversation of conversations) {
+ const label = chatDateGroup(conversation.lastMessageAt, now);
+ if (label) items[label].push(conversation);
+ }
+
+ return labels
+ .map((label) => ({ label, items: items[label] }))
+ .filter((group) => group.items.length > 0);
+}
diff --git a/apps/app/components/agent-builder/agent-code-workspace.tsx b/apps/app/components/agent-builder/agent-code-workspace.tsx
new file mode 100644
index 00000000..31c6bf93
--- /dev/null
+++ b/apps/app/components/agent-builder/agent-code-workspace.tsx
@@ -0,0 +1,172 @@
+"use client";
+
+import Checkmark from "@carbon/icons-react/es/Checkmark";
+import Renew from "@carbon/icons-react/es/Renew";
+import { Button } from "@crm/ui/components/button";
+import { Icon } from "@crm/ui/components/icon";
+import { File, MultiFileDiff } from "@pierre/diffs/react";
+import {
+ FileTree,
+ useFileTree,
+ useFileTreeSelection,
+} from "@pierre/trees/react";
+import { useState } from "react";
+import { latestBuilderArtifacts } from "@/lib/agent-builder-state";
+
+export type AgentCodeArtifact = {
+ id: string;
+ versionId: string | null;
+ path: string;
+ language: string;
+ content: string;
+ previousContent: string | null;
+ revision: number;
+ status: "WRITING" | "READY";
+ createdAt: string;
+};
+
+export function AgentCodeWorkspace({
+ artifacts,
+ working,
+ versionId = null,
+}: {
+ artifacts: AgentCodeArtifact[];
+ working: boolean;
+ versionId?: string | null;
+}) {
+ const latest = latestBuilderArtifacts(artifacts, versionId);
+ const paths = [...latest.keys()].sort();
+ const treeKey = paths
+ .map((path) => `${path}:${latest.get(path)?.status}`)
+ .join("|");
+
+ return (
+ <AgentCodeWorkspaceSurface
+ key={treeKey}
+ latest={latest}
+ paths={paths}
+ working={working}
+ />
+ );
+}
+
+function AgentCodeWorkspaceSurface({
+ latest,
+ paths,
+ working,
+}: {
+ latest: Map<string, AgentCodeArtifact>;
+ paths: string[];
+ working: boolean;
+}) {
+ const [mode, setMode] = useState<"code" | "changes">("code");
+ const { model } = useFileTree({
+ paths,
+ initialExpansion: "open",
+ initialSelectedPaths: paths[0] ? [paths[0]] : [],
+ gitStatus: paths.map((path) => ({
+ path,
+ status: latest.get(path)?.status === "READY" ? "added" : "modified",
+ })),
+ });
+ const selection = useFileTreeSelection(model);
+ const selectedPath =
+ selection.find((path) => latest.has(path)) ?? paths[0] ?? null;
+ const artifact = selectedPath ? latest.get(selectedPath) : null;
+ const previous = artifact?.previousContent ?? null;
+ const showChanges = mode === "changes" && previous !== null;
+
+ if (!artifact) return null;
+
+ const file = {
+ name: artifact.path,
+ contents: artifact.content,
+ lang: artifact.language,
+ cacheKey: artifact.id,
+ };
+
+ return (
+ <section
+ aria-label="Generated agent files"
+ className="overflow-hidden rounded-lg bg-muted/40"
+ >
+ <header className="flex min-h-11 flex-wrap items-center gap-2 px-3 py-2">
+ <span
+ className="flex min-w-0 flex-1 items-center gap-2"
+ role={working ? "status" : undefined}
+ >
+ <Icon
+ icon={working ? Renew : Checkmark}
+ className={
+ working ? "size-3.5 animate-spin text-ring" : "size-3.5 text-ring"
+ }
+ motion="none"
+ />
+ <span className="truncate font-medium text-sm">
+ {working ? "Writing agent code" : "Agent code"}
+ </span>
+ <span className="hidden shrink-0 text-muted-foreground text-xs sm:inline">
+ {paths.length} {paths.length === 1 ? "file" : "files"}
+ </span>
+ </span>
+ <fieldset
+ className="flex min-w-0 items-center gap-1 border-0 p-0"
+ aria-label="Code view"
+ >
+ <Button
+ variant={mode === "code" ? "secondary" : "ghost"}
+ size="xs"
+ aria-pressed={mode === "code"}
+ onClick={() => setMode("code")}
+ >
+ Code
+ </Button>
+ <Button
+ variant={mode === "changes" ? "secondary" : "ghost"}
+ size="xs"
+ disabled={previous === null}
+ aria-pressed={mode === "changes"}
+ onClick={() => setMode("changes")}
+ >
+ Changes
+ </Button>
+ </fieldset>
+ </header>
+
+ <div className="mx-2 mb-2 grid min-h-0 overflow-hidden rounded-md bg-background md:grid-cols-[190px_minmax(0,1fr)]">
+ <div className="h-36 min-w-0 border-b border-border/60 bg-muted/15 p-2 md:h-[360px] md:border-r md:border-b-0">
+ <FileTree
+ model={model}
+ aria-label="Agent files"
+ style={{ height: "100%", width: "100%" }}
+ />
+ </div>
+ <div className="h-80 min-w-0 overflow-auto bg-background md:h-[360px]">
+ {showChanges ? (
+ <MultiFileDiff
+ oldFile={{
+ name: artifact.path,
+ contents: previous,
+ lang: artifact.language,
+ cacheKey: `${artifact.id}:previous`,
+ }}
+ newFile={file}
+ options={{
+ diffStyle: "unified",
+ overflow: "wrap",
+ themeType: "system",
+ }}
+ disableWorkerPool
+ />
+ ) : (
+ <File
+ file={file}
+ options={{ overflow: "wrap", themeType: "system" }}
+ disableWorkerPool
+ />
+ )}
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/apps/app/components/agent-builder/agent-composer.tsx b/apps/app/components/agent-builder/agent-composer.tsx
new file mode 100644
index 00000000..d7a6bc04
--- /dev/null
+++ b/apps/app/components/agent-builder/agent-composer.tsx
@@ -0,0 +1,869 @@
+"use client";
+
+import Add from "@carbon/icons-react/es/Add";
+import Application from "@carbon/icons-react/es/Application";
+import ArrowUp from "@carbon/icons-react/es/ArrowUp";
+import AttachmentIcon from "@carbon/icons-react/es/Attachment";
+import Building from "@carbon/icons-react/es/Building";
+import Calendar from "@carbon/icons-react/es/Calendar";
+import Email from "@carbon/icons-react/es/Email";
+import Partnership from "@carbon/icons-react/es/Partnership";
+import Search from "@carbon/icons-react/es/Search";
+import User from "@carbon/icons-react/es/User";
+import {
+ AsyncButtonContent,
+ useAsyncAction,
+} from "@crm/ui/components/async-action";
+import { Button } from "@crm/ui/components/button";
+import { type CarbonIcon, Icon } from "@crm/ui/components/icon";
+import { Input } from "@crm/ui/components/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@crm/ui/components/popover";
+import { Skeleton } from "@crm/ui/components/skeleton";
+import { SkeletonSwap } from "@crm/ui/components/skeleton-swap";
+import { Textarea } from "@crm/ui/components/textarea";
+import { cn } from "@crm/ui/lib/utils";
+import { useQuery } from "@tanstack/react-query";
+import { useReducer, useRef } from "react";
+import { toast } from "sonner";
+import {
+ type BuilderCommandType,
+ builderCommandType,
+ consumeBuilderCommand,
+ consumeBuilderIntent,
+} from "@/lib/agent-builder";
+import { useTRPC } from "@/lib/trpc/client";
+import { AGENT_COMPOSER_CLASS_NAME } from "../agent-composer-frame";
+import {
+ ChatAttachmentChip,
+ type ChatChipAttachment,
+ type ChatChipResource,
+ ChatCommandChip,
+ ChatReferenceChip,
+ ChatReferenceIdentity,
+} from "./chat-chips";
+
+export type BuilderResource = ChatChipResource;
+
+export type BuilderUploadAttachment = ChatChipAttachment & {
+ id?: never;
+ contentBase64: string;
+};
+
+export type BuilderStoredAttachment = ChatChipAttachment & {
+ id: string;
+ contentBase64?: never;
+};
+
+export type BuilderAttachment =
+ | BuilderUploadAttachment
+ | BuilderStoredAttachment;
+
+export type BuilderPrompt<
+ TAttachment extends BuilderAttachment = BuilderAttachment,
+> = {
+ commandType: BuilderCommandType;
+ message: string;
+ resources: BuilderResource[];
+ attachments: TAttachment[];
+};
+
+export type BuilderComposerPrompt = BuilderPrompt<BuilderUploadAttachment>;
+
+type PendingSubmission = {
+ key: string;
+ clientRequestId: string;
+};
+
+const CREATE_AGENT_COMMAND = {
+ commandType: "CREATE_AGENT" as const,
+ invocation: "/Create agent",
+ label: "Create agent",
+ description: "Build a durable team automation",
+};
+
+type ComposerCommand = typeof CREATE_AGENT_COMMAND;
+
+type ComposerState = {
+ draft: string;
+ command: ComposerCommand | null;
+ detectedCommandLabel: string | null;
+ commandOpen: boolean;
+ resourceQuery: string;
+ resources: BuilderResource[];
+ attachments: BuilderUploadAttachment[];
+ attachmentsReading: boolean;
+};
+
+type ComposerAction =
+ | { type: "draft.changed"; value: string }
+ | { type: "command.selected" }
+ | { type: "command.removed" }
+ | { type: "command.open.changed"; open: boolean }
+ | { type: "resource.query.changed"; value: string }
+ | { type: "resource.added"; resource: BuilderResource }
+ | { type: "resource.removed"; resource: BuilderResource }
+ | { type: "attachments.added"; attachments: BuilderUploadAttachment[] }
+ | { type: "attachment.removed"; attachment: BuilderUploadAttachment }
+ | { type: "attachments.reading.started" }
+ | { type: "attachments.reading.finished" }
+ | { type: "submitted" };
+
+function initialComposerState(initialPrompt: string): ComposerState {
+ const explicitCommand = consumeBuilderCommand(initialPrompt);
+ const detectedIntent = explicitCommand
+ ? null
+ : consumeBuilderIntent(initialPrompt);
+ return {
+ draft: explicitCommand?.body ?? initialPrompt,
+ command: explicitCommand || detectedIntent ? CREATE_AGENT_COMMAND : null,
+ detectedCommandLabel: detectedIntent?.invocation ?? null,
+ commandOpen: false,
+ resourceQuery: "",
+ resources: [],
+ attachments: [],
+ attachmentsReading: false,
+ };
+}
+
+function composerReducer(
+ state: ComposerState,
+ action: ComposerAction,
+): ComposerState {
+ switch (action.type) {
+ case "draft.changed": {
+ const explicitCommand = consumeBuilderCommand(action.value);
+ if (explicitCommand) {
+ return {
+ ...state,
+ draft: explicitCommand.body,
+ command: CREATE_AGENT_COMMAND,
+ detectedCommandLabel: null,
+ commandOpen: false,
+ };
+ }
+ const detectedIntent = state.command
+ ? null
+ : consumeBuilderIntent(action.value);
+ if (detectedIntent) {
+ return {
+ ...state,
+ draft: action.value,
+ command: CREATE_AGENT_COMMAND,
+ detectedCommandLabel: detectedIntent.invocation,
+ commandOpen: false,
+ };
+ }
+ return {
+ ...state,
+ draft: action.value,
+ commandOpen: !state.command && action.value.trimStart().startsWith("/"),
+ };
+ }
+ case "command.selected":
+ return {
+ ...state,
+ command: CREATE_AGENT_COMMAND,
+ detectedCommandLabel: null,
+ commandOpen: false,
+ draft: state.draft.trimStart().startsWith("/") ? "" : state.draft,
+ };
+ case "command.removed":
+ return {
+ ...state,
+ command: null,
+ detectedCommandLabel: null,
+ };
+ case "command.open.changed":
+ return { ...state, commandOpen: action.open };
+ case "resource.query.changed":
+ return { ...state, resourceQuery: action.value };
+ case "resource.added":
+ return state.resources.some(
+ (item) =>
+ item.kind === action.resource.kind && item.id === action.resource.id,
+ )
+ ? state
+ : { ...state, resources: [...state.resources, action.resource] };
+ case "resource.removed":
+ return {
+ ...state,
+ resources: state.resources.filter(
+ (item) =>
+ item.kind !== action.resource.kind ||
+ item.id !== action.resource.id,
+ ),
+ };
+ case "attachments.added": {
+ const keys = new Set(state.attachments.map(attachmentKey));
+ const added = action.attachments.filter((attachment) => {
+ const key = attachmentKey(attachment);
+ if (keys.has(key)) return false;
+ keys.add(key);
+ return true;
+ });
+ if (added.length === 0) return state;
+ return {
+ ...state,
+ attachments: [...state.attachments, ...added].slice(0, 5),
+ };
+ }
+ case "attachment.removed":
+ return {
+ ...state,
+ attachments: state.attachments.filter(
+ (item) => item !== action.attachment,
+ ),
+ };
+ case "attachments.reading.started":
+ return { ...state, attachmentsReading: true };
+ case "attachments.reading.finished":
+ return { ...state, attachmentsReading: false };
+ case "submitted":
+ return {
+ ...state,
+ draft: "",
+ command: null,
+ detectedCommandLabel: null,
+ commandOpen: false,
+ resources: [],
+ attachments: [],
+ attachmentsReading: false,
+ };
+ }
+}
+
+function attachmentKey(attachment: ChatChipAttachment): string {
+ if (attachment.id) return attachment.id;
+ const existing = attachmentKeys.get(attachment);
+ if (existing) return existing;
+ const key = crypto.randomUUID();
+ attachmentKeys.set(attachment, key);
+ return key;
+}
+
+const attachmentKeys = new WeakMap<ChatChipAttachment, string>();
+
+export function AgentComposer({
+ mode,
+ disabled = false,
+ initialPrompt = "",
+ onSubmit,
+}: {
+ mode: "home" | "chat";
+ disabled?: boolean;
+ initialPrompt?: string;
+ onSubmit: (
+ prompt: BuilderComposerPrompt,
+ clientRequestId: string,
+ ) => Promise<void>;
+}) {
+ const trpc = useTRPC();
+ const pendingSubmission = useRef<PendingSubmission | null>(null);
+ const [state, dispatch] = useReducer(
+ composerReducer,
+ initialPrompt,
+ initialComposerState,
+ );
+ const resourceResults = useQuery(
+ trpc.conversations.builderResources.queryOptions({
+ q: state.resourceQuery,
+ }),
+ );
+ const google = useQuery(trpc.google.status.queryOptions());
+ const submitAction = useAsyncAction({
+ action: onSubmit,
+ onSuccess: () => {
+ pendingSubmission.current = null;
+ dispatch({ type: "submitted" });
+ },
+ });
+ const locked = disabled || submitAction.pending;
+ const canSend =
+ state.draft.trim().length > 0 && !locked && !state.attachmentsReading;
+
+ const submit = () => {
+ if (!canSend) return;
+ const body = state.draft.trim();
+ const message =
+ state.command && !state.detectedCommandLabel
+ ? `${state.command.invocation} ${body}`
+ : body;
+ const prompt = {
+ commandType: state.command?.commandType ?? builderCommandType(message),
+ message,
+ resources: state.resources,
+ attachments: state.attachments,
+ };
+ const key = JSON.stringify(prompt);
+ const pending = pendingSubmission.current;
+ const clientRequestId =
+ pending?.key === key ? pending.clientRequestId : crypto.randomUUID();
+ pendingSubmission.current = { key, clientRequestId };
+ submitAction.run(prompt, clientRequestId);
+ };
+
+ const connectedGoogle = (google.data?.sources ?? []).filter(
+ (source) => source.connected,
+ );
+
+ return (
+ <div
+ className={cn(
+ AGENT_COMPOSER_CLASS_NAME,
+ mode === "home" ? "min-h-24" : "min-h-[78px]",
+ )}
+ >
+ <ComposerContext
+ command={state.command}
+ resources={state.resources}
+ attachments={state.attachments}
+ disabled={locked}
+ dispatch={dispatch}
+ />
+
+ <ComposerTextarea
+ mode={mode}
+ value={state.draft}
+ detectedIntent={state.detectedCommandLabel}
+ onChange={(value) => dispatch({ type: "draft.changed", value })}
+ disabled={locked}
+ onSubmit={submit}
+ />
+
+ <div className="flex h-7 items-center justify-between">
+ <ComposerTools
+ state={state}
+ resources={resourceResults.data ?? []}
+ resourcesLoading={resourceResults.isFetching}
+ resourcesReady={resourceResults.isSuccess}
+ connectedGoogle={connectedGoogle}
+ disabled={locked}
+ attachmentsReading={state.attachmentsReading}
+ dispatch={dispatch}
+ />
+
+ <Button
+ variant="default"
+ size="icon-sm"
+ disabled={!canSend}
+ aria-busy={submitAction.pending || state.attachmentsReading}
+ aria-label={
+ state.attachmentsReading ? "Preparing attachments" : "Send message"
+ }
+ onClick={submit}
+ className="rounded-full"
+ >
+ <AsyncButtonContent
+ status={state.attachmentsReading ? "pending" : submitAction.status}
+ pendingLabel={
+ <span className="sr-only">
+ {state.attachmentsReading ? "Preparing attachments" : "Sending"}
+ </span>
+ }
+ successLabel={<span className="sr-only">Sent</span>}
+ errorLabel={<span className="sr-only">Send failed</span>}
+ >
+ <Icon icon={ArrowUp} />
+ </AsyncButtonContent>
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function ComposerTextarea({
+ mode,
+ value,
+ detectedIntent,
+ disabled,
+ onChange,
+ onSubmit,
+}: {
+ mode: "home" | "chat";
+ value: string;
+ detectedIntent: string | null;
+ disabled: boolean;
+ onChange: (value: string) => void;
+ onSubmit: () => void;
+}) {
+ const emphasis = useRef<HTMLDivElement>(null);
+ const intentStart = detectedIntent ? value.indexOf(detectedIntent) : -1;
+ const showEmphasis = detectedIntent !== null && intentStart >= 0;
+
+ return (
+ <div className="relative grid">
+ {showEmphasis ? (
+ <div
+ ref={emphasis}
+ data-intent-overlay
+ aria-hidden
+ className="pointer-events-none absolute inset-0 overflow-hidden whitespace-pre-wrap break-words border border-transparent px-1 py-0 text-base leading-6 sm:text-[15px] md:text-xs"
+ >
+ <span>{value.slice(0, intentStart)}</span>
+ <span data-intent-trigger className="relative">
+ {detectedIntent}
+ <span
+ data-intent-accent
+ className="absolute inset-x-0 bottom-0 h-px origin-left animate-in bg-primary duration-200 ease-out zoom-in-0 motion-reduce:animate-none"
+ />
+ </span>
+ <span>{value.slice(intentStart + detectedIntent.length)}</span>
+ </div>
+ ) : null}
+ <Textarea
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ onScroll={(event) => {
+ if (!emphasis.current) return;
+ emphasis.current.style.translate = `${-event.currentTarget.scrollLeft}px ${-event.currentTarget.scrollTop}px`;
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && !event.shiftKey) {
+ event.preventDefault();
+ onSubmit();
+ }
+ }}
+ disabled={disabled}
+ rows={mode === "home" ? 2 : 1}
+ variant="composer"
+ size="composer"
+ placeholder={
+ mode === "home"
+ ? "Ask about your CRM or automate a task…"
+ : "Send a message"
+ }
+ aria-label="Message the agent builder"
+ className={cn(
+ "relative",
+ showEmphasis && "text-transparent caret-foreground",
+ )}
+ />
+ </div>
+ );
+}
+
+function ComposerContext({
+ command,
+ resources,
+ attachments,
+ disabled,
+ dispatch,
+}: {
+ command: ComposerCommand | null;
+ resources: BuilderResource[];
+ attachments: BuilderUploadAttachment[];
+ disabled: boolean;
+ dispatch: React.Dispatch<ComposerAction>;
+}) {
+ if (!command && resources.length === 0 && attachments.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className="flex flex-wrap gap-1 px-1 pb-1">
+ {command ? (
+ <ChatCommandChip
+ label={command.label}
+ icon={Application}
+ onRemove={
+ disabled ? undefined : () => dispatch({ type: "command.removed" })
+ }
+ />
+ ) : null}
+ {resources.map((resource) => (
+ <ChatReferenceChip
+ key={`${resource.kind}:${resource.id}`}
+ resource={resource}
+ icon={RESOURCE_ICONS[resource.kind]}
+ onRemove={
+ disabled
+ ? undefined
+ : () => dispatch({ type: "resource.removed", resource })
+ }
+ />
+ ))}
+ {attachments.map((attachment) => (
+ <ChatAttachmentChip
+ key={attachmentKey(attachment)}
+ attachment={attachment}
+ onRemove={
+ disabled
+ ? undefined
+ : () => dispatch({ type: "attachment.removed", attachment })
+ }
+ />
+ ))}
+ </div>
+ );
+}
+
+function ComposerTools({
+ state,
+ resources,
+ resourcesLoading,
+ resourcesReady,
+ connectedGoogle,
+ disabled,
+ attachmentsReading,
+ dispatch,
+}: {
+ state: ComposerState;
+ resources: BuilderResource[];
+ resourcesLoading: boolean;
+ resourcesReady: boolean;
+ connectedGoogle: Array<{ source: string }>;
+ disabled: boolean;
+ attachmentsReading: boolean;
+ dispatch: React.Dispatch<ComposerAction>;
+}) {
+ return (
+ <div className="flex items-center gap-0.5">
+ <ResourcePicker
+ query={state.resourceQuery}
+ resources={resources}
+ loading={resourcesLoading}
+ ready={resourcesReady}
+ connectedGoogle={connectedGoogle}
+ disabled={disabled}
+ dispatch={dispatch}
+ />
+ <AttachmentPicker
+ disabled={disabled || attachmentsReading}
+ dispatch={dispatch}
+ />
+ <CommandPicker
+ open={state.commandOpen}
+ disabled={disabled}
+ dispatch={dispatch}
+ />
+ </div>
+ );
+}
+
+function ResourcePicker({
+ query,
+ resources,
+ loading,
+ ready,
+ connectedGoogle,
+ disabled,
+ dispatch,
+}: {
+ query: string;
+ resources: BuilderResource[];
+ loading: boolean;
+ ready: boolean;
+ connectedGoogle: Array<{ source: string }>;
+ disabled: boolean;
+ dispatch: React.Dispatch<ComposerAction>;
+}) {
+ const add = (resource: BuilderResource) =>
+ dispatch({ type: "resource.added", resource });
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Tag CRM records and integrations"
+ disabled={disabled}
+ >
+ <Icon icon={Add} />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent size="fit" align="start" side="top" className="w-80">
+ <div className="border-b p-2">
+ <div className="relative">
+ <Icon
+ icon={Search}
+ className="absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground"
+ />
+ <Input
+ value={query}
+ onChange={(event) =>
+ dispatch({
+ type: "resource.query.changed",
+ value: event.target.value,
+ })
+ }
+ placeholder="Search CRM records"
+ aria-label="Search CRM records"
+ disabled={disabled}
+ className="pl-8"
+ />
+ </div>
+ </div>
+ <div className="max-h-72 overflow-y-auto p-1">
+ {connectedGoogle.map((source) => {
+ const calendar = source.source === "calendar";
+ const label = calendar ? "Google Calendar" : "Gmail";
+ return (
+ <ResourceButton
+ key={source.source}
+ icon={calendar ? Calendar : Email}
+ label={label}
+ detail="Connected integration"
+ disabled={disabled}
+ onSelect={() =>
+ add({
+ kind: "integration",
+ id: `google:${source.source}`,
+ label,
+ detail: "Connected integration",
+ imageUrl: null,
+ })
+ }
+ />
+ );
+ })}
+ <SkeletonSwap
+ loading={loading}
+ label="CRM records"
+ skeleton={<ResourceResultsSkeleton />}
+ >
+ {resources.map((resource) => (
+ <ResourceButton
+ key={`${resource.kind}:${resource.id}`}
+ icon={RESOURCE_ICONS[resource.kind]}
+ label={resource.label}
+ detail={resource.detail ?? RESOURCE_LABELS[resource.kind]}
+ disabled={disabled}
+ imageUrl={resource.imageUrl}
+ onSelect={() => add(resource)}
+ />
+ ))}
+ {ready && connectedGoogle.length === 0 && resources.length === 0 ? (
+ <p className="px-3 py-5 text-center text-muted-foreground text-xs">
+ No matching records.
+ </p>
+ ) : null}
+ </SkeletonSwap>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+function AttachmentPicker({
+ disabled,
+ dispatch,
+}: {
+ disabled: boolean;
+ dispatch: React.Dispatch<ComposerAction>;
+}) {
+ const input = useRef<HTMLInputElement>(null);
+ const addFiles = async (files: FileList | null) => {
+ if (!files || files.length === 0) return;
+ dispatch({ type: "attachments.reading.started" });
+ try {
+ const attachments = await readFiles(files);
+ dispatch({ type: "attachments.added", attachments });
+ } catch {
+ toast.error("Those files could not be attached. Try again.");
+ } finally {
+ dispatch({ type: "attachments.reading.finished" });
+ }
+ };
+
+ return (
+ <>
+ <input
+ ref={input}
+ type="file"
+ multiple
+ disabled={disabled}
+ className="hidden"
+ onChange={(event) => {
+ void addFiles(event.currentTarget.files);
+ event.currentTarget.value = "";
+ }}
+ />
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Attach files"
+ disabled={disabled}
+ onClick={() => input.current?.click()}
+ >
+ <Icon icon={AttachmentIcon} />
+ </Button>
+ </>
+ );
+}
+
+function CommandPicker({
+ open,
+ disabled,
+ dispatch,
+}: {
+ open: boolean;
+ disabled: boolean;
+ dispatch: React.Dispatch<ComposerAction>;
+}) {
+ return (
+ <Popover
+ open={disabled ? false : open}
+ onOpenChange={(next) =>
+ dispatch({ type: "command.open.changed", open: next })
+ }
+ >
+ <PopoverTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Open slash commands"
+ disabled={disabled}
+ className="font-mono text-sm"
+ >
+ /
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent size="fit" align="start" side="top" className="w-64 p-1">
+ <button
+ type="button"
+ onClick={() => dispatch({ type: "command.selected" })}
+ className="flex w-full items-center gap-3 rounded-sm px-3 py-2 text-left outline-none hover:bg-muted focus-visible:bg-muted"
+ disabled={disabled}
+ >
+ <Icon icon={Application} className="size-4 text-muted-foreground" />
+ <span>
+ <span className="block font-medium text-xs">
+ /{CREATE_AGENT_COMMAND.label}
+ </span>
+ <span className="block text-muted-foreground text-xs">
+ {CREATE_AGENT_COMMAND.description}
+ </span>
+ </span>
+ </button>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+function ResourceResultsSkeleton() {
+ return (
+ <div className="flex flex-col gap-1 px-3 py-2">
+ {["first", "second", "third"].map((item) => (
+ <div key={item} className="flex h-10 items-center gap-3">
+ <Skeleton className="size-6 shrink-0" />
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ <Skeleton className="h-3 w-2/3" />
+ <Skeleton className="h-2.5 w-1/3" />
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+const RESOURCE_ICONS: Record<BuilderResource["kind"], CarbonIcon> = {
+ integration: Application,
+ company: Building,
+ contact: User,
+ deal: Partnership,
+};
+
+const RESOURCE_LABELS: Record<BuilderResource["kind"], string> = {
+ integration: "Integration",
+ company: "Company",
+ contact: "Contact",
+ deal: "Deal",
+};
+
+function ResourceButton({
+ icon,
+ label,
+ detail,
+ imageUrl,
+ disabled,
+ onSelect,
+}: {
+ icon: CarbonIcon;
+ label: string;
+ detail: string | null;
+ imageUrl?: string | null;
+ disabled: boolean;
+ onSelect: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onSelect}
+ disabled={disabled}
+ className="flex w-full items-center gap-3 rounded-sm px-3 py-2 text-left outline-none hover:bg-muted focus-visible:bg-muted"
+ >
+ <ChatReferenceIdentity
+ resource={{
+ kind: "integration",
+ id: label,
+ label,
+ detail,
+ imageUrl,
+ }}
+ icon={icon}
+ />
+ </button>
+ );
+}
+
+async function readFiles(
+ files: FileList | null,
+): Promise<BuilderUploadAttachment[]> {
+ if (!files) return [];
+ const acceptedFiles: File[] = [];
+
+ for (const file of Array.from(files).slice(0, 5)) {
+ if (file.size === 0) {
+ toast.error(`${file.name} is empty.`);
+ continue;
+ }
+ if (file.size > 2_000_000) {
+ toast.error(`${file.name} is larger than 2 MB.`);
+ continue;
+ }
+ if (file.name.length > 180) {
+ toast.error("That file name is too long.");
+ continue;
+ }
+ if (file.type.length > 120) {
+ toast.error(`${file.name} has an unsupported file type.`);
+ continue;
+ }
+ acceptedFiles.push(file);
+ }
+
+ const attachments = await Promise.all(
+ acceptedFiles.map(async (file): Promise<BuilderUploadAttachment | null> => {
+ try {
+ return {
+ name: file.name,
+ type: file.type || "application/octet-stream",
+ size: file.size,
+ contentBase64: bytesToBase64(
+ new Uint8Array(await file.arrayBuffer()),
+ ),
+ };
+ } catch {
+ toast.error(`${file.name} could not be read.`);
+ return null;
+ }
+ }),
+ );
+
+ return attachments.filter(
+ (attachment): attachment is BuilderUploadAttachment => attachment !== null,
+ );
+}
+
+function bytesToBase64(bytes: Uint8Array): string {
+ let binary = "";
+ for (let index = 0; index < bytes.length; index += 8192) {
+ binary += String.fromCharCode(...bytes.subarray(index, index + 8192));
+ }
+ return btoa(binary);
+}
diff --git a/apps/app/components/agent-builder/chat-chips.tsx b/apps/app/components/agent-builder/chat-chips.tsx
new file mode 100644
index 00000000..4286c482
--- /dev/null
+++ b/apps/app/components/agent-builder/chat-chips.tsx
@@ -0,0 +1,170 @@
+import Close from "@carbon/icons-react/es/Close";
+import Document from "@carbon/icons-react/es/Document";
+import { Avatar, AvatarFallback, AvatarImage } from "@crm/ui/components/avatar";
+import { type CarbonIcon, Icon } from "@crm/ui/components/icon";
+import Image from "next/image";
+
+export type ChatChipResource = {
+ kind: "integration" | "company" | "contact" | "deal";
+ id: string;
+ label: string;
+ detail?: string | null;
+ imageUrl?: string | null;
+};
+
+export type ChatChipAttachment = {
+ id?: string;
+ name: string;
+ type: string;
+ size: number;
+ contentBase64?: string;
+ previewUrl?: string | null;
+};
+
+export function ChatReferenceChip({
+ resource,
+ icon,
+ onRemove,
+}: {
+ resource: ChatChipResource;
+ icon: CarbonIcon;
+ onRemove?: () => void;
+}) {
+ return (
+ <span className="flex min-w-0 max-w-full items-center gap-2 rounded-md border bg-background py-1 pr-2 pl-1 text-left shadow-xs">
+ <ChatReferenceIdentity resource={resource} icon={icon} />
+ {onRemove ? (
+ <button
+ type="button"
+ aria-label={`Remove ${resource.label}`}
+ onClick={onRemove}
+ className="flex size-6 shrink-0 items-center justify-center rounded-sm text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"
+ >
+ <Icon icon={Close} className="size-3" />
+ </button>
+ ) : null}
+ </span>
+ );
+}
+
+export function ChatReferenceIdentity({
+ resource,
+ icon,
+}: {
+ resource: ChatChipResource;
+ icon: CarbonIcon;
+}) {
+ return (
+ <>
+ <Avatar size="sm">
+ {resource.imageUrl ? (
+ <AvatarImage src={resource.imageUrl} alt="" />
+ ) : null}
+ <AvatarFallback>
+ <Icon icon={icon} className="size-3" />
+ </AvatarFallback>
+ </Avatar>
+ <span className="min-w-0 max-w-48">
+ <span className="block truncate font-medium text-xs">
+ {resource.label}
+ </span>
+ {resource.detail ? (
+ <span className="block truncate text-[11px] text-muted-foreground">
+ {resource.detail}
+ </span>
+ ) : null}
+ </span>
+ </>
+ );
+}
+
+export function ChatAttachmentChip({
+ attachment,
+ onRemove,
+}: {
+ attachment: ChatChipAttachment;
+ onRemove?: () => void;
+}) {
+ const image = isPreviewableImage(attachment.type)
+ ? (attachment.previewUrl ??
+ (attachment.contentBase64
+ ? `data:${attachment.type};base64,${attachment.contentBase64}`
+ : null))
+ : null;
+
+ return (
+ <span className="flex min-w-0 max-w-full items-center gap-2 rounded-md border bg-background py-1 pr-2 pl-1 text-left shadow-xs">
+ <span className="flex size-6 shrink-0 items-center justify-center overflow-hidden rounded-sm bg-muted text-muted-foreground">
+ {image ? (
+ <Image
+ src={image}
+ alt=""
+ width={24}
+ height={24}
+ unoptimized
+ className="size-full object-cover"
+ />
+ ) : (
+ <Icon icon={Document} className="size-3.5" />
+ )}
+ </span>
+ <span className="min-w-0 max-w-48">
+ <span className="block truncate font-medium text-xs">
+ {attachment.name}
+ </span>
+ <span className="block text-[11px] text-muted-foreground">
+ {formatBytes(attachment.size)}
+ </span>
+ </span>
+ {onRemove ? (
+ <button
+ type="button"
+ aria-label={`Remove ${attachment.name}`}
+ onClick={onRemove}
+ className="flex size-6 shrink-0 items-center justify-center rounded-sm text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"
+ >
+ <Icon icon={Close} className="size-3" />
+ </button>
+ ) : null}
+ </span>
+ );
+}
+
+export function ChatCommandChip({
+ label,
+ icon,
+ onRemove,
+}: {
+ label: string;
+ icon: CarbonIcon;
+ onRemove?: () => void;
+}) {
+ return (
+ <span className="flex h-7 items-center gap-1.5 rounded-md bg-primary px-2 text-primary-foreground text-xs">
+ <Icon icon={icon} className="size-3.5" />
+ <span className="font-medium">{label}</span>
+ {onRemove ? (
+ <button
+ type="button"
+ aria-label={`Remove ${label}`}
+ onClick={onRemove}
+ className="-mr-1 flex size-5 items-center justify-center rounded-sm outline-none hover:bg-primary-foreground/15 focus-visible:ring-2 focus-visible:ring-primary-foreground/60"
+ >
+ <Icon icon={Close} className="size-3" />
+ </button>
+ ) : null}
+ </span>
+ );
+}
+
+function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+function isPreviewableImage(mediaType: string): boolean {
+ return ["image/gif", "image/jpeg", "image/png", "image/webp"].includes(
+ mediaType.toLowerCase(),
+ );
+}
diff --git a/apps/app/components/agent-builder/deal-list-result.tsx b/apps/app/components/agent-builder/deal-list-result.tsx
new file mode 100644
index 00000000..cd14ecec
--- /dev/null
+++ b/apps/app/components/agent-builder/deal-list-result.tsx
@@ -0,0 +1,180 @@
+"use client";
+
+import { EmptyCellValue } from "@crm/ui/components/empty-cell";
+import {
+ SimpleTable,
+ type SimpleTableColumn,
+ SimpleTableRow,
+} from "@crm/ui/components/simple-table";
+import { TableCell } from "@crm/ui/components/table";
+import { formatMoney } from "@crm/ui/lib/format";
+import { CompanyCell } from "@/components/crm/company-cell";
+import { DealStageIndicator } from "@/components/crm/deal-stage";
+import { OwnerCell } from "@/components/crm/owner-cell";
+import { usePrefetchRecord } from "@/components/crm/record-sheet/record-prefetch";
+import { useOpenRecord } from "@/components/crm/record-sheet/record-stack";
+import { LocalDay } from "@/components/local-date-time";
+import type { DealListItem, DealListResult } from "@/lib/agent-transcript";
+import { DEAL_STAGE_OPTIONS } from "@/lib/deal-stage";
+
+const COLUMNS: SimpleTableColumn[] = [
+ { id: "deal", header: "Deal", width: "w-[20%]" },
+ { id: "company", header: "Company", width: "w-[18%]" },
+ { id: "stage", header: "Stage", width: "w-[18%]" },
+ {
+ id: "amount",
+ header: "Amount",
+ width: "w-[12%]",
+ align: "right",
+ },
+ { id: "owner", header: "Owner", width: "w-[14%]" },
+ { id: "close", header: "Close date", width: "w-[12%]" },
+ { id: "idle", header: "Idle", width: "w-[8%]", align: "right" },
+];
+
+export function DealListResultTable({ result }: { result: DealListResult }) {
+ const openRecord = useOpenRecord();
+ const prefetchRecord = usePrefetchRecord();
+ const count = result.deals.length;
+ const title = tableTitle(result);
+
+ return (
+ <section aria-label={title} className="flex w-full flex-col gap-3">
+ <SimpleTable
+ columns={COLUMNS}
+ className="min-w-[56rem] table-fixed [&_td:first-child]:pl-4 [&_td:last-child]:pr-4 [&_th:first-child]:pl-4 [&_th:last-child]:pr-4"
+ headerHeight="h-11"
+ >
+ {count === 0 ? (
+ <SimpleTableRow>
+ <TableCell
+ colSpan={COLUMNS.length}
+ className="h-32 whitespace-normal py-8 text-center align-middle text-muted-foreground"
+ >
+ No deals met these pipeline filters.
+ </TableCell>
+ </SimpleTableRow>
+ ) : (
+ result.deals.map((deal) => {
+ const record = { kind: "deal" as const, id: deal.id };
+
+ return (
+ <SimpleTableRow
+ key={deal.id}
+ clickable
+ onClick={() => openRecord(record)}
+ onFocus={() => prefetchRecord(record)}
+ onMouseEnter={() => prefetchRecord(record)}
+ >
+ <TableCell className="overflow-hidden px-3 py-3">
+ <span className="block truncate font-medium">
+ {deal.name}
+ </span>
+ </TableCell>
+ <TableCell className="overflow-hidden px-3 py-3">
+ <CompanyCell company={deal.company} />
+ </TableCell>
+ <TableCell className="overflow-hidden px-3 py-3">
+ <Stage stage={deal.stage} />
+ </TableCell>
+ <TableCell className="overflow-hidden px-3 py-3 text-right">
+ {deal.amount === null ? (
+ <EmptyCellValue />
+ ) : (
+ <span className="tabular-nums">
+ {formatMoney(
+ Math.round(deal.amount * 100),
+ deal.currency,
+ )}
+ </span>
+ )}
+ </TableCell>
+ <TableCell className="overflow-hidden px-3 py-3">
+ <OwnerCell owner={deal.owner} />
+ </TableCell>
+ <TableCell className="overflow-hidden px-3 py-3">
+ {deal.expectedCloseDate ? (
+ <span className="text-muted-foreground">
+ <LocalDay date={deal.expectedCloseDate} />
+ </span>
+ ) : (
+ <EmptyCellValue />
+ )}
+ </TableCell>
+ <TableCell
+ className="overflow-hidden px-3 py-3 text-right text-muted-foreground tabular-nums"
+ title={
+ deal.neverActive
+ ? "No activity has ever been recorded"
+ : undefined
+ }
+ >
+ {deal.daysSinceLastActivity}d
+ </TableCell>
+ </SimpleTableRow>
+ );
+ })
+ )}
+ </SimpleTable>
+ <div className="flex flex-wrap items-center justify-between gap-3 text-muted-foreground text-xs">
+ <span>{tableMeta(result)}</span>
+ <span>
+ As of <LocalDay date={result.asOf} />
+ </span>
+ </div>
+ </section>
+ );
+}
+
+function Stage({ stage }: { stage: string }) {
+ const option = DEAL_STAGE_OPTIONS.find(
+ (candidate) => candidate.value === stage,
+ );
+ return option ? (
+ <DealStageIndicator stage={option.value} />
+ ) : (
+ <span className="text-muted-foreground">{humaniseStage(stage)}</span>
+ );
+}
+
+function tableTitle(result: DealListResult): string {
+ const count = result.deals.length;
+ const status =
+ result.criteria.status === "all" ? "" : `${result.criteria.status} `;
+ const stale = result.criteria.inactiveForDays === null ? "" : "stale ";
+ return count === 0
+ ? "No matching deals"
+ : `${count} ${stale}${status}deal${count === 1 ? "" : "s"}`;
+}
+
+function tableMeta(result: DealListResult): string {
+ const details = [
+ `${result.deals.length} deal${result.deals.length === 1 ? "" : "s"}`,
+ pipelineTotal(result.deals),
+ result.criteria.inactiveForDays === null
+ ? null
+ : `${result.criteria.inactiveForDays}+ days inactive`,
+ result.hasMore ? "More results available" : null,
+ ].filter((detail): detail is string => Boolean(detail));
+
+ return details.join(" · ");
+}
+
+function humaniseStage(stage: string): string {
+ return stage
+ .toLowerCase()
+ .split("_")
+ .map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`)
+ .join(" ");
+}
+
+function pipelineTotal(deals: readonly DealListItem[]): string | null {
+ const currencies = new Set(deals.map((deal) => deal.currency));
+ if (currencies.size !== 1) return null;
+
+ const currency = currencies.values().next().value;
+ if (!currency) return null;
+
+ const amount = deals.reduce((sum, deal) => sum + (deal.amount ?? 0), 0);
+ return `${formatMoney(Math.round(amount * 100), currency)} pipeline`;
+}
diff --git a/apps/app/components/agent-builder/delete-chat-action.tsx b/apps/app/components/agent-builder/delete-chat-action.tsx
new file mode 100644
index 00000000..1af2ddb6
--- /dev/null
+++ b/apps/app/components/agent-builder/delete-chat-action.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+import Close from "@carbon/icons-react/es/Close";
+import OverflowMenuVertical from "@carbon/icons-react/es/OverflowMenuVertical";
+import TrashCan from "@carbon/icons-react/es/TrashCan";
+import {
+ AlertDialog,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@crm/ui/components/alert-dialog";
+import {
+ AsyncButtonContent,
+ useAsyncAction,
+} from "@crm/ui/components/async-action";
+import { Button } from "@crm/ui/components/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@crm/ui/components/dropdown-menu";
+import { Icon } from "@crm/ui/components/icon";
+import { useMutation } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import { useCrmCache } from "@/lib/trpc/cache";
+import { useTRPC } from "@/lib/trpc/client";
+import { useWorkspaceUrl } from "@/lib/use-workspace-url";
+
+export function DeleteChatAction({
+ conversationId,
+ title,
+ trigger,
+ className,
+ returnToChatList = false,
+ onDeleted,
+}: {
+ conversationId: string;
+ title: string;
+ trigger: "close" | "menu";
+ className?: string;
+ returnToChatList?: boolean;
+ onDeleted?: () => void;
+}) {
+ const trpc = useTRPC();
+ const cache = useCrmCache();
+ const router = useRouter();
+ const workspaceUrl = useWorkspaceUrl();
+ const [confirming, setConfirming] = useState(false);
+ const remove = useMutation(
+ trpc.conversations.remove.mutationOptions({
+ onSuccess: async () => {
+ await cache.conversationRemoved(conversationId);
+ setConfirming(false);
+ toast.success("Chat deleted.");
+ onDeleted?.();
+
+ if (returnToChatList) {
+ router.replace(workspaceUrl("/chat"));
+ }
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+ const removeAction = useAsyncAction({
+ action: () => remove.mutateAsync({ id: conversationId }),
+ });
+
+ return (
+ <>
+ {trigger === "close" ? (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ className={className}
+ disabled={removeAction.pending}
+ aria-label={`Delete ${title}`}
+ onClick={() => setConfirming(true)}
+ >
+ <Icon icon={Close} />
+ </Button>
+ ) : (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ disabled={removeAction.pending}
+ >
+ <Icon icon={OverflowMenuVertical} />
+ <span className="sr-only">More chat actions</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ variant="destructive"
+ onSelect={() => setConfirming(true)}
+ >
+ <Icon icon={TrashCan} />
+ Delete chat
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+
+ <AlertDialog
+ open={confirming}
+ onOpenChange={(open) => {
+ if (!removeAction.pending) setConfirming(open);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete {title}?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This permanently deletes the chat, its messages, attachments, and
+ shared link. Any agent created from it stays available.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={removeAction.pending}>
+ Cancel
+ </AlertDialogCancel>
+ <Button
+ variant="destructive"
+ disabled={removeAction.pending}
+ aria-busy={removeAction.pending}
+ onClick={() => removeAction.run()}
+ >
+ <AsyncButtonContent
+ status={removeAction.status}
+ pendingLabel="Deleting"
+ successLabel="Deleted"
+ errorLabel="Try again"
+ >
+ Delete chat
+ </AsyncButtonContent>
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
diff --git a/apps/app/components/agent-builder/share-chat-dialog.tsx b/apps/app/components/agent-builder/share-chat-dialog.tsx
new file mode 100644
index 00000000..53a2cddd
--- /dev/null
+++ b/apps/app/components/agent-builder/share-chat-dialog.tsx
@@ -0,0 +1,304 @@
+"use client";
+
+import Close from "@carbon/icons-react/es/Close";
+import Copy from "@carbon/icons-react/es/Copy";
+import {
+ AsyncButtonContent,
+ useAsyncAction,
+} from "@crm/ui/components/async-action";
+import { Button } from "@crm/ui/components/button";
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@crm/ui/components/dialog";
+import { Icon } from "@crm/ui/components/icon";
+import { cn } from "@crm/ui/lib/utils";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import { toast } from "sonner";
+import { useTRPC } from "@/lib/trpc/client";
+import { useWorkspaceUrl } from "@/lib/use-workspace-url";
+
+export function ShareChatDialog({
+ conversationId,
+ title,
+}: {
+ conversationId: string;
+ title: string;
+}) {
+ const trpc = useTRPC();
+ const workspaceUrl = useWorkspaceUrl();
+ const queryClient = useQueryClient();
+ const [open, setOpen] = useState(false);
+ const [choice, setChoice] = useState<{
+ conversationId: string;
+ value: boolean;
+ } | null>(null);
+ const [token, setToken] = useState<{
+ conversationId: string;
+ value: string;
+ } | null>(null);
+ const status = useQuery({
+ ...trpc.conversations.shareStatus.queryOptions({ id: conversationId }),
+ enabled: open,
+ });
+ const selectedChoice =
+ choice?.conversationId === conversationId ? choice.value : null;
+ const shareToken =
+ token?.conversationId === conversationId ? token.value : null;
+ const shared = status.isSuccess
+ ? (selectedChoice ?? status.data.enabled)
+ : null;
+
+ const invalidate = () =>
+ queryClient.invalidateQueries({
+ queryKey: trpc.conversations.shareStatus.pathKey(),
+ });
+
+ const create = useMutation(
+ trpc.conversations.createShare.mutationOptions({
+ onSuccess: async (result, input) => {
+ setToken({ conversationId: input.id, value: result.token });
+ setChoice({ conversationId: input.id, value: true });
+ await invalidate();
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+ const revoke = useMutation(
+ trpc.conversations.revokeShare.mutationOptions({
+ onSuccess: async (_result, input) => {
+ setToken(null);
+ setChoice({ conversationId: input.id, value: false });
+ await invalidate();
+ toast.success("Chat link revoked.");
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+
+ const copyLink = async () => {
+ if (!shareToken) return;
+ await navigator.clipboard.writeText(
+ `${window.location.origin}${workspaceUrl(`/chat/${shareToken}`)}`,
+ );
+ toast.success("Chat link copied.");
+ };
+ const createAction = useAsyncAction({
+ action: () => create.mutateAsync({ id: conversationId }),
+ onError: () => setChoice(null),
+ });
+ const revokeAction = useAsyncAction({
+ action: () => revoke.mutateAsync({ id: conversationId }),
+ });
+ const copyAction = useAsyncAction({ action: copyLink });
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ if (!next) setChoice(null);
+ }}
+ >
+ <DialogTrigger asChild>
+ <Button variant="outline" size="sm">
+ Share chat
+ </Button>
+ </DialogTrigger>
+ <DialogContent
+ showCloseButton={false}
+ className="w-[440px] max-w-[calc(100%-2rem)] gap-0 overflow-hidden p-0 sm:max-w-[440px]"
+ >
+ <DialogHeader className="relative gap-1 border-b p-5 pr-14">
+ <DialogTitle className="font-semibold text-sm">
+ Share chat
+ </DialogTitle>
+ <DialogDescription>{title}</DialogDescription>
+ <DialogClose asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="absolute top-4 right-4"
+ >
+ <Icon icon={Close} />
+ <span className="sr-only">Close</span>
+ </Button>
+ </DialogClose>
+ </DialogHeader>
+
+ <div className="flex flex-col gap-2.5 p-5">
+ {status.isPending ? (
+ <p
+ role="status"
+ className="py-6 text-center text-muted-foreground text-sm"
+ >
+ Loading sharing status…
+ </p>
+ ) : status.isError ? (
+ <div
+ role="alert"
+ className="flex items-center justify-between gap-3 py-4"
+ >
+ <p className="text-muted-foreground text-sm">
+ Sharing status could not be loaded.
+ </p>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => status.refetch()}
+ >
+ Try again
+ </Button>
+ </div>
+ ) : (
+ <>
+ <ShareChoice
+ selected={shared === false}
+ label="Only you"
+ disabled={createAction.pending || revokeAction.pending}
+ onSelect={() => {
+ if (shared || status.data.enabled) {
+ revokeAction.run();
+ } else {
+ setChoice({ conversationId, value: false });
+ }
+ }}
+ />
+ <ShareChoice
+ selected={shared === true}
+ label="Anyone in Comp AI with the link"
+ detail="Read-only"
+ disabled={createAction.pending || revokeAction.pending}
+ onSelect={() => {
+ if (!shareToken) createAction.run();
+ setChoice({ conversationId, value: true });
+ }}
+ />
+
+ {shared === true ? (
+ <div className="flex h-9 items-center gap-3 rounded-md border bg-background py-[3px] pr-[3px] pl-4">
+ <span className="min-w-0 flex-1 truncate font-mono text-xs">
+ {shareToken
+ ? `${workspaceUrl(`/chat/${shareToken.slice(0, 12)}`)}…`
+ : "An active read-only link exists"}
+ </span>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ if (shareToken) {
+ copyAction.run();
+ } else {
+ createAction.run();
+ }
+ }}
+ disabled={createAction.pending || copyAction.pending}
+ aria-busy={createAction.pending || copyAction.pending}
+ >
+ <AsyncButtonContent
+ status={
+ shareToken ? copyAction.status : createAction.status
+ }
+ pendingLabel={shareToken ? "Copying" : "Creating link"}
+ successLabel={shareToken ? "Copied" : "Link created"}
+ errorLabel="Try again"
+ >
+ {shareToken ? (
+ <Icon icon={Copy} data-icon="inline-start" />
+ ) : null}
+ {shareToken ? "Copy link" : "Replace link"}
+ </AsyncButtonContent>
+ </Button>
+ </div>
+ ) : null}
+
+ <p className="text-muted-foreground text-xs">
+ Sharing this chat does not change who can edit or run the agent.
+ </p>
+ </>
+ )}
+ </div>
+
+ <DialogFooter className="flex-row items-center justify-between border-t p-4 px-5">
+ <Button
+ variant="ghost"
+ onClick={() => revokeAction.run()}
+ disabled={shared !== true || revokeAction.pending}
+ aria-busy={revokeAction.pending}
+ >
+ <AsyncButtonContent
+ status={revokeAction.status}
+ pendingLabel="Revoking"
+ successLabel="Revoked"
+ errorLabel="Try again"
+ >
+ Revoke link
+ </AsyncButtonContent>
+ </Button>
+ <div className="flex gap-3">
+ <DialogClose asChild>
+ <Button variant="outline">Cancel</Button>
+ </DialogClose>
+ <DialogClose asChild>
+ <Button>Done</Button>
+ </DialogClose>
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function ShareChoice({
+ selected,
+ label,
+ detail,
+ disabled = false,
+ onSelect,
+}: {
+ selected: boolean;
+ label: string;
+ detail?: string;
+ disabled?: boolean;
+ onSelect: () => void;
+}) {
+ return (
+ <label
+ className={cn(
+ "flex h-12 w-full cursor-pointer items-center gap-2.5 rounded-md border px-2.5 text-left outline-none focus-within:ring-2 focus-within:ring-ring/60",
+ selected && "border-muted-foreground/60 bg-muted",
+ disabled && "cursor-not-allowed opacity-50",
+ )}
+ >
+ <input
+ type="radio"
+ name="chat-sharing"
+ checked={selected}
+ disabled={disabled}
+ onChange={onSelect}
+ className="sr-only"
+ />
+ <span
+ className={cn(
+ "flex size-3.5 shrink-0 items-center justify-center rounded-full border border-muted-foreground",
+ selected && "border-ring",
+ )}
+ >
+ {selected ? <span className="size-2 rounded-full bg-ring" /> : null}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block font-medium text-sm">{label}</span>
+ {detail ? (
+ <span className="block text-muted-foreground text-xs">{detail}</span>
+ ) : null}
+ </span>
+ </label>
+ );
+}
diff --git a/apps/app/components/agent-builder/team-agent-detail.tsx b/apps/app/components/agent-builder/team-agent-detail.tsx
new file mode 100644
index 00000000..5f168d8c
--- /dev/null
+++ b/apps/app/components/agent-builder/team-agent-detail.tsx
@@ -0,0 +1,837 @@
+"use client";
+
+import ChevronDown from "@carbon/icons-react/es/ChevronDown";
+import ChevronUp from "@carbon/icons-react/es/ChevronUp";
+import Download from "@carbon/icons-react/es/Download";
+import OverflowMenuVertical from "@carbon/icons-react/es/OverflowMenuVertical";
+import Pause from "@carbon/icons-react/es/Pause";
+import Play from "@carbon/icons-react/es/Play";
+import TrashCan from "@carbon/icons-react/es/TrashCan";
+import {
+ AlertDialog,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@crm/ui/components/alert-dialog";
+import {
+ AsyncButtonContent,
+ useAsyncAction,
+} from "@crm/ui/components/async-action";
+import { Button } from "@crm/ui/components/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@crm/ui/components/dropdown-menu";
+import { Icon } from "@crm/ui/components/icon";
+import { Skeleton } from "@crm/ui/components/skeleton";
+import { cn } from "@crm/ui/lib/utils";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { toast } from "sonner";
+import {
+ PageShell,
+ PageShellActions,
+ PageShellContent,
+ PageShellDescription,
+ PageShellHeader,
+ PageShellHeading,
+ PageShellTitle,
+} from "@/components/page-shell";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+import { useWorkspaceUrl } from "@/lib/use-workspace-url";
+
+type AgentTab = "overview" | "runs" | "activity";
+type AgentDetail = RouterOutputs["agents"]["byId"];
+type Runs = RouterOutputs["agents"]["history"];
+type Activity = RouterOutputs["agents"]["activity"];
+type RunRow = Omit<Runs[number], "events"> & {
+ events: Array<{
+ id: string;
+ type: string;
+ data: unknown;
+ emittedAt: string;
+ }>;
+};
+type ActivityRow = Omit<Activity[number], "before" | "after"> & {
+ before: unknown;
+ after: unknown;
+};
+const DATE_FORMATTER = new Intl.DateTimeFormat("en-US", {
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ second: "2-digit",
+ timeZone: "UTC",
+ timeZoneName: "short",
+});
+const TIME_FORMATTER = new Intl.DateTimeFormat("en-US", {
+ hour: "2-digit",
+ minute: "2-digit",
+ second: "2-digit",
+ hour12: false,
+ timeZone: "UTC",
+});
+
+export function TeamAgentDetail({
+ agentId,
+ initialAgent,
+ initialRuns,
+ initialActivity,
+}: {
+ agentId: string;
+ initialAgent: AgentDetail;
+ initialRuns: Runs;
+ initialActivity: Activity;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const [tab, setTab] = useState<AgentTab>("runs");
+ const agent = useQuery({
+ ...trpc.agents.byId.queryOptions({ id: agentId }),
+ initialData: initialAgent,
+ });
+ const runs = useQuery({
+ ...trpc.agents.history.queryOptions({ id: agentId, limit: 50 }),
+ initialData: initialRuns,
+ refetchInterval: (query) =>
+ query.state.data?.some((run) =>
+ ["QUEUED", "RUNNING", "WAITING_FOR_APPROVAL"].includes(run.status),
+ )
+ ? 2500
+ : false,
+ });
+ const activity = useQuery({
+ ...trpc.agents.activity.queryOptions({ id: agentId, limit: 100 }),
+ initialData: initialActivity,
+ });
+ const invalidate = () =>
+ Promise.all([
+ queryClient.invalidateQueries({ queryKey: trpc.agents.byId.pathKey() }),
+ queryClient.invalidateQueries({ queryKey: trpc.agents.list.pathKey() }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.agents.activity.pathKey(),
+ }),
+ ]);
+ const runNow = useMutation(
+ trpc.agents.runNow.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ invalidate(),
+ queryClient.invalidateQueries({
+ queryKey: trpc.agents.history.pathKey(),
+ }),
+ ]);
+ setTab("runs");
+ toast.success("Agent run queued.");
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+ const pause = useMutation(
+ trpc.agents.pause.mutationOptions({
+ onSuccess: invalidate,
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+ const resume = useMutation(
+ trpc.agents.resume.mutationOptions({
+ onSuccess: invalidate,
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+ const runAction = useAsyncAction({
+ action: () =>
+ runNow.mutateAsync({
+ id: agentId,
+ clientRequestId: crypto.randomUUID(),
+ }),
+ });
+ const pauseAction = useAsyncAction({
+ action: () => pause.mutateAsync({ id: agentId }),
+ });
+ const resumeAction = useAsyncAction({
+ action: () => resume.mutateAsync({ id: agentId }),
+ });
+
+ if (agent.isPending) {
+ return (
+ <PageShell className="min-h-0" aria-busy="true">
+ <PageShellHeader>
+ <PageShellHeading>
+ <Skeleton className="h-8 w-72 max-w-full" />
+ <Skeleton className="h-4 w-[520px] max-w-full" />
+ </PageShellHeading>
+ </PageShellHeader>
+ <PageShellContent>
+ <Skeleton className="h-9 w-full" />
+ <Skeleton className="h-56 w-full" />
+ </PageShellContent>
+ <span role="status" className="sr-only">
+ Loading agent
+ </span>
+ </PageShell>
+ );
+ }
+
+ if (agent.isError) {
+ return (
+ <PageShell>
+ <PageShellHeader>
+ <PageShellHeading>
+ <PageShellTitle>Agent unavailable</PageShellTitle>
+ <PageShellDescription>{agent.error.message}</PageShellDescription>
+ </PageShellHeading>
+ </PageShellHeader>
+ </PageShell>
+ );
+ }
+
+ const data = agent.data;
+ const nextRun = data.triggers.find((trigger) => trigger.enabled)?.nextRunAt;
+
+ return (
+ <PageShell className="min-h-0">
+ <PageShellHeader className="[&>div]:grid-cols-1 sm:[&>div]:grid-cols-[minmax(0,1fr)_auto]">
+ <PageShellHeading>
+ <PageShellTitle className="wrap-break-word">
+ {data.name}
+ </PageShellTitle>
+ <PageShellDescription className="wrap-break-word leading-6">
+ <span className="block">
+ {data.description ?? "A durable team automation."}
+ </span>
+ <span className="mt-2 block text-xs">
+ Created by {data.createdBy.name} · Team agent · Version{" "}
+ {data.currentVersion?.number ?? "—"}
+ </span>
+ </PageShellDescription>
+ </PageShellHeading>
+ <PageShellActions className="col-start-1 row-start-3 justify-self-start sm:col-start-2 sm:row-start-1 sm:justify-self-end">
+ <div className="flex min-w-0 flex-col items-start gap-2 sm:items-end">
+ <span className="text-muted-foreground text-xs">Next run</span>
+ <span className="font-mono text-sm">
+ {nextRun ? formatDate(nextRun) : "Manual only"}
+ </span>
+ <div className="mt-1 flex flex-wrap gap-2">
+ <Button
+ variant="outline"
+ disabled={data.status !== "LIVE" || runAction.pending}
+ aria-busy={runAction.pending}
+ onClick={() => runAction.run()}
+ >
+ <AsyncButtonContent
+ status={runAction.status}
+ pendingLabel="Queueing"
+ successLabel="Queued"
+ errorLabel="Try again"
+ >
+ <Icon icon={Play} data-icon="inline-start" />
+ Run now
+ </AsyncButtonContent>
+ </Button>
+ {data.canManage && data.status === "LIVE" ? (
+ <Button
+ variant="outline"
+ disabled={pauseAction.pending}
+ aria-busy={pauseAction.pending}
+ onClick={() => pauseAction.run()}
+ >
+ <AsyncButtonContent
+ status={pauseAction.status}
+ pendingLabel="Pausing"
+ successLabel="Paused"
+ errorLabel="Try again"
+ >
+ <Icon icon={Pause} data-icon="inline-start" />
+ Pause
+ </AsyncButtonContent>
+ </Button>
+ ) : null}
+ {data.canManage && data.status === "PAUSED" ? (
+ <Button
+ variant="outline"
+ disabled={resumeAction.pending}
+ aria-busy={resumeAction.pending}
+ onClick={() => resumeAction.run()}
+ >
+ <AsyncButtonContent
+ status={resumeAction.status}
+ pendingLabel="Resuming"
+ successLabel="Resumed"
+ errorLabel="Try again"
+ >
+ <Icon icon={Play} data-icon="inline-start" />
+ Resume
+ </AsyncButtonContent>
+ </Button>
+ ) : null}
+ {data.canManage ? (
+ <DeleteAgentAction agentId={data.id} name={data.name} />
+ ) : null}
+ </div>
+ </div>
+ </PageShellActions>
+ </PageShellHeader>
+
+ <PageShellContent className="min-h-0">
+ <div
+ role="tablist"
+ aria-label="Agent details"
+ className="flex h-9 min-w-0 items-end gap-5 overflow-x-auto border-b sm:gap-6"
+ >
+ <TabButton
+ tab="overview"
+ active={tab === "overview"}
+ onClick={() => setTab("overview")}
+ >
+ Overview
+ </TabButton>
+ <TabButton
+ tab="runs"
+ active={tab === "runs"}
+ onClick={() => setTab("runs")}
+ >
+ Runs{" "}
+ <span className="font-mono text-muted-foreground">
+ {data.runCount}
+ </span>
+ </TabButton>
+ <TabButton
+ tab="activity"
+ active={tab === "activity"}
+ onClick={() => setTab("activity")}
+ >
+ Activity{" "}
+ <span className="font-mono text-muted-foreground">
+ {activity.data?.length ?? 0}
+ </span>
+ </TabButton>
+ </div>
+
+ {tab === "overview" ? (
+ <div
+ role="tabpanel"
+ id="agent-overview-panel"
+ aria-labelledby="agent-overview-tab"
+ >
+ <AgentOverview agent={data} />
+ </div>
+ ) : null}
+ {tab === "runs" ? (
+ <div
+ role="tabpanel"
+ id="agent-runs-panel"
+ aria-labelledby="agent-runs-tab"
+ >
+ <AgentRuns runs={runs.data ?? []} />
+ </div>
+ ) : null}
+ {tab === "activity" ? (
+ <div
+ role="tabpanel"
+ id="agent-activity-panel"
+ aria-labelledby="agent-activity-tab"
+ >
+ <AgentActivity activity={activity.data ?? []} />
+ </div>
+ ) : null}
+ </PageShellContent>
+ </PageShell>
+ );
+}
+
+function DeleteAgentAction({
+ agentId,
+ name,
+}: {
+ agentId: string;
+ name: string;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const router = useRouter();
+ const workspaceUrl = useWorkspaceUrl();
+ const [confirming, setConfirming] = useState(false);
+ const remove = useMutation(
+ trpc.agents.remove.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.agents.list.pathKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.agents.byId.pathKey(),
+ refetchType: "none",
+ }),
+ ]);
+ setConfirming(false);
+ toast.success(`${name} was deleted.`);
+ router.replace(workspaceUrl("/agents"));
+ },
+ onError: (error) => toast.error(error.message),
+ }),
+ );
+ const removeAction = useAsyncAction({
+ action: () => remove.mutateAsync({ id: agentId }),
+ });
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ disabled={removeAction.pending}
+ >
+ <Icon icon={OverflowMenuVertical} />
+ <span className="sr-only">More agent actions</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ variant="destructive"
+ onSelect={() => setConfirming(true)}
+ >
+ <Icon icon={TrashCan} />
+ Delete agent
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <AlertDialog
+ open={confirming}
+ onOpenChange={(open) => {
+ if (!removeAction.pending) setConfirming(open);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete {name}?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This removes it from the team agent list, disables its triggers,
+ and cancels queued runs. Its run and action history stays in the
+ audit log. A run already in progress may finish.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={removeAction.pending}>
+ Cancel
+ </AlertDialogCancel>
+ <Button
+ variant="destructive"
+ disabled={removeAction.pending}
+ aria-busy={removeAction.pending}
+ onClick={() => removeAction.run()}
+ >
+ <AsyncButtonContent
+ status={removeAction.status}
+ pendingLabel="Deleting"
+ successLabel="Deleted"
+ errorLabel="Try again"
+ >
+ Delete agent
+ </AsyncButtonContent>
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+}
+
+function TabButton({
+ tab,
+ active,
+ onClick,
+ children,
+}: {
+ tab: AgentTab;
+ active: boolean;
+ onClick: () => void;
+ children: React.ReactNode;
+}) {
+ return (
+ <button
+ id={`agent-${tab}-tab`}
+ type="button"
+ role="tab"
+ aria-selected={active}
+ aria-controls={`agent-${tab}-panel`}
+ onClick={onClick}
+ className={cn(
+ "flex h-8 items-center gap-2 border-b-2 border-transparent text-muted-foreground text-sm outline-none hover:text-foreground focus-visible:text-foreground",
+ active && "border-ring font-medium text-foreground",
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+function AgentOverview({ agent }: { agent: AgentDetail }) {
+ const version = agent.currentVersion as {
+ manifest: unknown;
+ sandboxPolicy: unknown;
+ modelId: string;
+ } | null;
+ const manifest = recordOf(version?.manifest);
+ const sandbox = recordOf(version?.sandboxPolicy);
+
+ return (
+ <div className="overflow-hidden rounded-lg border bg-card">
+ <DetailRow label="Status" value={agent.status} />
+ <DetailRow label="Model" value={version?.modelId ?? "—"} />
+ <DetailRow
+ label="Execution"
+ value={textOf(
+ sandbox.summary,
+ "Isolated sandbox · deny-all network · bounded CRM tools",
+ )}
+ />
+ <DetailRow
+ label="Scope"
+ value={textOf(
+ recordOf(manifest.dataScope).summary,
+ "Bounded CRM access",
+ )}
+ />
+ <DetailRow
+ label="Triggers"
+ value={
+ agent.triggers.map((trigger) => trigger.name).join(" · ") ||
+ "Manual only"
+ }
+ />
+ </div>
+ );
+}
+
+function DetailRow({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="flex min-h-11 flex-col items-start gap-1 border-t px-4 py-3 first:border-t-0 sm:flex-row sm:items-center sm:gap-5 sm:px-5 sm:py-2">
+ <span className="text-muted-foreground text-xs sm:w-36 sm:shrink-0">
+ {label}
+ </span>
+ <span className="min-w-0 max-w-full flex-1 wrap-break-word text-sm">
+ {value}
+ </span>
+ </div>
+ );
+}
+
+function AgentRuns({ runs }: { runs: Runs }) {
+ const [outcome, setOutcome] = useState("ALL");
+ const [expanded, setExpanded] = useState<string | null>(null);
+ const visible = runs.filter(
+ (run) => outcome === "ALL" || run.status === outcome,
+ );
+ const runNumbers = new Map(
+ runs.map((run, index) => [run.id, runs.length - index]),
+ );
+
+ return (
+ <div className="flex min-w-0 flex-col gap-4 sm:gap-6">
+ <div className="flex min-h-7 items-center justify-start sm:justify-end">
+ <select
+ value={outcome}
+ onChange={(event) => setOutcome(event.target.value)}
+ aria-label="Filter run outcomes"
+ className="h-7 rounded-md border bg-muted px-2.5 font-medium text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring/60"
+ >
+ <option value="ALL">All outcomes</option>
+ <option value="SUCCEEDED">Succeeded</option>
+ <option value="FAILED">Failed</option>
+ <option value="RUNNING">Running</option>
+ <option value="QUEUED">Queued</option>
+ <option value="WAITING_FOR_APPROVAL">Waiting for approval</option>
+ <option value="CANCELLED">Cancelled</option>
+ </select>
+ </div>
+
+ {visible.map((run) => (
+ <div
+ key={run.id}
+ className="min-w-0 overflow-hidden rounded-lg border bg-card"
+ >
+ <button
+ type="button"
+ onClick={() =>
+ setExpanded((current) => (current === run.id ? null : run.id))
+ }
+ className="flex min-h-14 w-full min-w-0 flex-col items-stretch gap-3 px-4 py-3 text-left outline-none hover:bg-muted/40 focus-visible:bg-muted/40 sm:flex-row sm:items-center sm:justify-between sm:gap-5 sm:px-5 sm:py-2"
+ >
+ <span className="min-w-0 flex-1">
+ <span className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <span className="font-semibold text-sm">
+ Run #{String(runNumbers.get(run.id)).padStart(3, "0")}
+ </span>
+ <span
+ className={cn(
+ "text-muted-foreground text-xs",
+ run.status === "FAILED" && "text-destructive",
+ )}
+ >
+ {humanStatus(run.status)}
+ </span>
+ </span>
+ <span className="mt-1 block wrap-break-word font-mono text-muted-foreground text-xs leading-5 sm:mt-0">
+ {humanStatus(run.triggerType)} · {formatDate(run.createdAt)} ·
+ Version {run.version.number}
+ </span>
+ </span>
+ <span className="flex min-w-0 items-center justify-between gap-3 font-mono text-muted-foreground text-xs sm:shrink-0 sm:justify-start sm:gap-4">
+ <span>{duration(run.startedAt, run.finishedAt)}</span>
+ <span>
+ {run.actions.length} external{" "}
+ {run.actions.length === 1 ? "action" : "actions"}
+ </span>
+ <Icon
+ icon={expanded === run.id ? ChevronUp : ChevronDown}
+ className="size-3.5"
+ />
+ </span>
+ </button>
+
+ {expanded === run.id ? (
+ <ExpandedRun run={run as unknown as RunRow} />
+ ) : null}
+ </div>
+ ))}
+
+ {visible.length === 0 ? (
+ <p className="py-12 text-center text-muted-foreground text-sm">
+ No runs match this outcome.
+ </p>
+ ) : null}
+ </div>
+ );
+}
+
+function ExpandedRun({ run }: { run: RunRow }) {
+ const events = run.events.filter(
+ (event) => event.type !== "message.appended",
+ );
+ const condensedEvents = run.events.length - events.length;
+
+ return (
+ <div className="min-w-0 border-t">
+ <div className="grid grid-cols-2 gap-x-4 gap-y-3 border-b bg-background px-4 py-3 sm:min-h-[58px] sm:grid-cols-4 sm:items-center sm:gap-0 sm:px-5 sm:py-2">
+ <RunMeta label="Trigger" value={humanStatus(run.triggerType)} />
+ <RunMeta
+ label="Initiated by"
+ value={run.initiatedBy?.name ?? "Eve scheduler"}
+ />
+ <RunMeta label="Model" value={run.modelId ?? "Gateway default"} />
+ <RunMeta label="Version" value={String(run.version.number)} last />
+ </div>
+
+ <div>
+ {events.map((event) => (
+ <div
+ key={event.id}
+ className="grid min-h-8 min-w-0 grid-cols-[68px_minmax(0,1fr)] items-start gap-x-3 border-t px-4 py-2 first:border-t-0 sm:flex sm:items-center sm:gap-5 sm:px-5 sm:py-1.5"
+ >
+ <span className="shrink-0 font-mono text-muted-foreground text-xs sm:w-[78px]">
+ {formatTime(event.emittedAt)}
+ </span>
+ <span className="min-w-0 flex-1 wrap-break-word text-sm">
+ {eventLabel(event.type, event.data)}
+ </span>
+ <span className="hidden shrink-0 font-mono text-muted-foreground text-xs sm:inline">
+ event
+ </span>
+ </div>
+ ))}
+ {run.actions.map((action) => (
+ <div
+ key={action.id}
+ className="grid min-h-12 min-w-0 grid-cols-[68px_minmax(0,1fr)] items-start gap-x-3 gap-y-1 border-t px-4 py-3 sm:flex sm:gap-5 sm:px-5"
+ >
+ <span className="shrink-0 font-mono text-muted-foreground text-xs sm:w-[78px]">
+ {formatTime(
+ action.completedAt ?? action.startedAt ?? action.plannedAt,
+ )}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block wrap-break-word text-sm">
+ {action.summary}
+ </span>
+ <span className="block wrap-break-word text-muted-foreground text-xs">
+ {action.provider} · {humanStatus(action.status)}
+ {action.targetLabel ? ` · ${action.targetLabel}` : ""}
+ </span>
+ </span>
+ <span className="col-start-2 min-w-0 wrap-break-word font-mono text-muted-foreground text-xs sm:col-auto sm:shrink-0">
+ {action.externalId ?? action.id.slice(0, 12)}
+ </span>
+ </div>
+ ))}
+ {condensedEvents > 0 ? (
+ <div className="flex min-h-9 items-center border-t px-4 py-2 text-muted-foreground text-xs sm:px-5">
+ {condensedEvents} streaming{" "}
+ {condensedEvents === 1 ? "update" : "updates"} condensed
+ </div>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+function RunMeta({
+ label,
+ value,
+ last = false,
+}: {
+ label: string;
+ value: string;
+ last?: boolean;
+}) {
+ return (
+ <span
+ className={cn(
+ "flex min-w-0 flex-col gap-0.5 sm:flex-1",
+ last && "sm:max-w-44",
+ )}
+ >
+ <span className="text-muted-foreground text-xs">{label}</span>
+ <span className="wrap-break-word text-sm sm:truncate">{value}</span>
+ </span>
+ );
+}
+
+function AgentActivity({ activity }: { activity: Activity }) {
+ const [kind, setKind] = useState("ALL");
+ const rows = activity as unknown as ActivityRow[];
+ const visible = rows.filter(
+ (event) => kind === "ALL" || event.type.startsWith(kind),
+ );
+
+ return (
+ <div className="flex min-w-0 flex-col gap-4 sm:gap-6">
+ <div className="flex min-h-7 flex-wrap items-center justify-start gap-2 sm:justify-end sm:gap-3">
+ <select
+ value={kind}
+ onChange={(event) => setKind(event.target.value)}
+ aria-label="Filter activity"
+ className="h-7 rounded-md border bg-muted px-2.5 font-medium text-xs outline-none focus-visible:ring-2 focus-visible:ring-ring/60"
+ >
+ <option value="ALL">All changes</option>
+ <option value="agent.">Agent changes</option>
+ <option value="run.">Run requests</option>
+ </select>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => exportJson("agent-activity.json", visible)}
+ >
+ <Icon icon={Download} data-icon="inline-start" />
+ Export
+ </Button>
+ </div>
+
+ <div className="min-w-0 overflow-hidden rounded-lg border bg-card">
+ <div className="hidden h-9 items-center border-b bg-background px-5 text-muted-foreground text-xs sm:flex">
+ <span className="w-[166px] shrink-0">Time</span>
+ <span className="min-w-0 flex-1">Change</span>
+ <span className="w-[140px] shrink-0">Actor</span>
+ <span className="w-[118px] shrink-0 text-right">Request</span>
+ </div>
+ {visible.map((event) => (
+ <div
+ key={event.id}
+ className="flex min-h-11 min-w-0 flex-col items-start gap-2 border-t px-4 py-3 first:border-t-0 sm:flex-row sm:items-center sm:gap-0 sm:px-5"
+ >
+ <span className="shrink-0 font-mono text-muted-foreground text-xs sm:w-[166px]">
+ {formatDate(event.emittedAt)}
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block wrap-break-word text-sm">
+ {event.summary}
+ </span>
+ {changeDetail(event.before, event.after) ? (
+ <span className="block max-w-full whitespace-pre-wrap wrap-break-word font-mono text-muted-foreground text-xs">
+ {changeDetail(event.before, event.after)}
+ </span>
+ ) : null}
+ </span>
+ <span className="min-w-0 wrap-break-word text-xs sm:w-[140px] sm:shrink-0 sm:text-sm">
+ <span className="text-muted-foreground sm:hidden">Actor · </span>
+ {event.actorUser?.name ?? event.actorId ?? event.actorType}
+ </span>
+ <span className="min-w-0 wrap-break-word font-mono text-muted-foreground text-xs sm:w-[118px] sm:shrink-0 sm:text-right">
+ <span className="font-sans sm:hidden">Request · </span>
+ {event.requestId?.slice(0, 12) ?? "—"}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
+
+function textOf(value: unknown, fallback: string): string {
+ return typeof value === "string" && value.trim() ? value : fallback;
+}
+
+function humanStatus(value: string): string {
+ return value
+ .toLowerCase()
+ .replace(/_/g, " ")
+ .replace(/^./, (character) => character.toUpperCase());
+}
+
+function formatDate(value: string): string {
+ return DATE_FORMATTER.format(new Date(value));
+}
+
+function formatTime(value: string): string {
+ return TIME_FORMATTER.format(new Date(value));
+}
+
+function duration(startedAt: string | null, finishedAt: string | null): string {
+ if (!startedAt) return "—";
+ if (!finishedAt) return "In progress";
+
+ const milliseconds =
+ new Date(finishedAt).getTime() - new Date(startedAt).getTime();
+ return `${Math.max(0, milliseconds / 1000).toFixed(1)}s`;
+}
+
+function eventLabel(type: string, data: unknown): string {
+ const payload = recordOf(data);
+ return textOf(payload.summary, humanStatus(type.replace(/\./g, " ")));
+}
+
+function changeDetail(before: unknown, after: unknown): string | null {
+ if (!before && !after) return null;
+ const previous = JSON.stringify(before);
+ const next = JSON.stringify(after);
+ return previous && next ? `${previous} → ${next}` : next || previous;
+}
+
+function exportJson(name: string, value: unknown) {
+ const url = URL.createObjectURL(
+ new Blob([JSON.stringify(value, null, 2)], { type: "application/json" }),
+ );
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = name;
+ anchor.click();
+ URL.revokeObjectURL(url);
+}
diff --git a/apps/app/components/agent-builder/team-agents-index.tsx b/apps/app/components/agent-builder/team-agents-index.tsx
new file mode 100644
index 00000000..ac9572e9
--- /dev/null
+++ b/apps/app/components/agent-builder/team-agents-index.tsx
@@ -0,0 +1,111 @@
+"use client";
+
+import ArrowRight from "@carbon/icons-react/es/ArrowRight";
+import Bot from "@carbon/icons-react/es/Bot";
+import { Icon } from "@crm/ui/components/icon";
+import { Skeleton } from "@crm/ui/components/skeleton";
+import { useQuery } from "@tanstack/react-query";
+import Link from "next/link";
+import { useTRPC } from "@/lib/trpc/client";
+import type { RouterOutputs } from "@/lib/trpc/types";
+import { useWorkspaceUrl } from "@/lib/use-workspace-url";
+
+type Agents = RouterOutputs["agents"]["list"];
+
+export function TeamAgentsIndex({ initialAgents }: { initialAgents: Agents }) {
+ const trpc = useTRPC();
+ const workspaceUrl = useWorkspaceUrl();
+ const agents = useQuery({
+ ...trpc.agents.list.queryOptions(),
+ initialData: initialAgents,
+ });
+ const rows = agents.data;
+
+ return (
+ <>
+ {rows === undefined ? (
+ <AgentListFallback />
+ ) : rows.length ? (
+ <div className="overflow-hidden rounded-lg border bg-card">
+ {rows.map((agent) => (
+ <Link
+ key={agent.id}
+ href={workspaceUrl(`/agents/${agent.id}`)}
+ transitionTypes={["nav-forward"]}
+ className="flex min-h-16 min-w-0 items-start gap-3 border-t px-4 py-4 outline-none first:border-t-0 hover:bg-muted/50 focus-visible:bg-muted/50 sm:items-center sm:gap-4 sm:px-5 sm:py-3"
+ >
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">
+ <Icon icon={Bot} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
+ <span className="min-w-0 wrap-break-word font-medium text-sm sm:truncate">
+ {agent.name}
+ </span>
+ <span className="shrink-0 text-muted-foreground text-xs">
+ {agent.status.toLowerCase()}
+ </span>
+ </span>
+ <span className="mt-1 block wrap-break-word text-muted-foreground text-xs sm:mt-0 sm:truncate">
+ {agent.description ?? "No description"}
+ </span>
+ <span className="mt-2 block font-mono text-muted-foreground text-xs sm:hidden">
+ {agent.runCount} runs
+ </span>
+ </span>
+ <span className="hidden shrink-0 font-mono text-muted-foreground text-xs sm:inline">
+ {agent.runCount} runs
+ </span>
+ <Icon
+ icon={ArrowRight}
+ className="size-4 text-muted-foreground"
+ />
+ </Link>
+ ))}
+ </div>
+ ) : (
+ <div className="flex min-h-64 flex-col items-center justify-center rounded-lg border border-dashed px-6 text-center">
+ <Icon icon={Bot} className="size-6 text-muted-foreground" />
+ <h2 className="mt-4 font-medium text-sm">No team agents yet</h2>
+ <p className="mt-1 text-muted-foreground text-xs">
+ Create one from a private chat, then review its access before
+ deploying it.
+ </p>
+ <Link
+ href={workspaceUrl("/chat")}
+ className="mt-4 text-primary text-xs hover:underline"
+ >
+ Open chat
+ </Link>
+ </div>
+ )}
+ </>
+ );
+}
+
+function AgentListFallback() {
+ return (
+ <>
+ <div
+ className="overflow-hidden rounded-lg border bg-card"
+ aria-hidden="true"
+ >
+ {[0, 1].map((row) => (
+ <div
+ key={row}
+ className="flex min-h-16 items-center gap-4 border-t px-4 py-3 first:border-t-0 sm:px-5"
+ >
+ <Skeleton className="size-8 shrink-0 rounded-md" />
+ <span className="min-w-0 flex-1 space-y-2">
+ <Skeleton className="h-3 w-32 max-w-full" />
+ <Skeleton className="h-2.5 w-full max-w-96" />
+ </span>
+ </div>
+ ))}
+ </div>
+ <span role="status" className="sr-only">
+ Loading team agents
+ </span>
+ </>
+ );
+}
diff --git a/apps/app/components/agent-clarification-composer.tsx b/apps/app/components/agent-clarification-composer.tsx
new file mode 100644
index 00000000..81f14811
--- /dev/null
+++ b/apps/app/components/agent-clarification-composer.tsx
@@ -0,0 +1,135 @@
+"use client";
+
+import { AsyncButtonContent } from "@crm/ui/components/async-action";
+import {
+ Questionnaire,
+ QuestionnaireActions,
+ QuestionnaireChoice,
+ QuestionnaireChoices,
+ QuestionnaireDescription,
+ QuestionnaireError,
+ QuestionnaireInput,
+ QuestionnaireItem,
+ QuestionnaireSubmit,
+ QuestionnaireTitle,
+} from "@crm/ui/components/questionnaire";
+import type { EveMessageInputRequest } from "eve/react";
+import { type FormEvent, useState } from "react";
+import { AGENT_COMPOSER_CLASS_NAME } from "./agent-composer-frame";
+
+const OPTION_VALUE_PREFIX = "option:";
+
+export type ClarificationResponse =
+ | { requestId: string; optionId: string; text?: never }
+ | { requestId: string; optionId?: never; text: string };
+
+export function AgentClarificationComposer({
+ question,
+ pending,
+ onSubmit,
+}: {
+ question: EveMessageInputRequest;
+ pending: boolean;
+ onSubmit: (response: ClarificationResponse) => Promise<void>;
+}) {
+ const options = question.options ?? [];
+ const [transportError, setTransportError] = useState<string | null>(null);
+ const showFreeform =
+ question.display === "text" ||
+ question.allowFreeform === true ||
+ options.length === 0;
+ const items = [
+ {
+ name: "response",
+ required: true,
+ choices: options.map((option) => ({
+ disabled: pending,
+ value: `${OPTION_VALUE_PREFIX}${option.id}`,
+ })),
+ },
+ ];
+
+ const submit = async (event: FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+ if (pending) return;
+ const value = String(
+ new FormData(event.currentTarget).get("response") ?? "",
+ ).trim();
+ if (!value) return;
+ const optionId = value.startsWith(OPTION_VALUE_PREFIX)
+ ? value.slice(OPTION_VALUE_PREFIX.length)
+ : null;
+ const selectedOption = options.find((option) => option.id === optionId);
+ setTransportError(null);
+ try {
+ const response = (
+ selectedOption
+ ? { requestId: question.requestId, optionId: selectedOption.id }
+ : { requestId: question.requestId, text: value }
+ ) satisfies ClarificationResponse;
+ await onSubmit(response);
+ } catch {
+ setTransportError(
+ "Unable to submit. Check your connection and try again.",
+ );
+ }
+ };
+
+ return (
+ <Questionnaire
+ className={AGENT_COMPOSER_CLASS_NAME}
+ defaultItem="response"
+ items={items}
+ shortcuts="letters"
+ onSubmit={(event) => void submit(event)}
+ >
+ <QuestionnaireItem name="response" required>
+ <QuestionnaireTitle>{question.prompt}</QuestionnaireTitle>
+ <QuestionnaireDescription>
+ {options.length > 0
+ ? "Choose an answer, then submit."
+ : "Add the detail the agent needs to continue."}
+ </QuestionnaireDescription>
+ <QuestionnaireChoices>
+ {options.map((option) => (
+ <QuestionnaireChoice
+ key={option.id}
+ value={`${OPTION_VALUE_PREFIX}${option.id}`}
+ disabled={pending}
+ >
+ <span className="font-medium">{option.label}</span>
+ {option.description ? (
+ <span className="text-muted-foreground">
+ {option.description}
+ </span>
+ ) : null}
+ </QuestionnaireChoice>
+ ))}
+ {showFreeform ? (
+ <QuestionnaireInput
+ aria-label={options.length > 0 ? "Another answer" : "Your answer"}
+ placeholder="Add the detail the agent needs"
+ disabled={pending}
+ />
+ ) : null}
+ </QuestionnaireChoices>
+ <QuestionnaireError />
+ </QuestionnaireItem>
+ {transportError ? (
+ <p role="alert" className="text-destructive text-xs">
+ {transportError}
+ </p>
+ ) : null}
+ <QuestionnaireActions>
+ <QuestionnaireSubmit disabled={pending} aria-busy={pending} size="sm">
+ <AsyncButtonContent
+ status={pending ? "pending" : "idle"}
+ pendingLabel="Submitting"
+ >
+ Submit answer
+ </AsyncButtonContent>
+ </QuestionnaireSubmit>
+ </QuestionnaireActions>
+ </Questionnaire>
+ );
+}
diff --git a/apps/app/components/agent-composer-frame.ts b/apps/app/components/agent-composer-frame.ts
new file mode 100644
index 00000000..d7edc8d4
--- /dev/null
+++ b/apps/app/components/agent-composer-frame.ts
@@ -0,0 +1,2 @@
+export const AGENT_COMPOSER_CLASS_NAME =
+ "flex w-full flex-col justify-between rounded-lg border bg-muted p-[11px] shadow-[inset_0_1px_1px_rgb(0_0_0/0.12)] transition-colors focus-within:border-muted-foreground/60 focus-within:ring-1 focus-within:ring-ring/40";
diff --git a/apps/app/components/app-icon-rail.tsx b/apps/app/components/app-icon-rail.tsx
index 10b658d2..290842de 100644
--- a/apps/app/components/app-icon-rail.tsx
+++ b/apps/app/components/app-icon-rail.tsx
@@ -1,7 +1,9 @@
"use client";
+import Bot from "@carbon/icons-react/es/Bot";
import Building from "@carbon/icons-react/es/Building";
import type { CarbonIconType } from "@carbon/icons-react/es/CarbonIcon";
+import Close from "@carbon/icons-react/es/Close";
import Dashboard from "@carbon/icons-react/es/Dashboard";
import Partnership from "@carbon/icons-react/es/Partnership";
import Settings from "@carbon/icons-react/es/Settings";
@@ -23,6 +25,7 @@ import { cn } from "@crm/ui/lib/utils";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useMemo } from "react";
+import { AgentBuilderSidebar } from "@/components/agent-builder/agent-builder-sidebar";
import { usePrefetchSection } from "@/components/crm/section-prefetch";
import { useMobileNav } from "@/components/mobile-nav";
import { useWorkspaceUrl } from "@/lib/use-workspace-url";
@@ -32,6 +35,7 @@ type RailItem = {
href: string;
icon: CarbonIconType;
match: "exact" | "prefix";
+ related?: string[];
};
const ITEMS: RailItem[] = [
@@ -44,13 +48,21 @@ const ITEMS: RailItem[] = [
match: "prefix",
},
{ title: "Deals", href: "/deals", icon: Partnership, match: "prefix" },
+ {
+ title: "Chat",
+ href: "/chat",
+ icon: Bot,
+ match: "prefix",
+ related: ["/agents"],
+ },
{ title: "Settings", href: "/settings", icon: Settings, match: "prefix" },
];
function isActive(item: RailItem, pathname: string): boolean {
return (
pathname === item.href ||
- (item.match === "prefix" && pathname.startsWith(item.href))
+ (item.match === "prefix" && pathname.startsWith(item.href)) ||
+ Boolean(item.related?.some((prefix) => pathname.startsWith(prefix)))
);
}
@@ -122,6 +134,9 @@ function MobileRailLink({
onFocus={onPrefetch}
aria-current={active ? "page" : undefined}
onClick={onNavigate}
+ transitionTypes={[
+ item.title === "Chat" ? "nav-forward" : "nav-lateral",
+ ]}
>
<Icon icon={item.icon} />
<span>{item.title}</span>
@@ -130,6 +145,43 @@ function MobileRailLink({
);
}
+function MobileRailIconLink({
+ item,
+ active,
+ onNavigate,
+ onPrefetch,
+}: {
+ item: RailItem;
+ active: boolean;
+ onNavigate: () => void;
+ onPrefetch: () => void;
+}) {
+ return (
+ <Button
+ asChild
+ variant="ghost"
+ size="icon"
+ className={cn(
+ "text-muted-foreground",
+ active &&
+ "bg-muted text-foreground hover:bg-muted hover:text-foreground",
+ )}
+ >
+ <Link
+ href={item.href}
+ prefetch
+ onMouseEnter={onPrefetch}
+ onFocus={onPrefetch}
+ aria-current={active ? "page" : undefined}
+ onClick={onNavigate}
+ >
+ <Icon icon={item.icon} />
+ <span className="sr-only">{item.title}</span>
+ </Link>
+ </Button>
+ );
+}
+
export function AppIconRailFallback() {
return (
<nav
@@ -165,9 +217,13 @@ export function AppIconRail() {
...item,
section: item.href,
href: workspaceUrl(item.href),
+ related: item.related?.map((path) => workspaceUrl(path)),
})),
[workspaceUrl],
);
+ const inChat = items.some(
+ (item) => item.title === "Chat" && isActive(item, pathname),
+ );
return (
<>
@@ -186,22 +242,64 @@ export function AppIconRail() {
</nav>
<Sheet open={open} onOpenChange={setOpen}>
- <SheetContent side="left" className="w-64 gap-0 p-0">
- <SheetHeader>
- <SheetTitle>Navigation</SheetTitle>
- </SheetHeader>
- <nav aria-label="Primary" className="flex flex-1 flex-col gap-1 p-2">
- {items.map((item) => (
- <MobileRailLink
- key={item.href}
- item={item}
- active={isActive(item, pathname)}
- onNavigate={() => setOpen(false)}
- onPrefetch={() => prefetchSection(item.section)}
- />
- ))}
- </nav>
- </SheetContent>
+ {inChat ? (
+ <SheetContent
+ side="left"
+ showCloseButton={false}
+ className="w-5/6 max-w-sm flex-row gap-0 p-0"
+ >
+ <SheetHeader className="sr-only">
+ <SheetTitle>Navigation and agent chats</SheetTitle>
+ </SheetHeader>
+ <nav
+ aria-label="Primary"
+ className="flex w-14 shrink-0 flex-col items-center gap-1 border-r py-3"
+ >
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label="Close navigation"
+ onClick={() => setOpen(false)}
+ >
+ <Icon icon={Close} />
+ </Button>
+ <div className="my-1 h-px w-5 bg-border" />
+ {items.map((item) => (
+ <MobileRailIconLink
+ key={item.href}
+ item={item}
+ active={isActive(item, pathname)}
+ onNavigate={() => setOpen(false)}
+ onPrefetch={() => prefetchSection(item.section)}
+ />
+ ))}
+ </nav>
+ <AgentBuilderSidebar
+ className="flex flex-1"
+ onNavigate={() => setOpen(false)}
+ />
+ </SheetContent>
+ ) : (
+ <SheetContent side="left" className="w-64 gap-0 p-0">
+ <SheetHeader>
+ <SheetTitle>Navigation</SheetTitle>
+ </SheetHeader>
+ <nav
+ aria-label="Primary"
+ className="flex flex-1 flex-col gap-1 p-2"
+ >
+ {items.map((item) => (
+ <MobileRailLink
+ key={item.href}
+ item={item}
+ active={isActive(item, pathname)}
+ onNavigate={() => setOpen(false)}
+ onPrefetch={() => prefetchSection(item.section)}
+ />
+ ))}
+ </nav>
+ </SheetContent>
+ )}
</Sheet>
</>
);
diff --git a/apps/app/components/crm/agent-panel.tsx b/apps/app/components/crm/agent-panel.tsx
index d03cd8b2..da2cec42 100644
--- a/apps/app/components/crm/agent-panel.tsx
+++ b/apps/app/components/crm/agent-panel.tsx
@@ -46,7 +46,8 @@ import {
import { Spinner } from "@crm/ui/components/spinner";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEveAgent } from "eve/react";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useEffectEvent, useRef, useState } from "react";
+import { AgentClarificationComposer } from "@/components/agent-clarification-composer";
import {
type Conversation,
ConversationPicker,
@@ -83,19 +84,36 @@ export function AgentPanel({ record }: { record: AgentRecord }) {
const history = conversations.data ?? [];
- const landedOn = useRef<string | null>(null);
- if (landedOn.current === null && conversations.isSuccess) {
- landedOn.current = history[0]?.id ?? NEW_THREAD;
- }
+ if (conversations.isPending) return <Loading />;
+
+ return (
+ <LoadedAgentPanel
+ record={record}
+ history={history}
+ thread={thread}
+ setThread={setThread}
+ />
+ );
+}
+function LoadedAgentPanel({
+ record,
+ history,
+ thread,
+ setThread,
+}: {
+ record: AgentRecord;
+ history: Conversation[];
+ thread: string | null;
+ setThread: (thread: string) => void;
+}) {
+ const [landedOn] = useState(() => history[0]?.id ?? NEW_THREAD);
const { openId, current } = resolveThread({
conversations: history,
fromUrl: thread,
- landedOn: landedOn.current,
+ landedOn,
});
- if (conversations.isPending) return <Loading />;
-
return (
<div className="flex min-h-0 flex-1 flex-col">
<ConversationPicker
@@ -221,7 +239,7 @@ function Thread({
<MessageScrollerProvider autoScroll defaultScrollPosition="end">
<MessageScroller className="flex-1">
<MessageScrollerViewport>
- <MessageScrollerContent className="gap-3 px-5 py-4">
+ <MessageScrollerContent className="gap-3 px-4 py-4 sm:px-5">
{messages.length === 0 && !busy ? (
<Idle kind={record.kind} onAsk={ask} />
) : null}
@@ -229,18 +247,15 @@ function Thread({
{messages.map((message) => (
<MessageScrollerItem key={message.id} messageId={message.id}>
<div className="space-y-3">
- {message.items.map((item) => (
- <Item key={item.id} item={item} />
- ))}
+ {message.items.map((item) =>
+ item.kind === "asked" &&
+ item.question.requestId === question?.requestId ? null : (
+ <Item key={item.id} item={item} />
+ ),
+ )}
</div>
</MessageScrollerItem>
))}
-
- {question ? (
- <MessageScrollerItem messageId={question.requestId}>
- <Question question={question} agent={agent} />
- </MessageScrollerItem>
- ) : null}
</MessageScrollerContent>
</MessageScrollerViewport>
@@ -251,15 +266,15 @@ function Thread({
{agent.error ? <Failure message={agent.error.message} /> : null}
{thread?.status === "working" && !busy ? (
- <p className="border-t px-5 py-2 text-muted-foreground text-xs">
+ <p className="border-t px-4 py-2 text-pretty text-muted-foreground text-xs sm:px-5">
Still working on the last question. Your next one can go in when it
finishes.
</p>
) : null}
{ended ? (
- <div className="flex items-center justify-between gap-3 border-t px-5 py-2">
- <p className="text-muted-foreground text-xs">
+ <div className="flex flex-col items-start gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5 sm:py-2">
+ <p className="text-pretty text-muted-foreground text-xs">
This conversation has ended.
</p>
<Button variant="outline" size="sm" onClick={onNewThread}>
@@ -268,29 +283,40 @@ function Thread({
</div>
) : null}
- <form
- className="flex items-center gap-2 border-t px-5 py-3"
- onSubmit={(event) => {
- event.preventDefault();
- ask(draft);
- }}
- >
- <Input
- value={draft}
- onChange={(event) => setDraft(event.target.value)}
- placeholder={copy.placeholder}
- disabled={locked}
- />
- <Button
- type="submit"
- size="icon-sm"
- variant="outline"
- disabled={locked}
- >
- {busy ? <Spinner /> : <Icon icon={Send} />}
- <span className="sr-only">Ask</span>
- </Button>
- </form>
+ <div className="border-t px-4 py-3 sm:px-5">
+ {question ? (
+ <AgentClarificationComposer
+ key={question.requestId}
+ question={question}
+ pending={busy}
+ onSubmit={(response) => agent.send({ inputResponses: [response] })}
+ />
+ ) : (
+ <form
+ className="flex min-w-0 items-center gap-2"
+ onSubmit={(event) => {
+ event.preventDefault();
+ ask(draft);
+ }}
+ >
+ <Input
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ placeholder={copy.placeholder}
+ disabled={locked}
+ />
+ <Button
+ type="submit"
+ size="icon-sm"
+ variant="outline"
+ disabled={locked}
+ >
+ {busy ? <Spinner /> : <Icon icon={Send} />}
+ <span className="sr-only">Ask</span>
+ </Button>
+ </form>
+ )}
+ </div>
</div>
);
}
@@ -340,9 +366,11 @@ function Failure({ message }: { message: string }) {
: null;
return (
- <div className="border-t px-5 py-3 text-xs">
- <p className="text-destructive">{message}</p>
- {hint ? <p className="text-muted-foreground text-xs">{hint}</p> : null}
+ <div className="border-t px-4 py-3 text-xs sm:px-5">
+ <p className="wrap-break-word text-destructive">{message}</p>
+ {hint ? (
+ <p className="wrap-break-word text-muted-foreground text-xs">{hint}</p>
+ ) : null}
</div>
);
}
@@ -362,20 +390,20 @@ const SOURCE_ICONS: Record<Source["network"], CarbonIcon> = {
function Item({ item }: { item: TranscriptItem }) {
if (item.kind === "said") {
return item.mine ? (
- <Message align="end">
+ <Message align="end" className="min-w-0">
<MessageContent>
<Bubble variant="secondary" align="end">
- <BubbleContent>{item.text}</BubbleContent>
+ <BubbleContent className="text-pretty">{item.text}</BubbleContent>
</Bubble>
</MessageContent>
</Message>
) : (
- <Message>
+ <Message className="min-w-0">
<AgentAvatar />
<MessageContent>
<Bubble variant="ghost">
<BubbleContent>
- <Markdown>{item.text}</Markdown>
+ <Markdown className="wrap-break-word">{item.text}</Markdown>
</BubbleContent>
</Bubble>
</MessageContent>
@@ -383,8 +411,21 @@ function Item({ item }: { item: TranscriptItem }) {
);
}
+ if (item.kind === "asked") {
+ return (
+ <div className="w-full max-w-sm border-ring/50 border-l-2 bg-muted/40 px-3 py-2.5">
+ <p className="font-medium text-xs">Follow-up</p>
+ <Markdown className="mt-1.5 wrap-break-word text-sm leading-5">
+ {item.question.prompt}
+ </Markdown>
+ </div>
+ );
+ }
+
+ if (item.kind === "reasoned") return null;
+
return (
- <div className="space-y-1.5">
+ <div className="min-w-0 space-y-1.5">
<Marker>
<MarkerIcon>
{item.pending ? <Spinner /> : <Icon icon={TONE_ICONS[item.tone]} />}
@@ -430,44 +471,6 @@ function AgentAvatar() {
);
}
-function Question({
- question,
- agent,
-}: {
- question: NonNullable<ReturnType<typeof pendingQuestion>>;
- agent: ReturnType<typeof useEveAgent>;
-}) {
- return (
- <Message>
- <AgentAvatar />
- <MessageContent>
- <Bubble variant="tinted">
- <BubbleContent>{question.prompt}</BubbleContent>
- </Bubble>
-
- <div className="flex flex-wrap gap-2">
- {(question.options ?? []).map((option) => (
- <Button
- key={option.id}
- variant="outline"
- size="sm"
- onClick={() =>
- void agent.send({
- inputResponses: [
- { requestId: question.requestId, optionId: option.id },
- ],
- })
- }
- >
- {option.label}
- </Button>
- ))}
- </div>
- </MessageContent>
- </Message>
- );
-}
-
function useSavedConversation({
record,
conversation,
@@ -496,53 +499,36 @@ function useSavedConversation({
const isNew = conversation === null || conversation.sessionId !== sessionId;
- const latest = useRef({ save, queryClient, trpc, opening });
- latest.current = { save, queryClient, trpc, opening };
-
const written = useRef<string | null>(null);
-
- useEffect(() => {
- if (!sessionId) return;
-
- const cursor = `${sessionId}:${token ?? ""}:${messages}`;
- if (written.current === cursor) return;
- written.current = cursor;
-
- const {
- save: mutation,
- queryClient: cache,
- trpc: api,
- opening: title,
- } = latest.current;
-
- mutation.mutate(
+ const persist = useEffectEvent(() => {
+ save.mutate(
{
...(contactId ? { contactId } : {}),
...(companyId ? { companyId } : {}),
...(dealId ? { dealId } : {}),
- sessionId,
+ sessionId: sessionId ?? "",
continuationToken: token,
streamIndex,
messageCount: messages,
- ...(isNew ? { title: title.current ?? undefined } : {}),
+ ...(isNew ? { title: opening.current ?? undefined } : {}),
},
{
onSuccess: () => {
if (!isNew) return;
- void cache.invalidateQueries({
- queryKey: api.conversations.list.pathKey(),
+ void queryClient.invalidateQueries({
+ queryKey: trpc.conversations.list.pathKey(),
});
},
},
);
- }, [
- sessionId,
- token,
- streamIndex,
- messages,
- contactId,
- companyId,
- dealId,
- isNew,
- ]);
+ });
+
+ useEffect(() => {
+ if (!sessionId) return;
+
+ const cursor = `${sessionId}:${token ?? ""}:${messages}`;
+ if (written.current === cursor) return;
+ written.current = cursor;
+ persist();
+ }, [sessionId, token, messages]);
}
diff --git a/apps/app/lib/agent-builder-state.test.ts b/apps/app/lib/agent-builder-state.test.ts
new file mode 100644
index 00000000..77db4475
--- /dev/null
+++ b/apps/app/lib/agent-builder-state.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from "bun:test";
+import {
+ builderConversationIsWorking,
+ completedBuilderSteps,
+ displayedArtifactVersionId,
+ latestBuilderArtifacts,
+ latestCompletedArtifactVersionId,
+ reviewVersionId,
+} from "./agent-builder-state";
+
+const completedConversation = {
+ sessionId: "session-1",
+ continuationToken: "continue-1",
+ submissions: [{ status: "ACCEPTED" }],
+ createdVersions: [{ id: "version-1", status: "DEPLOYED" }],
+ agent: {
+ status: "LIVE",
+ currentVersion: { id: "version-1" },
+ },
+};
+
+describe("agent builder state", () => {
+ it("keeps polling a new turn after an agent has already been deployed", () => {
+ expect(
+ builderConversationIsWorking({
+ ...completedConversation,
+ submissions: [{ status: "ACCEPTED" }, { status: "PENDING" }],
+ }),
+ ).toBe(true);
+ });
+
+ it("starts revision progress from the current turn instead of old files", () => {
+ const artifacts = [
+ {
+ path: "agent/README.md",
+ createdAt: "2026-08-05T10:00:00.000Z",
+ },
+ {
+ path: "agent/instructions.md",
+ createdAt: "2026-08-05T10:05:01.000Z",
+ },
+ ];
+
+ expect(
+ completedBuilderSteps(artifacts, "2026-08-05T10:05:00.000Z", "session-1"),
+ ).toBe(2);
+ });
+
+ it("tracks an active Eve session until its continuation token is available", () => {
+ expect(
+ builderConversationIsWorking({
+ ...completedConversation,
+ continuationToken: null,
+ }),
+ ).toBe(true);
+ expect(builderConversationIsWorking(completedConversation)).toBe(false);
+ });
+
+ it("offers a newer ready version for review without replacing the live version", () => {
+ const conversation = {
+ ...completedConversation,
+ createdVersions: [{ id: "version-2", status: "READY" }],
+ };
+ expect(reviewVersionId(conversation)).toBe("version-2");
+ expect(displayedArtifactVersionId(conversation, false)).toBe("version-2");
+ expect(displayedArtifactVersionId(conversation, true)).toBeNull();
+ });
+
+ it("renders the immutable deployed artifact snapshot after completion", () => {
+ const artifacts = [
+ {
+ id: "working-3",
+ versionId: null,
+ path: "agent/manifest.json",
+ revision: 3,
+ status: "WRITING" as const,
+ },
+ {
+ id: "ready-2",
+ versionId: "version-1",
+ path: "agent/manifest.json",
+ revision: 2,
+ status: "READY" as const,
+ },
+ ];
+
+ expect(
+ latestBuilderArtifacts(artifacts, "version-1").get("agent/manifest.json")
+ ?.id,
+ ).toBe("ready-2");
+ expect(
+ latestBuilderArtifacts(artifacts, null).get("agent/manifest.json")?.id,
+ ).toBe("working-3");
+ expect(latestCompletedArtifactVersionId(artifacts)).toBe("version-1");
+ });
+});
diff --git a/apps/app/lib/agent-builder-state.ts b/apps/app/lib/agent-builder-state.ts
new file mode 100644
index 00000000..0434535c
--- /dev/null
+++ b/apps/app/lib/agent-builder-state.ts
@@ -0,0 +1,101 @@
+export type BuilderArtifactState = {
+ id: string;
+ versionId: string | null;
+ path: string;
+ revision: number;
+ status: "WRITING" | "READY";
+};
+
+type BuilderVersionState = {
+ id: string;
+ status: string;
+};
+
+type BuilderAgentState = {
+ status: string;
+ currentVersion: { id: string } | null;
+};
+
+export type BuilderConversationState = {
+ sessionId: string | null;
+ continuationToken: string | null;
+ submissions: Array<{ status: string }>;
+ createdVersions: BuilderVersionState[];
+ agent: BuilderAgentState | null;
+};
+
+export function completedBuilderSteps(
+ artifacts: ReadonlyArray<{ path: string; createdAt: string }>,
+ startedAt: string | null,
+ sessionId: string | null,
+): number {
+ const paths = new Set<string>();
+ for (const artifact of artifacts) {
+ if (!startedAt || artifact.createdAt >= startedAt) {
+ paths.add(artifact.path);
+ }
+ }
+ if (paths.has("agent/README.md")) return 4;
+ if (paths.has("agent/manifest.json")) return 3;
+ if (paths.has("agent/instructions.md")) return 2;
+ return sessionId ? 1 : 0;
+}
+
+export function builderConversationIsWorking(
+ conversation: BuilderConversationState,
+): boolean {
+ return (
+ conversation.submissions.some((submission) =>
+ ["PENDING", "SENDING"].includes(submission.status),
+ ) || Boolean(conversation.sessionId && !conversation.continuationToken)
+ );
+}
+
+export function reviewVersionId(
+ conversation: BuilderConversationState,
+): string | null {
+ const version = conversation.createdVersions[0];
+ if (version?.status !== "READY") return null;
+ if (version.id === conversation.agent?.currentVersion?.id) return null;
+ return version.id;
+}
+
+export function displayedArtifactVersionId(
+ conversation: BuilderConversationState,
+ working: boolean,
+): string | null {
+ if (working) return null;
+ return (
+ reviewVersionId(conversation) ??
+ conversation.agent?.currentVersion?.id ??
+ conversation.createdVersions[0]?.id ??
+ null
+ );
+}
+
+export function latestBuilderArtifacts<T extends BuilderArtifactState>(
+ artifacts: readonly T[],
+ versionId: string | null,
+): Map<string, T> {
+ const candidates = versionId
+ ? artifacts.filter((artifact) => artifact.versionId === versionId)
+ : artifacts;
+ const latest = new Map<string, T>();
+ for (const artifact of candidates) {
+ const current = latest.get(artifact.path);
+ if (!current || artifact.revision > current.revision) {
+ latest.set(artifact.path, artifact);
+ }
+ }
+ return latest;
+}
+
+export function latestCompletedArtifactVersionId(
+ artifacts: readonly BuilderArtifactState[],
+): string | null {
+ return (
+ artifacts.find(
+ (artifact) => artifact.status === "READY" && artifact.versionId,
+ )?.versionId ?? null
+ );
+}
diff --git a/apps/app/lib/agent-builder.ts b/apps/app/lib/agent-builder.ts
new file mode 100644
index 00000000..80fcb36f
--- /dev/null
+++ b/apps/app/lib/agent-builder.ts
@@ -0,0 +1,72 @@
+export type BuilderCommandType = "CHAT" | "CREATE_AGENT";
+
+const CREATE_AGENT = /^\/create(?:\s+agent|-agent)(?:\s|$)/i;
+const CREATE_AGENT_REQUEST =
+ /\b(?:create|build|draft|make|configure|set\s+up)(?:\s+me)?\s+(?:(?:and\s+save)\s+)?(?:(?:a|an|the|this)\s+)?(?:new\s+)?agent\b/i;
+const CREATE_AGENT_NON_REQUEST =
+ /\b(?:(?:do\s+not|don't|dont|never)\b[^.!?]*|how\s+(?:(?:do|can|could|would|should)\s+(?:i|we)|to))\s*$/i;
+const CREATE_AGENT_QUESTION =
+ /^(?:how|why|when|where|what|does|do|did|is|are|will|would|can|could|should)\b/i;
+const CREATE_AGENT_REQUEST_CUE =
+ /\b(?:please|plz|(?:can|could|would|will)\s+you|i\s+(?:need|want)\b|we\s+need\b|let'?s)\b/i;
+
+function matchCreateAgentRequest(message: string): RegExpExecArray | null {
+ const match = CREATE_AGENT_REQUEST.exec(message);
+ if (!match) return null;
+
+ const prefix = message.slice(0, match.index);
+ if (CREATE_AGENT_NON_REQUEST.test(prefix)) return null;
+ if (
+ message.trimEnd().endsWith("?") &&
+ CREATE_AGENT_QUESTION.test(message.trimStart()) &&
+ !CREATE_AGENT_REQUEST_CUE.test(prefix)
+ ) {
+ return null;
+ }
+
+ return match;
+}
+
+export function builderCommandType(message: string): BuilderCommandType {
+ const trimmed = message.trimStart();
+ return CREATE_AGENT.test(trimmed) || matchCreateAgentRequest(trimmed)
+ ? "CREATE_AGENT"
+ : "CHAT";
+}
+
+export function consumeBuilderCommand(
+ message: string,
+): { commandType: BuilderCommandType; body: string } | null {
+ const trimmed = message.trimStart();
+ const match = CREATE_AGENT.exec(trimmed);
+ if (!match) return null;
+
+ return {
+ commandType: "CREATE_AGENT",
+ body: trimmed.slice(match[0].length).trimStart(),
+ };
+}
+
+export function consumeBuilderIntent(message: string): {
+ commandType: "CREATE_AGENT";
+ body: string;
+ invocation: string;
+} | null {
+ const trimmed = message.trimStart();
+ const match = matchCreateAgentRequest(trimmed);
+ if (!match) return null;
+
+ return {
+ commandType: "CREATE_AGENT",
+ body: trimmed.slice(match.index + match[0].length).replace(/^[\s,:-]+/, ""),
+ invocation: match[0].trim(),
+ };
+}
+
+export function hasCreateAgentCommand(
+ submissions: ReadonlyArray<{ commandType: BuilderCommandType }>,
+): boolean {
+ return submissions.some(
+ (submission) => submission.commandType === "CREATE_AGENT",
+ );
+}
diff --git a/apps/app/lib/agent-transcript.ts b/apps/app/lib/agent-transcript.ts
index a315c9a5..cc985657 100644
--- a/apps/app/lib/agent-transcript.ts
+++ b/apps/app/lib/agent-transcript.ts
@@ -1,14 +1,28 @@
-import type { EveMessage, EveMessagePart } from "eve/react";
+import type { MessageStreamEvent } from "eve/client";
+import {
+ defaultMessageReducer,
+ type EveMessage,
+ type EveMessageInputRequest,
+ type EveMessagePart,
+} from "eve/react";
export type TranscriptItem =
| { kind: "said"; id: string; mine: boolean; text: string }
+ | { kind: "reasoned"; id: string; streaming: boolean; text: string }
+ | {
+ kind: "asked";
+ id: string;
+ question: EveMessageInputRequest;
+ }
| {
kind: "did";
id: string;
label: string;
+ output: unknown;
tone: Tone;
pending: boolean;
sources: Source[];
+ tool: string;
};
export type Tone = "neutral" | "success" | "warning";
@@ -19,6 +33,16 @@ export type Source = {
network: "linkedin" | "github" | "web";
};
+export type AgentTurnFailure = {
+ code: string;
+ kind: "rate-limit" | "restricted" | "credits" | "unknown";
+};
+
+type AgentStreamEvent = {
+ type: string;
+ data?: unknown;
+};
+
const VERBS: Record<string, string> = {
read_crm_history: "Read our emails and meetings with them",
read_company_history: "Read everything we have on the company",
@@ -72,11 +96,109 @@ export type TranscriptMessage = {
items: TranscriptItem[];
};
+export type ConversationTimelineItem<
+ TSubmission extends { id: string; createdAt: string },
+> =
+ | { kind: "submission"; id: string; submission: TSubmission }
+ | { kind: "assistant"; id: string; message: EveMessage };
+
+export function messagesFromEvents(
+ events: readonly MessageStreamEvent[],
+): readonly EveMessage[] {
+ const reducer = defaultMessageReducer();
+ let data = reducer.initial();
+
+ for (const event of events) data = reducer.reduce(data, event);
+
+ return data.messages;
+}
+
+const SETTLED_EVENT_TYPES = new Set([
+ "input.requested",
+ "session.completed",
+ "session.failed",
+ "session.waiting",
+ "turn.cancelled",
+]);
+
+export function eventStreamSettled(
+ events: readonly { type: string }[],
+): boolean {
+ const last = events.at(-1);
+ return Boolean(last && SETTLED_EVENT_TYPES.has(last.type));
+}
+
+export function conversationTimeline<
+ TSubmission extends { id: string; createdAt: string },
+>(
+ submissions: readonly TSubmission[],
+ events: readonly MessageStreamEvent[],
+ messages: readonly EveMessage[],
+): ConversationTimelineItem<TSubmission>[] {
+ const turnTimes = new Map<string, number>();
+
+ for (const event of events) {
+ const turnId = stringOf(
+ recordOf("data" in event ? event.data : undefined).turnId,
+ );
+ if (!turnId || turnTimes.has(turnId)) continue;
+ turnTimes.set(turnId, timestampOf(event.meta.at));
+ }
+
+ const assistantRows: Array<{
+ kind: "assistant";
+ id: string;
+ message: EveMessage;
+ at: number;
+ index: number;
+ }> = [];
+ for (const [index, message] of messages.entries()) {
+ if (message.role !== "assistant") continue;
+ assistantRows.push({
+ kind: "assistant",
+ id: `assistant:${message.id}`,
+ message,
+ at:
+ turnTimes.get(stringOf(recordOf(message.metadata).turnId) ?? "") ??
+ Number.POSITIVE_INFINITY,
+ index,
+ });
+ }
+
+ const rows = [
+ ...submissions.map((submission, index) => ({
+ kind: "submission" as const,
+ id: `submission:${submission.id}`,
+ submission,
+ at: timestampOf(submission.createdAt),
+ index,
+ })),
+ ...assistantRows,
+ ];
+
+ rows.sort((a, b) =>
+ a.at !== b.at
+ ? a.at - b.at
+ : a.kind === b.kind
+ ? a.index - b.index
+ : a.kind === "submission"
+ ? -1
+ : 1,
+ );
+
+ return rows.map((row) =>
+ row.kind === "submission"
+ ? { kind: row.kind, id: row.id, submission: row.submission }
+ : { kind: row.kind, id: row.id, message: row.message },
+ );
+}
+
export function toTranscript(
messages: readonly EveMessage[],
): TranscriptMessage[] {
- return messages
- .map((message) => ({
+ const transcript: TranscriptMessage[] = [];
+ for (const message of messages) {
+ const row = {
id: message.id,
mine: message.role === "user",
items: message.parts.flatMap((part, index): TranscriptItem[] => {
@@ -88,26 +210,53 @@ export function toTranscript(
return [{ kind: "said", id, mine: message.role === "user", text }];
}
+ if (part.type === "reasoning") {
+ const text = part.text.trim();
+ if (!text) return [];
+ return [
+ {
+ kind: "reasoned",
+ id,
+ streaming: part.state === "streaming",
+ text,
+ },
+ ];
+ }
+
+ if (part.type === "dynamic-tool") {
+ const request = part.toolMetadata?.eve?.inputRequest;
+ if (request?.kind === "question") {
+ return [{ kind: "asked", id, question: request }];
+ }
+ }
+
if (part.type.startsWith("tool-") || part.type === "dynamic-tool") {
const state = "state" in part ? part.state : undefined;
+ const tool = toolName(part);
return [
{
kind: "did",
id,
label: describe(part),
+ output: output(part),
tone: outcomeTone(part),
pending:
- state === "input-streaming" || state === "input-available",
+ state === "input-streaming" ||
+ state === "input-available" ||
+ state === "approval-requested",
sources: sourcesOf(part),
+ tool,
},
];
}
return [];
}),
- }))
- .filter((message) => message.items.length > 0);
+ };
+ if (row.items.length > 0) transcript.push(row);
+ }
+ return transcript;
}
function partId(
@@ -180,10 +329,48 @@ export function sourcesOf(part: EveMessagePart): Source[] {
export function pendingQuestion(messages: readonly EveMessage[]) {
for (const part of messages.at(-1)?.parts ?? []) {
- if (part.type !== "dynamic-tool") continue;
+ if (part.type !== "dynamic-tool" || part.state !== "approval-requested") {
+ continue;
+ }
const request = part.toolMetadata?.eve?.inputRequest;
- if (request) return request;
+ if (request?.kind === "question") return request;
+ }
+
+ return null;
+}
+
+export function latestTurnFailure(
+ events: readonly AgentStreamEvent[],
+): AgentTurnFailure | null {
+ for (let index = events.length - 1; index >= 0; index -= 1) {
+ const event = events[index];
+ if (!event) continue;
+ if (event.type === "turn.completed" || event.type === "turn.started") {
+ return null;
+ }
+ if (event.type !== "turn.failed" && event.type !== "session.failed") {
+ continue;
+ }
+
+ const data = recordOf(event.data);
+ const message = typeof data.message === "string" ? data.message : "";
+ const code = typeof data.code === "string" ? data.code : "AGENT_FAILED";
+
+ return {
+ code,
+ kind: /free tier users do not have access|RestrictedModelsError/i.test(
+ message,
+ )
+ ? "restricted"
+ : /GatewayRateLimitError|free tier requests.*rate-?limited/i.test(
+ message,
+ )
+ ? "rate-limit"
+ : /credits?|quota|billing|usage limit/i.test(message)
+ ? "credits"
+ : "unknown",
+ };
}
return null;
@@ -195,6 +382,21 @@ function output(part: EveMessagePart): Record<string, unknown> | null {
: null;
}
+function recordOf(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : {};
+}
+
+function stringOf(value: unknown): string | null {
+ return typeof value === "string" && value ? value : null;
+}
+
+function timestampOf(value: string): number {
+ const timestamp = Date.parse(value);
+ return Number.isFinite(timestamp) ? timestamp : Number.POSITIVE_INFINITY;
+}
+
function hostOf(url: string): string {
try {
return new URL(url).hostname.replace(/^www\./, "");
@@ -203,6 +405,243 @@ function hostOf(url: string): string {
}
}
+export type DealListItem = {
+ id: string;
+ name: string;
+ stage: string;
+ amount: number | null;
+ currency: string;
+ company: {
+ id: string;
+ name: string;
+ domain: string | null;
+ iconUrl: string | null;
+ iconDarkUrl: string | null;
+ iconTone: string | null;
+ logoUrl: string | null;
+ };
+ owner: {
+ id: string;
+ name: string;
+ email: string;
+ image: string | null;
+ } | null;
+ daysSinceLastActivity: number;
+ neverActive: boolean;
+ expectedCloseDate: string | null;
+};
+
+export type DealListResult = {
+ asOf: string;
+ criteria: {
+ status: string;
+ inactiveForDays: number | null;
+ companyId: string | null;
+ ownerId: string | null;
+ };
+ deals: DealListItem[];
+ hasMore: boolean;
+};
+
+export function dealListResultOf(value: unknown): DealListResult | null {
+ const result = recordOf(value);
+ const asOf = stringOf(result.asOf);
+ const criteria = recordOf(result.criteria);
+ const status = stringOf(criteria.status);
+ const inactiveForDays = nullableNumberOf(criteria.inactiveForDays);
+ const companyId = nullableStringOf(criteria.companyId);
+ const ownerId = nullableStringOf(criteria.ownerId);
+ const rows = Array.isArray(result.deals) ? result.deals : null;
+
+ if (
+ !asOf ||
+ !status ||
+ inactiveForDays === undefined ||
+ companyId === undefined ||
+ ownerId === undefined ||
+ !rows
+ )
+ return null;
+
+ const deals = rows.map(dealListItemOf);
+ if (deals.some((deal) => deal === null)) return null;
+
+ return {
+ asOf,
+ criteria: { status, inactiveForDays, companyId, ownerId },
+ deals: deals as DealListItem[],
+ hasMore: result.hasMore === true,
+ };
+}
+
+export function mergeDealListResultPages(
+ results: readonly DealListResult[],
+): DealListResult[] {
+ const groups = new Map<string, DealListResult>();
+ for (const result of results) {
+ const key = JSON.stringify(result.criteria);
+ const previous = groups.get(key);
+ const deals = new Map(
+ previous?.deals.map((deal) => [deal.id, deal] as const),
+ );
+ for (const deal of result.deals) deals.set(deal.id, deal);
+
+ groups.set(key, {
+ ...result,
+ deals: [...deals.values()],
+ });
+ }
+
+ return [...groups.values()];
+}
+
+function stripMarkdownTables(markdown: string): string {
+ const lines = markdown.split("\n");
+ const kept: string[] = [];
+
+ for (let index = 0; index < lines.length; index += 1) {
+ const line = lines[index] ?? "";
+ const separator = lines[index + 1] ?? "";
+
+ if (line.includes("|") && isMarkdownTableSeparator(separator)) {
+ index += 1;
+ while (index + 1 < lines.length) {
+ const nextLine = lines[index + 1];
+ if (nextLine === undefined || !isMarkdownTableRow(nextLine)) break;
+ index += 1;
+ }
+ if (kept.at(-1) !== "") kept.push("");
+ continue;
+ }
+
+ kept.push(line);
+ }
+
+ return kept
+ .join("\n")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+}
+
+export function splitMarkdownTable(markdown: string): {
+ after: string;
+ before: string;
+ found: boolean;
+} {
+ const lines = markdown.split("\n");
+
+ for (let index = 0; index < lines.length - 1; index += 1) {
+ const line = lines[index] ?? "";
+ const separator = lines[index + 1] ?? "";
+ if (!line.includes("|") || !isMarkdownTableSeparator(separator)) continue;
+
+ let end = index + 2;
+ while (end < lines.length) {
+ const row = lines[end];
+ if (row === undefined || !isMarkdownTableRow(row)) break;
+ end += 1;
+ }
+
+ return {
+ before: normaliseMarkdown(lines.slice(0, index).join("\n")),
+ after: stripMarkdownTables(lines.slice(end).join("\n")),
+ found: true,
+ };
+ }
+
+ return { before: "", after: normaliseMarkdown(markdown), found: false };
+}
+
+function dealListItemOf(value: unknown): DealListItem | null {
+ const deal = recordOf(value);
+ const company = recordOf(deal.company);
+ const owner = deal.owner === null ? null : recordOf(deal.owner);
+ const id = stringOf(deal.id);
+ const name = stringOf(deal.name);
+ const stage = stringOf(deal.stage);
+ const currency = stringOf(deal.currency);
+ const companyId = stringOf(company.id);
+ const companyName = stringOf(company.name);
+ const daysSinceLastActivity = numberOf(deal.daysSinceLastActivity);
+ const amount = nullableNumberOf(deal.amount);
+ const expectedCloseDate = nullableStringOf(deal.expectedCloseDate);
+
+ if (
+ !id ||
+ !name ||
+ !stage ||
+ !currency ||
+ !companyId ||
+ !companyName ||
+ daysSinceLastActivity === null ||
+ amount === undefined ||
+ expectedCloseDate === undefined
+ ) {
+ return null;
+ }
+
+ const parsedOwner = owner
+ ? {
+ id: stringOf(owner.id),
+ name: stringOf(owner.name),
+ email: stringOf(owner.email),
+ image: nullableStringOf(owner.image) ?? null,
+ }
+ : null;
+ if (
+ parsedOwner &&
+ (!parsedOwner.id || !parsedOwner.name || !parsedOwner.email)
+ ) {
+ return null;
+ }
+
+ return {
+ id,
+ name,
+ stage,
+ amount,
+ currency,
+ company: {
+ id: companyId,
+ name: companyName,
+ domain: nullableStringOf(company.domain) ?? null,
+ iconUrl: nullableStringOf(company.iconUrl) ?? null,
+ iconDarkUrl: nullableStringOf(company.iconDarkUrl) ?? null,
+ iconTone: nullableStringOf(company.iconTone) ?? null,
+ logoUrl: nullableStringOf(company.logoUrl) ?? null,
+ },
+ owner: parsedOwner as DealListItem["owner"],
+ daysSinceLastActivity,
+ neverActive: deal.neverActive === true,
+ expectedCloseDate,
+ };
+}
+
+function numberOf(value: unknown): number | null {
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
+}
+
+function nullableNumberOf(value: unknown): number | null | undefined {
+ return value === null ? null : (numberOf(value) ?? undefined);
+}
+
+function nullableStringOf(value: unknown): string | null | undefined {
+ return value === null ? null : (stringOf(value) ?? undefined);
+}
+
+function isMarkdownTableSeparator(line: string): boolean {
+ return /^\s*\|?\s*:?-{3,}:?(?:\s*\|\s*:?-{3,}:?)+\s*\|?\s*$/.test(line);
+}
+
+function isMarkdownTableRow(line: string): boolean {
+ const trimmed = line.trim();
+ return trimmed.includes("|") && !isMarkdownTableSeparator(trimmed);
+}
+
+function normaliseMarkdown(markdown: string): string {
+ return markdown.replace(/\n{3,}/g, "\n\n").trim();
+}
+
export const NEW_THREAD = "new";
export function resolveThread<T extends { id: string }>({
diff --git a/apps/app/lib/api-proxy-response.ts b/apps/app/lib/api-proxy-response.ts
new file mode 100644
index 00000000..2363a2c1
--- /dev/null
+++ b/apps/app/lib/api-proxy-response.ts
@@ -0,0 +1,37 @@
+import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib";
+
+export async function bufferedProxyResponse(
+ upstream: Response,
+ headers: Headers,
+ method: string,
+): Promise<Response> {
+ const responseHeaders = new Headers(headers);
+ responseHeaders.delete("content-encoding");
+ responseHeaders.delete("content-length");
+ const init: ResponseInit = {
+ status: upstream.status,
+ statusText: upstream.statusText,
+ headers: responseHeaders,
+ };
+ if (!responseCanHaveBody(method, upstream.status)) {
+ return new Response(null, init);
+ }
+
+ const raw = Buffer.from(await upstream.arrayBuffer());
+ const body = decode(raw, upstream.headers.get("content-encoding"));
+ return new Response(new Uint8Array(body), init);
+}
+
+export function responseCanHaveBody(method: string, status: number): boolean {
+ return method !== "HEAD" && ![204, 205, 304].includes(status);
+}
+
+function decode(buf: Buffer, encoding: string | null): Buffer {
+ const enc = (encoding ?? "").toLowerCase();
+ try {
+ if (enc.includes("br")) return brotliDecompressSync(buf);
+ if (enc.includes("gzip")) return gunzipSync(buf);
+ if (enc.includes("deflate")) return inflateSync(buf);
+ } catch {}
+ return buf;
+}
diff --git a/apps/app/lib/chat-date-group.ts b/apps/app/lib/chat-date-group.ts
new file mode 100644
index 00000000..54581bb0
--- /dev/null
+++ b/apps/app/lib/chat-date-group.ts
@@ -0,0 +1,18 @@
+const DAY_MS = 86_400_000;
+
+export type ChatDateGroup = "Today" | "Yesterday" | "Last 7 days";
+
+export function chatDateGroup(
+ lastMessageAt: string,
+ now: number,
+): ChatDateGroup | null {
+ if (!now) return null;
+
+ const daysAgo =
+ Math.floor(now / DAY_MS) -
+ Math.floor(new Date(lastMessageAt).getTime() / DAY_MS);
+ if (daysAgo <= 0) return "Today";
+ if (daysAgo === 1) return "Yesterday";
+ if (daysAgo <= 7) return "Last 7 days";
+ return null;
+}
diff --git a/apps/app/lib/chat-route.ts b/apps/app/lib/chat-route.ts
new file mode 100644
index 00000000..a4916a2c
--- /dev/null
+++ b/apps/app/lib/chat-route.ts
@@ -0,0 +1,5 @@
+const SHARED_CHAT_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
+
+export function isSharedChatToken(value: string): boolean {
+ return SHARED_CHAT_TOKEN_PATTERN.test(value);
+}
diff --git a/apps/app/next.config.ts b/apps/app/next.config.ts
index f3e1834c..98b199a7 100644
--- a/apps/app/next.config.ts
+++ b/apps/app/next.config.ts
@@ -8,7 +8,19 @@ const apiUrl =
process.env.NEXT_PUBLIC_API_URL ??
"http://localhost:3001";
+const allowedDevOrigins = (process.env.APP_URL ?? "")
+ .split(",")
+ .flatMap((origin) => {
+ try {
+ return [new URL(origin.trim()).hostname];
+ } catch {
+ return [];
+ }
+ });
+
const nextConfig: NextConfig = {
+ allowedDevOrigins,
+
env: {
NEXT_PUBLIC_API_URL: apiUrl,
},
diff --git a/apps/app/package.json b/apps/app/package.json
index 35e03a23..72cc7149 100644
--- a/apps/app/package.json
+++ b/apps/app/package.json
@@ -18,6 +18,8 @@
"@crm/env": "workspace:*",
"@crm/telemetry": "workspace:*",
"@crm/ui": "workspace:*",
+ "@pierre/diffs": "^1.2.12",
+ "@pierre/trees": "^1.0.0-beta.5",
"@tanstack/react-query": "^5.101.2",
"@trpc/client": "^11.18.0",
"@trpc/server": "^11.18.0",
diff --git a/apps/app/test/agent-builder.spec.ts b/apps/app/test/agent-builder.spec.ts
new file mode 100644
index 00000000..3abbbf1d
--- /dev/null
+++ b/apps/app/test/agent-builder.spec.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from "bun:test";
+import {
+ builderCommandType,
+ consumeBuilderCommand,
+ consumeBuilderIntent,
+ hasCreateAgentCommand,
+} from "../lib/agent-builder";
+
+describe("agent builder commands", () => {
+ it("enters agent creation for slash commands and direct build requests", () => {
+ expect(builderCommandType("/Create agent Flag stalled deals")).toBe(
+ "CREATE_AGENT",
+ );
+ expect(builderCommandType(" /create agent summarize renewals")).toBe(
+ "CREATE_AGENT",
+ );
+ expect(builderCommandType("Tell me about this customer")).toBe("CHAT");
+ expect(builderCommandType("/Create agentic workflows")).toBe("CHAT");
+ expect(builderCommandType("/create-agent Flag stalled deals")).toBe(
+ "CREATE_AGENT",
+ );
+ expect(
+ builderCommandType('Create an agent named "Stalled Deal Brief".'),
+ ).toBe("CREATE_AGENT");
+ expect(builderCommandType("Build and save a new agent for renewals")).toBe(
+ "CREATE_AGENT",
+ );
+ expect(builderCommandType("Build me an agent for stalled deals")).toBe(
+ "CREATE_AGENT",
+ );
+ expect(builderCommandType("Build the agent I described above")).toBe(
+ "CREATE_AGENT",
+ );
+ expect(builderCommandType("Please set up an agent for overdue deals")).toBe(
+ "CREATE_AGENT",
+ );
+ expect(
+ builderCommandType("I want you to create an agent for renewals"),
+ ).toBe("CREATE_AGENT");
+ expect(builderCommandType("hey fucker plz create an agent to")).toBe(
+ "CREATE_AGENT",
+ );
+ expect(builderCommandType("How do I create an agent?")).toBe("CHAT");
+ expect(builderCommandType("Tell me how to create an agent")).toBe("CHAT");
+ expect(builderCommandType("I do not want you to create an agent")).toBe(
+ "CHAT",
+ );
+ expect(builderCommandType("Tell me about our agent workflows")).toBe(
+ "CHAT",
+ );
+ expect(consumeBuilderCommand("/Create agent Flag stalled deals")).toEqual({
+ commandType: "CREATE_AGENT",
+ body: "Flag stalled deals",
+ });
+ expect(
+ consumeBuilderIntent("Build an agent that flags stalled deals"),
+ ).toEqual({
+ commandType: "CREATE_AGENT",
+ body: "that flags stalled deals",
+ invocation: "Build an agent",
+ });
+ expect(consumeBuilderIntent("hey fucker plz create an agent to")).toEqual({
+ commandType: "CREATE_AGENT",
+ body: "to",
+ invocation: "create an agent",
+ });
+ expect(
+ consumeBuilderIntent("Tell me about our agent workflows"),
+ ).toBeNull();
+ });
+
+ it("shows creation surfaces only after a creation command", () => {
+ expect(hasCreateAgentCommand([{ commandType: "CHAT" }])).toBe(false);
+ expect(
+ hasCreateAgentCommand([
+ { commandType: "CHAT" },
+ { commandType: "CREATE_AGENT" },
+ ]),
+ ).toBe(true);
+ });
+});
diff --git a/apps/app/test/agent-transcript.spec.ts b/apps/app/test/agent-transcript.spec.ts
index d7cfb62d..09b4d006 100644
--- a/apps/app/test/agent-transcript.spec.ts
+++ b/apps/app/test/agent-transcript.spec.ts
@@ -2,18 +2,34 @@ import { describe, expect, it } from "bun:test";
import { readdirSync } from "node:fs";
import type { EveMessage } from "eve/react";
import {
+ conversationTimeline,
+ dealListResultOf,
describe as describeStep,
+ eventStreamSettled,
+ latestTurnFailure,
+ mergeDealListResultPages,
NEW_THREAD,
outcomeTone,
pendingQuestion,
resolveThread,
sourcesOf,
+ splitMarkdownTable,
TOOL_VERBS,
toTranscript,
} from "../lib/agent-transcript";
-const message = (parts: unknown[], role: "user" | "assistant" = "assistant") =>
- ({ id: "m1", role, parts }) as unknown as EveMessage;
+const message = (
+ parts: unknown[],
+ role: "user" | "assistant" = "assistant",
+ id = "m1",
+ turnId?: string,
+) =>
+ ({
+ id,
+ role,
+ parts,
+ metadata: turnId ? { turnId } : undefined,
+ }) as unknown as EveMessage;
const tool = (
toolName: string,
@@ -47,6 +63,24 @@ describe("toTranscript", () => {
expect(grouped[0]?.items.map((item) => item.kind)).toEqual(["said", "did"]);
});
+ it("keeps emitted model reasoning as a first-class part", () => {
+ const grouped = toTranscript([
+ message([
+ {
+ type: "reasoning",
+ state: "streaming",
+ text: "I need to inspect the pipeline.",
+ },
+ ]),
+ ]);
+
+ expect(grouped[0]?.items[0]).toMatchObject({
+ kind: "reasoned",
+ streaming: true,
+ text: "I need to inspect the pipeline.",
+ });
+ });
+
it("gives a tool call the same id across its streaming states", () => {
const streaming = toTranscript([
message([
@@ -86,6 +120,220 @@ describe("toTranscript", () => {
expect(grouped[0]?.items[0]).toMatchObject({ kind: "did", pending: true });
});
+
+ it("keeps a tool name and structured output for dedicated result UI", () => {
+ const grouped = toTranscript([
+ message([
+ tool("list_deals", {
+ output: { deals: [] },
+ }),
+ ]),
+ ]);
+
+ expect(grouped[0]?.items[0]).toMatchObject({
+ kind: "did",
+ tool: "list_deals",
+ output: { deals: [] },
+ });
+ });
+
+ it("keeps an ask_question tool as a first-class follow-up", () => {
+ const request = {
+ requestId: "req_1",
+ kind: "question",
+ prompt: "Which account should I use?",
+ options: [{ id: "primary", label: "Primary account" }],
+ };
+ const grouped = toTranscript([
+ message([
+ {
+ type: "dynamic-tool",
+ toolName: "ask_question",
+ state: "approval-requested",
+ toolMetadata: { eve: { inputRequest: request } },
+ },
+ ]),
+ ]);
+
+ expect(grouped[0]?.items[0]).toMatchObject({
+ kind: "asked",
+ question: { requestId: "req_1", prompt: "Which account should I use?" },
+ });
+ });
+});
+
+describe("deal list presentation", () => {
+ const output = {
+ asOf: "2026-08-06T01:14:05.025Z",
+ criteria: {
+ status: "open",
+ inactiveForDays: 14,
+ companyId: null,
+ ownerId: null,
+ },
+ deals: [
+ {
+ id: "deal-1",
+ name: "Notion — expansion",
+ stage: "CONTRACT_SENT",
+ amount: 14_000,
+ currency: "USD",
+ company: {
+ id: "company-1",
+ name: "Notion",
+ domain: "notion.so",
+ iconUrl: "https://cdn.example.test/notion.png",
+ iconDarkUrl: null,
+ iconTone: "opaque",
+ logoUrl: "https://cdn.example.test/notion.svg",
+ },
+ owner: {
+ id: "user-1",
+ name: "Priya Raman",
+ email: "[email protected]",
+ image: "https://cdn.example.test/priya.png",
+ },
+ daysSinceLastActivity: 201,
+ neverActive: true,
+ expectedCloseDate: "2026-09-03T19:50:06.111Z",
+ },
+ ],
+ hasMore: false,
+ };
+
+ it("parses structured list_deals output", () => {
+ expect(dealListResultOf(output)).toMatchObject({
+ criteria: { status: "open", inactiveForDays: 14 },
+ deals: [
+ {
+ id: "deal-1",
+ daysSinceLastActivity: 201,
+ company: {
+ iconUrl: "https://cdn.example.test/notion.png",
+ },
+ owner: { image: "https://cdn.example.test/priya.png" },
+ },
+ ],
+ });
+ expect(dealListResultOf({ deals: [] })).toBeNull();
+ });
+
+ it("merges paginated deal results without duplicate rows", () => {
+ const first = dealListResultOf({ ...output, hasMore: true });
+ const second = dealListResultOf({
+ ...output,
+ asOf: "2026-08-06T01:15:00.000Z",
+ deals: [
+ output.deals[0],
+ { ...output.deals[0], id: "deal-2", name: "Linear — Comp AI" },
+ ],
+ });
+ if (!first || !second) throw new Error("Expected valid deal list results");
+
+ expect(mergeDealListResultPages([first, second])).toMatchObject([
+ {
+ asOf: "2026-08-06T01:15:00.000Z",
+ hasMore: false,
+ deals: [{ id: "deal-1" }, { id: "deal-2" }],
+ },
+ ]);
+ });
+
+ it("keeps different deal query scopes in separate result groups", () => {
+ const open = dealListResultOf(output);
+ const company = dealListResultOf({
+ ...output,
+ criteria: { ...output.criteria, companyId: "company-1" },
+ });
+ if (!open || !company) throw new Error("Expected valid deal list results");
+
+ expect(mergeDealListResultPages([open, company])).toMatchObject([
+ { criteria: { companyId: null }, deals: [{ id: "deal-1" }] },
+ { criteria: { companyId: "company-1" }, deals: [{ id: "deal-1" }] },
+ ]);
+ });
+
+ it("removes model-authored Markdown tables while keeping its analysis", () => {
+ const markdown = [
+ "I found two stale deals.",
+ "",
+ "| Deal | Idle |",
+ "|---|---|",
+ "| Notion | 201 days |",
+ "| Linear | 134 days |",
+ "",
+ "### What stands out",
+ "Follow up on Notion first.",
+ ].join("\n");
+
+ expect(splitMarkdownTable(markdown)).toEqual({
+ before: "I found two stale deals.",
+ after: "### What stands out\nFollow up on Notion first.",
+ found: true,
+ });
+ });
+});
+
+describe("conversationTimeline", () => {
+ it("renders each follow-up before the answer submitted for it", () => {
+ const submissions = [
+ { id: "opening", createdAt: "2026-08-05T10:00:00.000Z" },
+ { id: "answer", createdAt: "2026-08-05T10:02:00.000Z" },
+ ];
+ const messages = [
+ message(
+ [{ type: "text", text: "Which one?" }],
+ "assistant",
+ "a1",
+ "turn-1",
+ ),
+ message([{ type: "text", text: "Got it." }], "assistant", "a2", "turn-2"),
+ ];
+ const events = [
+ {
+ type: "turn.started",
+ data: { turnId: "turn-1" },
+ meta: { id: "event-1", at: "2026-08-05T10:01:00.000Z" },
+ },
+ {
+ type: "turn.started",
+ data: { turnId: "turn-2" },
+ meta: { id: "event-2", at: "2026-08-05T10:03:00.000Z" },
+ },
+ ] as never;
+
+ const timeline = conversationTimeline(submissions, events, messages);
+
+ expect(timeline.map((item) => item.kind)).toEqual([
+ "submission",
+ "assistant",
+ "submission",
+ "assistant",
+ ]);
+ expect(timeline.map((item) => item.id)).toEqual([
+ "submission:opening",
+ "assistant:a1",
+ "submission:answer",
+ "assistant:a2",
+ ]);
+ });
+});
+
+describe("eventStreamSettled", () => {
+ it("keeps fetching after a tool step until the terminal event arrives", () => {
+ expect(
+ eventStreamSettled([
+ { type: "message.completed" },
+ { type: "tool.completed" },
+ ]),
+ ).toBe(false);
+ expect(
+ eventStreamSettled([
+ { type: "message.completed" },
+ { type: "session.waiting" },
+ ]),
+ ).toBe(true);
+ });
});
describe("describe", () => {
@@ -184,6 +432,7 @@ describe("sourcesOf", () => {
describe("pendingQuestion", () => {
const request = {
requestId: "req_1",
+ kind: "question",
prompt: "Which one?",
options: [{ id: "a", label: "The first" }],
};
@@ -194,6 +443,7 @@ describe("pendingQuestion", () => {
{
type: "dynamic-tool",
toolName: "ask_question",
+ state: "approval-requested",
toolMetadata: { eve: { inputRequest: request } },
},
]),
@@ -207,6 +457,7 @@ describe("pendingQuestion", () => {
{
type: "dynamic-tool",
toolName: "ask_question",
+ state: "approval-requested",
toolMetadata: { eve: { inputRequest: request } },
},
]);
@@ -215,11 +466,87 @@ describe("pendingQuestion", () => {
expect(pendingQuestion([asked, answered])).toBeNull();
});
+ it("ignores a question that already has a response", () => {
+ expect(
+ pendingQuestion([
+ message([
+ {
+ type: "dynamic-tool",
+ toolName: "ask_question",
+ state: "approval-responded",
+ toolMetadata: { eve: { inputRequest: request } },
+ },
+ ]),
+ ]),
+ ).toBeNull();
+ });
+
it("finds nothing in an empty transcript", () => {
expect(pendingQuestion([])).toBeNull();
});
});
+describe("latestTurnFailure", () => {
+ it("recognizes the Vercel Gateway free-tier rate limit", () => {
+ expect(
+ latestTurnFailure([
+ {
+ type: "turn.failed",
+ data: {
+ code: "MODEL_CALL_FAILED",
+ message:
+ "GatewayRateLimitError: Free tier requests on this model are rate-limited.",
+ },
+ },
+ ]),
+ ).toEqual({ code: "MODEL_CALL_FAILED", kind: "rate-limit" });
+ });
+
+ it("does not keep an earlier failure after a later turn completes", () => {
+ expect(
+ latestTurnFailure([
+ { type: "turn.failed", data: { message: "Provider unavailable" } },
+ { type: "turn.completed", data: {} },
+ { type: "session.waiting", data: {} },
+ ]),
+ ).toBeNull();
+ });
+
+ it("clears an earlier failure when a retry starts", () => {
+ expect(
+ latestTurnFailure([
+ { type: "turn.failed", data: { message: "Provider unavailable" } },
+ { type: "turn.started", data: {} },
+ ]),
+ ).toBeNull();
+ });
+
+ it("recognizes a model restricted to paid Gateway credits", () => {
+ expect(
+ latestTurnFailure([
+ {
+ type: "session.failed",
+ data: {
+ code: "MODEL_CALL_FAILED",
+ message: "Free tier users do not have access to this model.",
+ },
+ },
+ ]),
+ ).toEqual({ code: "MODEL_CALL_FAILED", kind: "restricted" });
+ });
+
+ it("keeps provider details out of the display contract", () => {
+ expect(
+ latestTurnFailure([
+ {
+ type: "session.failed",
+ data: { message: "Internal provider stack and request body" },
+ },
+ ]),
+ ).toEqual({ code: "AGENT_FAILED", kind: "unknown" });
+ });
+});
+
describe("resolveThread", () => {
const rows = [
{ id: "c2", title: "Thursday" },
diff --git a/apps/app/test/api-proxy-response.spec.ts b/apps/app/test/api-proxy-response.spec.ts
new file mode 100644
index 00000000..3cb71b2d
--- /dev/null
+++ b/apps/app/test/api-proxy-response.spec.ts
@@ -0,0 +1,50 @@
+import { describe, expect, test } from "bun:test";
+import { gzipSync } from "node:zlib";
+import {
+ bufferedProxyResponse,
+ responseCanHaveBody,
+} from "../lib/api-proxy-response";
+
+describe("API proxy responses", () => {
+ test("does not attach a body where HTTP forbids one", async () => {
+ for (const [method, status] of [
+ ["HEAD", 200],
+ ["GET", 204],
+ ["GET", 205],
+ ["GET", 304],
+ ] as const) {
+ expect(responseCanHaveBody(method, status)).toBe(false);
+ const response = await bufferedProxyResponse(
+ new Response(null, { status }),
+ new Headers(),
+ method,
+ );
+ expect(response.body).toBeNull();
+ expect(response.status).toBe(status);
+ }
+ });
+
+ test("forwards non-success responses with their body", async () => {
+ const response = await bufferedProxyResponse(
+ Response.json({ error: "invalid" }, { status: 422 }),
+ new Headers({ "content-type": "application/json" }),
+ "POST",
+ );
+
+ expect(response.status).toBe(422);
+ expect(await response.json()).toEqual({ error: "invalid" });
+ });
+
+ test("decodes compressed upstream bodies after stripping encoding headers", async () => {
+ const response = await bufferedProxyResponse(
+ new Response(gzipSync("hello"), {
+ headers: { "content-encoding": "gzip" },
+ }),
+ new Headers({ "content-encoding": "gzip" }),
+ "GET",
+ );
+
+ expect(await response.text()).toBe("hello");
+ expect(response.headers.has("content-encoding")).toBe(false);
+ });
+});
diff --git a/apps/app/test/chat-date-group.spec.ts b/apps/app/test/chat-date-group.spec.ts
new file mode 100644
index 00000000..6670204c
--- /dev/null
+++ b/apps/app/test/chat-date-group.spec.ts
@@ -0,0 +1,17 @@
+import { describe, expect, test } from "bun:test";
+import { chatDateGroup } from "../lib/chat-date-group";
+
+describe("chat date groups", () => {
+ const now = Date.parse("2026-08-05T20:00:00.000Z");
+
+ test("uses deterministic UTC calendar buckets", () => {
+ expect(chatDateGroup("2026-08-05T00:00:00.000Z", now)).toBe("Today");
+ expect(chatDateGroup("2026-08-04T23:59:59.999Z", now)).toBe("Yesterday");
+ expect(chatDateGroup("2026-07-30T12:00:00.000Z", now)).toBe("Last 7 days");
+ expect(chatDateGroup("2026-07-28T23:59:59.999Z", now)).toBeNull();
+ });
+
+ test("does not group before a query has a stable timestamp", () => {
+ expect(chatDateGroup("2026-08-05T12:00:00.000Z", 0)).toBeNull();
+ });
+});
diff --git a/apps/app/test/chat-route.spec.ts b/apps/app/test/chat-route.spec.ts
new file mode 100644
index 00000000..a8c9a2ff
--- /dev/null
+++ b/apps/app/test/chat-route.spec.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from "bun:test";
+import { isSharedChatToken } from "../lib/chat-route";
+
+describe("chat routes", () => {
+ it("distinguishes private conversation ids from shared link tokens", () => {
+ expect(isSharedChatToken("cmsee2ntb0000govjsw7iayac")).toBe(false);
+ expect(isSharedChatToken("x".repeat(42))).toBe(false);
+ expect(isSharedChatToken("x".repeat(43))).toBe(true);
+ expect(isSharedChatToken(`${"x".repeat(42)}_`)).toBe(true);
+ expect(isSharedChatToken(`${"x".repeat(43)}.`)).toBe(false);
+ });
+});
diff --git a/apps/app/turbo.json b/apps/app/turbo.json
index d54c8fd2..cea0ca0e 100644
--- a/apps/app/turbo.json
+++ b/apps/app/turbo.json
@@ -27,6 +27,7 @@
"passThroughEnv": ["API_URL", "NEXT_PUBLIC_API_URL"]
},
"dev": {
+ "dependsOn": ["$TURBO_EXTENDS$"],
"cache": false,
"persistent": true,
"passThroughEnv": [
diff --git a/bun.lock b/bun.lock
index 432ca0d2..ef142184 100644
--- a/bun.lock
+++ b/bun.lock
@@ -79,6 +79,8 @@
"@crm/env": "workspace:*",
"@crm/telemetry": "workspace:*",
"@crm/ui": "workspace:*",
+ "@pierre/diffs": "^1.2.12",
+ "@pierre/trees": "^1.0.0-beta.5",
"@tanstack/react-query": "^5.101.2",
"@trpc/client": "^11.18.0",
"@trpc/server": "^11.18.0",
@@ -183,12 +185,12 @@
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
- "@shadcn/react": "^0.2.1",
+ "@shadcn/react": "^0.3.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
- "date-fns": "^4.4.0",
"lucide-react": "^1.28.0",
+ "motion": "^12.42.2",
"next-themes": "^0.4.6",
"nuqs": "^2.8.9",
"radix-ui": "^1.6.0",
@@ -560,6 +562,14 @@
"@paralleldrive/cuid2": ["@paralleldrive/[email protected]", "", { "dependencies": { "@noble/hashes": "^1.1.5" } }, "sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw=="],
+ "@pierre/diffs": ["@pierre/[email protected]", "", { "dependencies": { "@pierre/theme": "2.0.0", "@pierre/theming": "1.0.1", "@shikijs/transformers": "^3.0.0 || ^4.0.0", "diff": "9.0.0", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0 || ^4.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-6Dt48jQIL+H54QyNB943Oqn5p4uRw7NpiXLSEapnaYgYvTmSHNPAUCDfg6AcRC+W02z0IYJnJJvcs3lsNp7gCw=="],
+
+ "@pierre/theme": ["@pierre/[email protected]", "", {}, "sha512-yNDd9GYLQl1mEUJR8AneJ5e4ohLIHQd/wZLWr4fagt78vS2RwwZNW530vVgHqXFAyFVcFlRmGUD5ramXH46OXw=="],
+
+ "@pierre/theming": ["@pierre/[email protected]", "", { "peerDependencies": { "@pierre/theme": "^1.1.0 || ^2.0.0", "@shikijs/themes": "^3.0.0 || ^4.0.0", "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0", "shiki": "^3.0.0 || ^4.0.0" }, "optionalPeers": ["@pierre/theme", "@shikijs/themes", "react", "react-dom", "shiki"] }, "sha512-WCI5Qd7iprDpISL9fBYOLe8RV53+b7mFNA3bPzl60/2CKCSrsKN8zEcep6Y3BAzvARlmca50zGjDodqPGiTUKA=="],
+
+ "@pierre/trees": ["@pierre/[email protected]", "", { "dependencies": { "@pierre/theming": "1.0.0", "preact": "11.0.0-beta.0", "preact-render-to-string": "6.6.5" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-zxeuSFM9TveM7b5XofweJALCtm/tGYV9HZzdbf7Uf+kBxIlUyz24/EHaGRjB0dsmmfDQl2ETz7AWwJ15lhSnpw=="],
+
"@posthog/browser-common": ["@posthog/[email protected]", "", { "dependencies": { "@posthog/core": "^1.46.8", "@posthog/types": "^1.402.0" } }, "sha512-W9DCGVks15docUMPvJ2nd8NS16Gn74bsGWuaeg31beEKFSjdW8wvnQ1ETY6WSql5pYxZb3GdJmEUZVVstKSrBQ=="],
"@posthog/core": ["@posthog/[email protected]", "", { "dependencies": { "@posthog/types": "^1.401.1" } }, "sha512-WQTSwlFhsWk09xngTimHiTyhFU8QZHFZEGSm+6brY3acwYdvTLcTxpIhgl/qOCgn/XoqlCFTZqU1ldWLxNntfA=="],
@@ -752,7 +762,25 @@
"@sec-ant/readable-stream": ["@sec-ant/[email protected]", "", {}, "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg=="],
- "@shadcn/react": ["@shadcn/[email protected]", "", { "peerDependencies": { "@types/react": ">=19", "react": ">=19" }, "optionalPeers": ["@types/react", "react"] }, "sha512-5krgi3dRMKb5jH6a+qPzVJUy/54s0kKE4Rw4LjDfLqOdVQTWKUgxWf1kW8r912I0jX/Lzxqc+pgjkjWxUIK5BQ=="],
+ "@shadcn/react": ["@shadcn/[email protected]", "", { "peerDependencies": { "@types/react": ">=19", "react": ">=19" }, "optionalPeers": ["@types/react", "react"] }, "sha512-iKN0NuYe850VDHlxEfvppFrpa7CMV3zArTHusXlaSmeFeQhohGbIqclv6WwPTs/44I8EkXQpcuRt6sXEVKkWqQ=="],
+
+ "@shikijs/core": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/primitive": "4.4.2", "@shikijs/types": "4.4.2", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5", "hast-util-to-html": "^9.0.5" } }, "sha512-StyzbAyxg2/tBGf78gwbBkGyeQ73lf8UiJArFaQhTQIDqQOCKPCQFanvrs4/Yv3Yfyc+ONInJM6K+FMIf+P+kA=="],
+
+ "@shikijs/engine-javascript": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "4.4.2", "@shikijs/vscode-textmate": "^10.0.2", "oniguruma-to-es": "^4.3.6" } }, "sha512-MnIkeqWdVPUWsxlx8gKLVCJFTsqrQJgpTPBPpQwaFeJ56lOnJxj5aN2LUFnfxUEcvOQuNocmbaMnVrCEln6rkw=="],
+
+ "@shikijs/engine-oniguruma": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "4.4.2", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-GLhowz1+jixjz+wiZ3wMnOn1jTxiFCGl2PkXufivbnwPHKuyw1AYqu5/hbWhZZ2oAb0NP05WUJhYeigY14drnw=="],
+
+ "@shikijs/langs": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "4.4.2" } }, "sha512-8DfeusD+Zdv/eYIDdXyJTUnSMHt+aAWjAOCXV20HNGAHRlInXpG8wh421v6B91WOm9TFwRLN+b/LG5F2NAIojg=="],
+
+ "@shikijs/primitive": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "4.4.2", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5" } }, "sha512-l6fQQKsOMlz72n38fztmSgZ76MO6KSWuw8o+GJ+FhmqrpC9pIOJNQNXGgbb5yX2AwpzlEHwsaLPnk/8o4Fm+rA=="],
+
+ "@shikijs/themes": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/types": "4.4.2" } }, "sha512-H0CFoL07ddDC2Dd6EdrPYNkRhUR6YCkJlnuYFceYYUJJA5TIm2b5B33qqiDYryBExgbKMndFJPb2u1gTuqO37g=="],
+
+ "@shikijs/transformers": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/core": "4.4.2", "@shikijs/types": "4.4.2" } }, "sha512-d81PJ9KkR1tVP95FH/9296HTtDo0mh76wv10u9T1YmsZq/UcXgt0OLdBszfUQ1i+umkRMCjDnFbFZU7/tCODTQ=="],
+
+ "@shikijs/types": ["@shikijs/[email protected]", "", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5" } }, "sha512-PFYitV4vpDr/iPCIhnHp+Q4ftic5N5VeNJ3KQ1O8gn3h2ar8qgwMAXF7tq4m1CWaMS60fV4VqF6vfnWH4F7vqQ=="],
+
+ "@shikijs/vscode-textmate": ["@shikijs/[email protected]", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="],
"@sindresorhus/merge-streams": ["@sindresorhus/[email protected]", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="],
@@ -1440,6 +1468,8 @@
"forwarded": ["[email protected]", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="],
+ "framer-motion": ["[email protected]", "", { "dependencies": { "motion-dom": "^12.43.0", "motion-utils": "^12.39.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-1eaL3RvR/kAlbG7UYcpMptEyzPoENO0c6w7ZnB3/hh2vSAz/6uGAFn6fdoqTBguNstf3MsFhJHsD/0DHiclG+g=="],
+
"fresh": ["[email protected]", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],
"fs-constants": ["[email protected]", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
@@ -1506,6 +1536,8 @@
"hast-util-sanitize": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "unist-util-position": "^5.0.0" } }, "sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg=="],
+ "hast-util-to-html": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-whitespace": "^3.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "stringify-entities": "^4.0.0", "zwitch": "^2.0.4" } }, "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw=="],
+
"hast-util-to-jsx-runtime": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
"hast-util-to-parse5": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "web-namespaces": "^2.0.0", "zwitch": "^2.0.0" } }, "sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA=="],
@@ -1694,6 +1726,8 @@
"lru.min": ["[email protected]", "", {}, "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA=="],
+ "lru_map": ["[email protected]", "", {}, "sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg=="],
+
"lucide-react": ["[email protected]", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-fARAFJULsGuDDydjp6+6blekG/sBIM29TerzLjc9bQUKAcEfrSc4ZQKb25KRz4OMKd87cZTb5dgq0w/T6KufVg=="],
"magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
@@ -1826,6 +1860,12 @@
"modern-tar": ["[email protected]", "", {}, "sha512-t9VmxaqrmANnEOBhpSDI6HD192Ge48k8vmWqQQL7hSFEqHEYwZbbsu49+aKLWZeRvFs3j1pMhXOqqF4kPlvjkQ=="],
+ "motion": ["[email protected]", "", { "dependencies": { "framer-motion": "^12.43.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-BQgQbSa9Hn3/mtbib0MK53y6JSANa+YKUKlaYnWzAVDH424RYQ5LVpV3pNiWH00BA2z4ojsSdMzqT7g2FQwjuQ=="],
+
+ "motion-dom": ["[email protected]", "", { "dependencies": { "motion-utils": "^12.39.0" } }, "sha512-azKON4d9S65PEoFUiQTMTgPheEmzf2QngdRc50AKfJp9Q9mmcBVw22c8eMq9k8kxOFHdL7+WZY7N/5F/lwiDag=="],
+
+ "motion-utils": ["[email protected]", "", {}, "sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ=="],
+
"ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"multer": ["[email protected]", "", { "dependencies": { "append-field": "^1.0.0", "busboy": "^1.6.0", "concat-stream": "^2.0.0", "type-is": "^1.6.18" } }, "sha512-6rdyFg2kLrMh9Jee7/BMPuV9lEAd7lLW2YUpF9/YxR7njyoUwwQ0ZPh3TaIY50Sw6vlyD2HW3wGOkTS4P79xrQ=="],
@@ -1886,6 +1926,10 @@
"onetime": ["[email protected]", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="],
+ "oniguruma-parser": ["[email protected]", "", {}, "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw=="],
+
+ "oniguruma-to-es": ["[email protected]", "", { "dependencies": { "oniguruma-parser": "^0.12.2", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA=="],
+
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
"ora": ["[email protected]", "", { "dependencies": { "chalk": "^5.3.0", "cli-cursor": "^5.0.0", "cli-spinners": "^2.9.2", "is-interactive": "^2.0.0", "is-unicode-supported": "^2.0.0", "log-symbols": "^6.0.0", "stdin-discarder": "^0.2.2", "string-width": "^7.2.0", "strip-ansi": "^7.1.0" } }, "sha512-weP+BZ8MVNnlCm8c0Qdc1WSWq4Qn7I+9CJGm7Qali6g44e/PUzbjNqJX5NJ9ljlNMosfJvg1fKEGILklK9cwnw=="],
@@ -1980,7 +2024,9 @@
"powershell-utils": ["[email protected]", "", {}, "sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A=="],
- "preact": ["[email protected]", "", { "peerDependencies": { "preact-render-to-string": ">=5" }, "optionalPeers": ["preact-render-to-string"] }, "sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q=="],
+ "preact": ["[email protected]", "", {}, "sha512-IcODoASASYwJ9kxz7+MJeiJhvLriwSb4y4mHIyxdgaRZp6kPUud7xytrk/6GZw8U3y6EFJaRb5wi9SrEK+8+lg=="],
+
+ "preact-render-to-string": ["[email protected]", "", { "peerDependencies": { "preact": ">=10 || >= 11.0.0-0" } }, "sha512-O6MHzYNIKYaiSX3bOw0gGZfEbOmlIDtDfWwN1JJdc/T3ihzRT6tGGSEWE088dWrEDGa1u7101q+6fzQnO9XCPA=="],
"prebuild-install": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.0", "expand-template": "^2.0.3", "github-from-package": "0.0.0", "minimist": "^1.2.3", "mkdirp-classic": "^0.5.3", "napi-build-utils": "^2.0.0", "node-abi": "^3.3.0", "pump": "^3.0.0", "rc": "^1.2.7", "simple-get": "^4.0.0", "tar-fs": "^2.0.0", "tunnel-agent": "^0.6.0" }, "bin": { "prebuild-install": "bin.js" } }, "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug=="],
@@ -2056,6 +2102,12 @@
"reflect-metadata": ["[email protected]", "", {}, "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q=="],
+ "regex": ["[email protected]", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg=="],
+
+ "regex-recursion": ["[email protected]", "", { "dependencies": { "regex-utilities": "^2.3.0" } }, "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg=="],
+
+ "regex-utilities": ["[email protected]", "", {}, "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng=="],
+
"regexp-to-ast": ["[email protected]", "", {}, "sha512-tlbJqcMHnPKI9zSrystikWKwHkBqu2a/Sgw01h3zFjvYrMxEDYHzzoMZnUrbIfpTFEsoRnnviOXNCzFiSc54Qw=="],
"rehype-harden": ["[email protected]", "", { "dependencies": { "unist-util-visit": "^5.0.0" } }, "sha512-Qn7vR1xrf6fZCrkm9TDWi/AB4ylrHy+jqsNm1EHOAmbARYA6gsnVJBq/sdBh6kmT4NEZxH5vgIjrscefJAOXcw=="],
@@ -2144,6 +2196,8 @@
"shell-quote": ["[email protected]", "", {}, "sha512-Iov+JwFv/2HcTpcwNMKd8+IWNb8tboQJNQTkAY/LLVK7gGH9jy+LGkVqPxfekHl+yMmiqXszdGWXgkfml7hjqA=="],
+ "shiki": ["[email protected]", "", { "dependencies": { "@shikijs/core": "4.4.2", "@shikijs/engine-javascript": "4.4.2", "@shikijs/engine-oniguruma": "4.4.2", "@shikijs/langs": "4.4.2", "@shikijs/themes": "4.4.2", "@shikijs/types": "4.4.2", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.5" } }, "sha512-P8F/dFhRevaw2uSdeIYlq/5SXZNY85DPtmXQ947gD1Zj2JqO5AkNvVVBar0Me9JkFx3uzVud/qOtP5ek9NEQGA=="],
+
"side-channel": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4", "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ=="],
"side-channel-list": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="],
@@ -2466,6 +2520,10 @@
"@paralleldrive/cuid2/@noble/hashes": ["@noble/[email protected]", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="],
+ "@pierre/diffs/diff": ["[email protected]", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="],
+
+ "@pierre/trees/@pierre/theming": ["@pierre/[email protected]", "", { "peerDependencies": { "@pierre/theme": "^1.1.0", "@shikijs/themes": "^3.0.0 || ^4.0.0", "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0", "shiki": "^3.0.0 || ^4.0.0" }, "optionalPeers": ["@pierre/theme", "@shikijs/themes", "react", "react-dom", "shiki"] }, "sha512-WsdrnhKfjeyXGDikZmN9pkpeZ5S/cl6EE72feiSc0tlynT1tMYqXqouhuv/foK+PY9OEnebOAVRQn3+rAstR8g=="],
+
"@prisma/engines/@prisma/get-platform": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/debug": "7.9.1" } }, "sha512-PK8R60YZRQvYxBrGG9i7l2/rFyzy+2MuI1dKtmtrCqPH8YpiJx/MfiC7LRzX5786rZDEv7BngcjfIJW4/9ADuw=="],
"@prisma/fetch-engine/@prisma/get-platform": ["@prisma/[email protected]", "", { "dependencies": { "@prisma/debug": "7.9.1" } }, "sha512-PK8R60YZRQvYxBrGG9i7l2/rFyzy+2MuI1dKtmtrCqPH8YpiJx/MfiC7LRzX5786rZDEv7BngcjfIJW4/9ADuw=="],
@@ -2718,6 +2776,8 @@
"pg-types/postgres-array": ["[email protected]", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="],
+ "posthog-js/preact": ["[email protected]", "", { "peerDependencies": { "preact-render-to-string": ">=5" }, "optionalPeers": ["preact-render-to-string"] }, "sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q=="],
+
"prompts/kleur": ["[email protected]", "", {}, "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w=="],
"prop-types/react-is": ["[email protected]", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],
diff --git a/packages/ui/package.json b/packages/ui/package.json
index fbb368a8..504419a2 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -23,12 +23,12 @@
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
- "@shadcn/react": "^0.2.1",
+ "@shadcn/react": "^0.3.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
- "date-fns": "^4.4.0",
"lucide-react": "^1.28.0",
+ "motion": "^12.42.2",
"next-themes": "^0.4.6",
"nuqs": "^2.8.9",
"radix-ui": "^1.6.0",
diff --git a/packages/ui/src/components/async-action.tsx b/packages/ui/src/components/async-action.tsx
new file mode 100644
index 00000000..faaaab7a
--- /dev/null
+++ b/packages/ui/src/components/async-action.tsx
@@ -0,0 +1,192 @@
+"use client";
+
+import { CircleAlertIcon, CheckIcon } from "lucide-react";
+import { domAnimation, LazyMotion, m, useReducedMotion } from "motion/react";
+import {
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
+import { Spinner } from "@crm/ui/components/spinner";
+
+const TRANSITION = {
+ type: "spring",
+ stiffness: 520,
+ damping: 34,
+ mass: 0.45,
+} as const;
+
+const INSTANT = { duration: 0 } as const;
+
+export type AsyncActionStatus = "idle" | "pending" | "success" | "error";
+
+export type UseAsyncActionOptions<TArgs extends unknown[], TResult> = {
+ action: (...args: TArgs) => TResult | Promise<TResult>;
+ resetAfter?: number;
+ onSuccess?: (result: TResult) => void;
+ onError?: (error: unknown) => void;
+};
+
+export function useAsyncAction<TArgs extends unknown[], TResult>({
+ action,
+ resetAfter = 1400,
+ onSuccess,
+ onError,
+}: UseAsyncActionOptions<TArgs, TResult>) {
+ const [status, setStatus] = useState<AsyncActionStatus>("idle");
+ const phase = useRef<AsyncActionStatus>("idle");
+ const runId = useRef(0);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const alive = useRef(true);
+
+ const clear = useCallback(() => {
+ if (timer.current) {
+ clearTimeout(timer.current);
+ timer.current = null;
+ }
+ }, []);
+
+ const reset = useCallback(() => {
+ runId.current += 1;
+ clear();
+ phase.current = "idle";
+ setStatus("idle");
+ }, [clear]);
+
+ const run = useCallback(
+ (...args: TArgs) => {
+ if (phase.current === "pending") return;
+
+ clear();
+ const id = ++runId.current;
+ phase.current = "pending";
+ setStatus("pending");
+
+ const settle = (next: "success" | "error") => {
+ if (!alive.current || id !== runId.current) return;
+ clear();
+ phase.current = next;
+ setStatus(next);
+ timer.current = setTimeout(() => {
+ if (!alive.current || id !== runId.current) return;
+ phase.current = "idle";
+ setStatus("idle");
+ }, resetAfter);
+ };
+
+ Promise.resolve()
+ .then(() => action(...args))
+ .then(
+ (result) => {
+ settle("success");
+ onSuccess?.(result);
+ },
+ (error: unknown) => {
+ settle("error");
+ onError?.(error);
+ },
+ );
+ },
+ [action, clear, onError, onSuccess, resetAfter],
+ );
+
+ useEffect(() => {
+ alive.current = true;
+ return () => {
+ alive.current = false;
+ clear();
+ };
+ }, [clear]);
+
+ return {
+ status,
+ run,
+ reset,
+ pending: status === "pending",
+ };
+}
+
+export type AsyncButtonContentProps = {
+ status: AsyncActionStatus;
+ children: ReactNode;
+ pendingLabel: ReactNode;
+ successLabel?: ReactNode;
+ errorLabel?: ReactNode;
+};
+
+export function AsyncButtonContent({
+ status,
+ children,
+ pendingLabel,
+ successLabel = "Done",
+ errorLabel = "Try again",
+}: AsyncButtonContentProps) {
+ const reduced = useReducedMotion() === true;
+ const states: Array<{ status: AsyncActionStatus; content: ReactNode }> = [
+ { status: "idle", content: children },
+ {
+ status: "pending",
+ content: (
+ <>
+ <Spinner data-icon="inline-start" aria-hidden />
+ {pendingLabel}
+ </>
+ ),
+ },
+ {
+ status: "success",
+ content: (
+ <>
+ <CheckIcon data-icon="inline-start" aria-hidden />
+ {successLabel}
+ </>
+ ),
+ },
+ {
+ status: "error",
+ content: (
+ <>
+ <CircleAlertIcon data-icon="inline-start" aria-hidden />
+ {errorLabel}
+ </>
+ ),
+ },
+ ];
+
+ return (
+ <LazyMotion features={domAnimation}>
+ <span className="relative grid min-w-0 items-center justify-items-center">
+ {states.map((state) => {
+ const active = state.status === status;
+ return (
+ <m.span
+ key={state.status}
+ aria-hidden={!active}
+ className="col-start-1 row-start-1 inline-flex items-center justify-center gap-1.5 whitespace-nowrap"
+ initial={false}
+ animate={{
+ opacity: active ? 1 : 0,
+ scale: reduced || active ? 1 : 0.92,
+ filter: reduced || active ? "blur(0px)" : "blur(2px)",
+ }}
+ transition={reduced ? INSTANT : TRANSITION}
+ >
+ {state.content}
+ </m.span>
+ );
+ })}
+ <span role="status" aria-live="polite" className="sr-only">
+ {status === "pending"
+ ? pendingLabel
+ : status === "success"
+ ? successLabel
+ : status === "error"
+ ? errorLabel
+ : ""}
+ </span>
+ </span>
+ </LazyMotion>
+ );
+}
diff --git a/packages/ui/src/components/questionnaire.tsx b/packages/ui/src/components/questionnaire.tsx
new file mode 100644
index 00000000..10456641
--- /dev/null
+++ b/packages/ui/src/components/questionnaire.tsx
@@ -0,0 +1,314 @@
+"use client";
+
+import Checkmark from "@carbon/icons-react/es/Checkmark";
+import { Questionnaire as QuestionnairePrimitive } from "@shadcn/react/questionnaire";
+import type * as React from "react";
+import { buttonVariants, type Button } from "./button";
+import { Icon } from "./icon";
+import { cn } from "../lib/utils";
+
+function Questionnaire({
+ className,
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Root>) {
+ return (
+ <QuestionnairePrimitive.Root
+ data-slot="questionnaire"
+ className={cn("flex w-full min-w-0 flex-col gap-4", className)}
+ {...props}
+ />
+ );
+}
+
+function QuestionnaireProgress({
+ className,
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Progress>) {
+ return (
+ <QuestionnairePrimitive.Progress
+ data-slot="questionnaire-progress"
+ className={cn(
+ "min-h-[1lh] w-fit min-w-[14ch] font-medium text-muted-foreground text-xs tabular-nums",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function QuestionnaireItem({
+ className,
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Item>) {
+ return (
+ <QuestionnairePrimitive.Item
+ data-slot="questionnaire-item"
+ className={cn(
+ "flex min-w-0 flex-col gap-4 border-0 p-0 outline-none",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function QuestionnaireTitle({
+ className,
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Title>) {
+ return (
+ <QuestionnairePrimitive.Title
+ data-slot="questionnaire-title"
+ className={cn(
+ "text-pretty font-medium text-base leading-snug [&:not(:has(~[data-slot=questionnaire-description]))]:mb-4",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function QuestionnaireDescription({
+ className,
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Description>) {
+ return (
+ <QuestionnairePrimitive.Description
+ data-slot="questionnaire-description"
+ className={cn("text-pretty text-muted-foreground text-sm", className)}
+ {...props}
+ />
+ );
+}
+
+function QuestionnaireChoices({
+ className,
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Choices>) {
+ return (
+ <QuestionnairePrimitive.Choices
+ data-slot="questionnaire-choices"
+ className={cn(
+ "group/questionnaire-choices grid min-w-0 gap-2",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function QuestionnaireChoice({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Choice>) {
+ return (
+ <QuestionnairePrimitive.Choice
+ data-slot="questionnaire-choice"
+ className={cn(
+ "group/questionnaire-choice relative flex min-h-11 cursor-pointer select-none items-start gap-2.5 rounded-md border border-input bg-transparent px-3 py-2.5 text-start text-sm outline-none transition-colors hover:bg-muted/50 has-[>input:focus-visible]:border-ring has-[>input:focus-visible]:ring-3 has-[>input:focus-visible]:ring-ring/50 data-checked:border-primary/40 data-checked:bg-muted data-invalid:border-destructive data-disabled:pointer-events-none data-disabled:cursor-not-allowed data-disabled:opacity-50 dark:bg-input/20 dark:data-checked:bg-muted",
+ className,
+ )}
+ {...props}
+ >
+ <QuestionnairePrimitive.ChoiceInput
+ data-slot="questionnaire-choice-input"
+ className="absolute inset-0 z-10 size-full cursor-pointer opacity-0"
+ />
+ <span
+ aria-hidden="true"
+ data-slot="questionnaire-choice-indicator"
+ className="pointer-events-none relative flex size-4 shrink-0 items-center justify-center rounded-sm border border-input group-data-[type=radio]/questionnaire-choice:rounded-full group-data-checked/questionnaire-choice:border-primary group-data-checked/questionnaire-choice:bg-primary group-data-checked/questionnaire-choice:text-primary-foreground dark:bg-input/30 dark:group-data-checked/questionnaire-choice:bg-primary"
+ >
+ <span
+ data-slot="questionnaire-choice-indicator-dot"
+ className="hidden size-2 rounded-full bg-primary-foreground group-data-[type=checkbox]/questionnaire-choice:hidden group-data-checked/questionnaire-choice:block"
+ />
+ <Icon
+ icon={Checkmark}
+ motion="none"
+ data-slot="questionnaire-choice-indicator-check"
+ className="hidden group-data-[type=radio]/questionnaire-choice:hidden group-data-checked/questionnaire-choice:block"
+ />
+ </span>
+ <QuestionnairePrimitive.ChoiceLabel
+ data-slot="questionnaire-choice-label"
+ className="flex min-w-0 flex-1 flex-col gap-0.5 leading-snug"
+ >
+ {children}
+ </QuestionnairePrimitive.ChoiceLabel>
+ <QuestionnairePrimitive.ChoiceShortcut
+ data-slot="questionnaire-choice-shortcut"
+ className="pointer-events-none ms-auto mt-0.5 hidden size-5 shrink-0 items-center justify-center rounded-md border border-input bg-background font-mono font-medium text-[0.625rem] text-muted-foreground leading-none group-data-[shortcut]/questionnaire-choice:inline-flex"
+ />
+ </QuestionnairePrimitive.Choice>
+ );
+}
+
+function QuestionnaireInput({
+ className,
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Input>) {
+ return (
+ <div
+ data-slot="questionnaire-input-wrapper"
+ className="group/questionnaire-input relative w-full min-w-0"
+ >
+ <QuestionnairePrimitive.Input
+ data-slot="questionnaire-input"
+ className={cn(
+ "h-8 min-h-11 w-full min-w-0 rounded-md border border-input bg-transparent px-2.5 py-1 text-base outline-none transition-[color,box-shadow,background-color] focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 sm:min-h-0 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
+ "selection:bg-primary selection:text-primary-foreground placeholder:text-muted-foreground",
+ className,
+ )}
+ {...props}
+ />
+ </div>
+ );
+}
+
+function QuestionnaireError({
+ className,
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Error>) {
+ return (
+ <QuestionnairePrimitive.Error
+ data-slot="questionnaire-error"
+ className={cn("text-destructive text-sm", className)}
+ {...props}
+ />
+ );
+}
+
+function QuestionnaireActions({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="questionnaire-actions"
+ className={cn(
+ "grid min-h-11 w-full grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-2 sm:min-h-8",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function QuestionnairePrevious({
+ children,
+ className,
+ size = "default",
+ variant = "outline",
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Previous> &
+ Pick<React.ComponentProps<typeof Button>, "size" | "variant">) {
+ return (
+ <QuestionnairePrimitive.Previous
+ data-slot="questionnaire-previous"
+ data-size={size}
+ data-variant={variant}
+ className={cn(
+ buttonVariants({ size, variant }),
+ "col-start-1 row-start-1 min-h-11 justify-self-start sm:min-h-0",
+ className,
+ )}
+ {...props}
+ >
+ {children ?? "Previous"}
+ </QuestionnairePrimitive.Previous>
+ );
+}
+
+function QuestionnaireSkip({
+ children,
+ className,
+ size = "default",
+ variant = "outline",
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Skip> &
+ Pick<React.ComponentProps<typeof Button>, "size" | "variant">) {
+ return (
+ <QuestionnairePrimitive.Skip
+ data-slot="questionnaire-skip"
+ data-size={size}
+ data-variant={variant}
+ className={cn(
+ buttonVariants({ size, variant }),
+ "col-start-2 row-start-1 min-h-11 justify-self-end sm:min-h-0",
+ className,
+ )}
+ {...props}
+ >
+ {children ?? "Skip"}
+ </QuestionnairePrimitive.Skip>
+ );
+}
+
+function QuestionnaireNext({
+ children,
+ className,
+ size = "default",
+ variant = "default",
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Next> &
+ Pick<React.ComponentProps<typeof Button>, "size" | "variant">) {
+ return (
+ <QuestionnairePrimitive.Next
+ data-slot="questionnaire-next"
+ data-size={size}
+ data-variant={variant}
+ className={cn(
+ buttonVariants({ size, variant }),
+ "col-start-3 row-start-1 min-h-11 justify-self-end sm:min-h-0",
+ className,
+ )}
+ {...props}
+ >
+ {children ?? "Next"}
+ </QuestionnairePrimitive.Next>
+ );
+}
+
+function QuestionnaireSubmit({
+ children,
+ className,
+ size = "default",
+ variant = "default",
+ ...props
+}: React.ComponentProps<typeof QuestionnairePrimitive.Submit> &
+ Pick<React.ComponentProps<typeof Button>, "size" | "variant">) {
+ return (
+ <QuestionnairePrimitive.Submit
+ data-slot="questionnaire-submit"
+ data-size={size}
+ data-variant={variant}
+ className={cn(
+ buttonVariants({ size, variant }),
+ "col-start-3 row-start-1 min-h-11 justify-self-end sm:min-h-0",
+ className,
+ )}
+ {...props}
+ >
+ {children ?? "Submit"}
+ </QuestionnairePrimitive.Submit>
+ );
+}
+
+export {
+ Questionnaire,
+ QuestionnaireActions,
+ QuestionnaireChoice,
+ QuestionnaireChoices,
+ QuestionnaireDescription,
+ QuestionnaireError,
+ QuestionnaireInput,
+ QuestionnaireItem,
+ QuestionnaireNext,
+ QuestionnairePrevious,
+ QuestionnaireProgress,
+ QuestionnaireSkip,
+ QuestionnaireSubmit,
+ QuestionnaireTitle,
+};
diff --git a/packages/ui/src/components/reasoning.tsx b/packages/ui/src/components/reasoning.tsx
new file mode 100644
index 00000000..8d41f587
--- /dev/null
+++ b/packages/ui/src/components/reasoning.tsx
@@ -0,0 +1,42 @@
+"use client";
+
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+} from "@crm/ui/components/accordion";
+import { Shimmer } from "@crm/ui/components/shimmer";
+import { cn } from "@crm/ui/lib/utils";
+import type { ReactNode } from "react";
+
+export function Reasoning({
+ children,
+ className,
+ isStreaming = false,
+ label = "Reasoning",
+}: {
+ children: ReactNode;
+ className?: string;
+ isStreaming?: boolean;
+ label?: string;
+}) {
+ return (
+ <Accordion
+ key={isStreaming ? "streaming" : "settled"}
+ type="single"
+ collapsible
+ defaultValue={isStreaming ? "reasoning" : undefined}
+ className={cn(className)}
+ >
+ <AccordionItem value="reasoning">
+ <AccordionTrigger variant="subtle">
+ {isStreaming ? <Shimmer>Thinking…</Shimmer> : label}
+ </AccordionTrigger>
+ <AccordionContent className="text-muted-foreground">
+ {children}
+ </AccordionContent>
+ </AccordionItem>
+ </Accordion>
+ );
+}
diff --git a/packages/ui/src/components/shimmer.tsx b/packages/ui/src/components/shimmer.tsx
new file mode 100644
index 00000000..87cf3727
--- /dev/null
+++ b/packages/ui/src/components/shimmer.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { cn } from "@crm/ui/lib/utils";
+import { motion, useReducedMotion } from "motion/react";
+import type { CSSProperties } from "react";
+
+export function Shimmer({
+ children,
+ className,
+ duration = 1,
+}: {
+ children: string;
+ className?: string;
+ duration?: number;
+}) {
+ const reduceMotion = useReducedMotion();
+
+ if (reduceMotion) {
+ return (
+ <span className={cn("text-muted-foreground", className)}>{children}</span>
+ );
+ }
+
+ return (
+ <motion.span
+ animate={{ backgroundPosition: "0% center" }}
+ initial={{ backgroundPosition: "100% center" }}
+ transition={{
+ duration,
+ ease: "linear",
+ repeat: Number.POSITIVE_INFINITY,
+ }}
+ className={cn(
+ "relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent",
+ "[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,no-repeat]",
+ className,
+ )}
+ style={
+ {
+ "--spread": `${children.length * 2}px`,
+ backgroundImage:
+ "var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))",
+ } as CSSProperties
+ }
+ >
+ {children}
+ </motion.span>
+ );
+}
diff --git a/packages/ui/src/components/skeleton-swap.tsx b/packages/ui/src/components/skeleton-swap.tsx
new file mode 100644
index 00000000..ce19974c
--- /dev/null
+++ b/packages/ui/src/components/skeleton-swap.tsx
@@ -0,0 +1,136 @@
+"use client";
+
+import { Skeleton } from "@crm/ui/components/skeleton";
+import { cn } from "@crm/ui/lib/utils";
+import { domAnimation, LazyMotion, m, useReducedMotion } from "motion/react";
+import {
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
+
+const CROSSFADE = {
+ type: "spring",
+ stiffness: 260,
+ damping: 34,
+ mass: 0.8,
+} as const;
+
+const INSTANT = { duration: 0 } as const;
+
+export type SkeletonSwapProps = {
+ loading: boolean;
+ children: ReactNode;
+ skeleton?: ReactNode;
+ delay?: number;
+ minVisible?: number;
+ label?: string;
+ className?: string;
+};
+
+export function SkeletonSwap({
+ loading,
+ children,
+ skeleton,
+ delay = 120,
+ minVisible = 380,
+ label,
+ className,
+}: SkeletonSwapProps) {
+ const [showSkeleton, setShowSkeleton] = useState(false);
+ const shownAt = useRef(0);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const reduced = useReducedMotion() === true;
+
+ const clear = useCallback(() => {
+ if (timer.current) {
+ clearTimeout(timer.current);
+ timer.current = null;
+ }
+ }, []);
+
+ const bind = useCallback(
+ (node: HTMLDivElement | null) => {
+ if (!node) return;
+ clear();
+
+ if (loading && !showSkeleton) {
+ timer.current = setTimeout(() => {
+ shownAt.current = performance.now();
+ setShowSkeleton(true);
+ }, delay);
+ return;
+ }
+
+ if (!loading && showSkeleton) {
+ const remaining = Math.max(
+ 0,
+ minVisible - (performance.now() - shownAt.current),
+ );
+ timer.current = setTimeout(() => setShowSkeleton(false), remaining);
+ }
+ },
+ [clear, delay, loading, minVisible, showSkeleton],
+ );
+
+ useEffect(() => clear, [clear]);
+
+ return (
+ <LazyMotion features={domAnimation}>
+ <div
+ ref={bind}
+ aria-busy={loading}
+ aria-label={label}
+ className={cn("relative grid min-w-0", className)}
+ >
+ <m.div
+ inert={showSkeleton ? true : undefined}
+ aria-hidden={showSkeleton}
+ className="col-start-1 row-start-1 min-w-0"
+ initial={false}
+ animate={{
+ opacity: showSkeleton ? 0 : 1,
+ scale: reduced || !showSkeleton ? 1 : 0.99,
+ filter: reduced || !showSkeleton ? "blur(0px)" : "blur(3px)",
+ }}
+ transition={reduced ? INSTANT : CROSSFADE}
+ style={{
+ transformOrigin: "top left",
+ pointerEvents: showSkeleton ? "none" : undefined,
+ }}
+ >
+ {children}
+ </m.div>
+ <m.div
+ aria-hidden
+ className="pointer-events-none col-start-1 row-start-1 min-w-0"
+ initial={false}
+ animate={{
+ opacity: showSkeleton ? 1 : 0,
+ filter: reduced || showSkeleton ? "blur(0px)" : "blur(3px)",
+ }}
+ transition={reduced ? INSTANT : CROSSFADE}
+ >
+ {skeleton ?? <DefaultSkeleton />}
+ </m.div>
+ {label ? (
+ <span role="status" aria-live="polite" className="sr-only">
+ {loading ? "" : `${label} loaded`}
+ </span>
+ ) : null}
+ </div>
+ </LazyMotion>
+ );
+}
+
+function DefaultSkeleton() {
+ return (
+ <div className="flex flex-col gap-2">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-11/12" />
+ <Skeleton className="h-4 w-8/12" />
+ </div>
+ );
+}