Comp AI CRM is an open source, CRM designed for AI agents. Agentic-first CRM.
TypeScript
fix(app): render agent transcript chronologically with anchored tool results (#92)
github-actions[bot]0e68e4590918
diff --git a/apps/app/components/agent-builder/agent-builder-chat.tsx b/apps/app/components/agent-builder/agent-builder-chat.tsxindex a4eaea97..de6e1398 100644--- a/apps/app/components/agent-builder/agent-builder-chat.tsx+++ b/apps/app/components/agent-builder/agent-builder-chat.tsx@@ -5,7 +5,6 @@ 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";@@ -19,7 +18,9 @@ import {AsyncButtonContent,useAsyncAction,} from "@crm/ui/components/async-action";+import { Badge } from "@crm/ui/components/badge";import { Button } from "@crm/ui/components/button";+import { DotMatrix } from "@crm/ui/components/dot-matrix";import { Icon } from "@crm/ui/components/icon";import { Markdown } from "@crm/ui/components/markdown";import {@@ -37,7 +38,7 @@ 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 { Fragment, type ReactNode, useState } from "react";import { toast } from "sonner";import {AgentClarificationComposer,@@ -55,16 +56,16 @@ import {latestCompletedArtifactVersionId,reviewVersionId,} from "@/lib/agent-builder-state";+import { toolLabel } from "@/lib/agent-tool-display";import {type AgentTurnFailure,conversationTimeline,- dealListResultOf,eventStreamSettled,latestTurnFailure,- mergeDealListResultPages,messagesFromEvents,pendingQuestion,splitMarkdownTable,+ type TranscriptItem,toTranscript,} from "@/lib/agent-transcript";import { isSharedChatToken } from "@/lib/chat-route";@@ -73,13 +74,17 @@ 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 {+ agentResultSkeleton,+ agentResultsByItem,+ hasAgentResult,+} from "./agent-result";import { AgentScopeBadges } from "./agent-scope-badges";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";@@ -87,6 +92,12 @@ type Conversation = RouterOutputs["conversations"]["builderById"];type SharedConversation = RouterOutputs["conversations"]["shared"];const BUILDER_STEPS = ["Scope", "Instructions", "Manifest", "Review"] as const;+const BUILDER_STEP_ARTIFACTS = [+ null,+ "agent/instructions.md",+ "agent/manifest.json",+ "agent/README.md",+] as const;type DraftVersion = {id: string;status: string;@@ -282,6 +293,11 @@ export function AgentBuilderChat({: [event],}))}+ onEnded={() =>+ setLiveStream((current) =>+ current?.key === streamKey ? null : current,+ )+ }/>) : null}<ChatHeader@@ -439,20 +455,23 @@ function BuilderEventFollower({sessionId,onSnapshot,onEvent,+ onEnded,}: {conversationId: string;sessionId: string;onSnapshot: (events: readonly MessageStreamEvent[]) => void;onEvent: (event: MessageStreamEvent) => void;+ onEnded: () => void;}) {useMountEffect(() => {const controller = new AbortController();- const session = new Client({+ const client = new Client({headers: { "x-crm-builder-conversation": conversationId },host: "",- }).session({ sessionId, streamIndex: 0 });+ });const follow = async () => {+ const session = client.session({ sessionId, streamIndex: 0 });const snapshot = await session.snapshot({ signal: controller.signal });if (controller.signal.aborted) return;onSnapshot(snapshot.events);@@ -466,11 +485,13 @@ function BuilderEventFollower({}};- void follow().catch((error: unknown) => {- if (!controller.signal.aborted) {- console.error(error);- }- });+ void follow()+ .catch((error: unknown) => {+ if (!controller.signal.aborted) console.error(error);+ })+ .finally(() => {+ if (!controller.signal.aborted) onEnded();+ });return () => controller.abort();});@@ -478,6 +499,40 @@ function BuilderEventFollower({return null;}+function withoutTable(text: string): string {+ const { before, after } = splitMarkdownTable(text);+ return [before, after].filter(Boolean).join("\n\n").trim();+}++function AgentToolStep({+ item,+}: {+ item: Extract<TranscriptItem, { kind: "did" }>;+}) {+ return (+ <div className="flex min-w-0 flex-col gap-1">+ <div className="flex min-w-0 items-start gap-2 text-sm">+ {item.pending ? (+ <DotMatrix decorative className="mt-0.5" />+ ) : 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">{toolLabel(item)}</span>+ </div>+ {item.errorText ? (+ <p className="pl-[22px] wrap-break-word text-destructive text-xs leading-5">+ {item.errorText}+ </p>+ ) : null}+ {hasAgentResult(item.tool) && item.pending+ ? agentResultSkeleton(item.tool)+ : null}+ </div>+ );+}+function appendEvent(events: readonly MessageStreamEvent[],event: MessageStreamEvent,@@ -707,130 +762,57 @@ function AssistantMessage({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";+ const results = agentResultsByItem(transcript.items);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}+ {transcript.items.map((item) => {+ if (item.kind === "reasoned") {+ return (+ <Reasoning+ key={item.id}+ isStreaming={item.streaming}+ label="Reasoning"+ >+ <Markdown className="wrap-break-word leading-5">+ {item.text}</Markdown>- );- }+ </Reasoning>+ );+ }- 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;- }+ if (item.kind === "did") {+ return (+ <Fragment key={item.id}>+ <AgentToolStep item={item} />+ {results.get(item.id)}+ </Fragment>+ );+ }++ if (item.kind === "said") {+ const text = results.size > 0 ? withoutTable(item.text) : item.text;+ if (!text) return null;++ return (+ <Markdown+ key={item.id}+ className="wrap-break-word text-sm leading-5"+ >+ {text}+ </Markdown>+ );+ }- return null;- })- )}+ return conversation === null ||+ answeredQuestionIds.has(item.question.requestId) ? (+ <FollowUpTranscriptItem+ key={item.id}+ question={item.question}+ answered={answeredQuestionIds.has(item.question.requestId)}+ />+ ) : null;+ })}{markdown ? (conversation ? (<ResponseActions@@ -974,80 +956,91 @@ function BuildingAgentCard({onError: () => toast.error("The agent could not be stopped. Try again."),});+ const writingPath =+ artifacts.find((artifact) => artifact.status === "WRITING")?.path ?? null;+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"- />+ <div className="w-full max-w-lg">+ <div className="overflow-hidden rounded-lg border bg-card">+ <div className="flex items-center gap-2 px-4 pt-4"><span className="min-w-0 flex-1 font-medium text-sm">Building the agent</span>- <span className="font-mono text-muted-foreground text-xs">+ <span className="shrink-0 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"- >+ <ol className="flex flex-col gap-1 p-3" aria-label="Agent creation">{BUILDER_STEPS.map((label, index) => {const done = index < completed;const active =index === completed && completed < BUILDER_STEPS.length;+ const artifact = BUILDER_STEP_ARTIFACTS[index];return (<likey={label}className={cn(- "flex min-h-9 min-w-0 items-center gap-3 rounded-md px-2.5 py-2",- active && "bg-background",+ "flex min-h-8 min-w-0 flex-col justify-center gap-1 rounded-md px-2",+ active && "bg-muted py-2",)}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>+ <div className="flex min-w-0 items-center gap-2">+ <span+ className={cn(+ "flex size-5 shrink-0 items-center justify-center font-mono text-xs",+ (done || active) && "text-ring",+ !done && !active && "text-muted-foreground",+ )}+ >+ {done ? (+ <Icon icon={Checkmark} className="size-3.5" />+ ) : active ? (+ <DotMatrix decorative />+ ) : (+ index + 1+ )}+ </span>+ <span+ className={cn(+ "min-w-0 flex-1 wrap-break-word text-sm",+ !done && !active && "text-muted-foreground",+ )}+ >+ {label}+ </span>+ <span+ className={cn(+ "shrink-0 text-xs",+ done && artifact && "font-mono",+ active ? "text-foreground" : "text-muted-foreground",+ )}+ >+ {done && artifact+ ? artifact.replace("agent/", "")+ : done+ ? "Done"+ : active+ ? "Working"+ : "Queued"}+ </span>+ </div>+ {active && writingPath ? (+ <p className="pl-7 font-mono text-muted-foreground text-xs">+ Writing {writingPath}+ </p>+ ) : null}</li>);})}</ol>- <footer className="flex min-h-12 items-center gap-3 bg-background/55 px-4 py-2.5">+ <footer className="flex items-center gap-2 border-t bg-muted px-4 py-3"><p className="min-w-0 flex-1 text-pretty text-muted-foreground text-xs">Runs in the background</p><Button- variant="ghost"+ variant="outline"size="sm"disabled={!sessionId || stop.pending}aria-busy={stop.pending}@@ -1145,47 +1138,67 @@ function ReviewAgentCard({<p className="max-w-[640px] text-pretty text-sm leading-5">Your private draft is ready to review.</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">- <AgentScopeBadges- scopes={manifest.access}- fallback="Bounded CRM read access"- />- </ReviewRow>- <p className="border-t px-4 py-2 text-pretty text-muted-foreground text-xs sm:px-5">- Runs in an isolated sandbox. CRM access is limited to the scopes- above, and credentials never enter the sandbox.- </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">- Review the draft before sharing it with your team.- </p>- <div className="sm:shrink-0">- <Button asChild>- <Link- href={workspaceUrl(`/agents/${agent.id}`)}- transitionTypes={["nav-forward"]}- >- View agent details- <Icon icon={ArrowRight} data-icon="inline-end" />- </Link>- </Button>- </div>+ <AgentCardShell name={manifest.name ?? agent.name} status="Private">+ <div className="flex flex-col gap-2 p-4">+ <ReviewRow label="When" value={manifest.trigger} />+ <ReviewRow label="Find" value={manifest.looksAt} />+ <ReviewRow label="Then" value={manifest.action} />+ <ReviewRow label="Scope">+ <AgentScopeBadges+ scopes={manifest.access}+ fallback="Bounded CRM read access"+ />+ </ReviewRow></div>+ <AgentCardFooter note="Sandboxed · credentials never enter the sandbox">+ <Button asChild size="sm">+ <Link+ href={workspaceUrl(`/agents/${agent.id}`)}+ transitionTypes={["nav-forward"]}+ >+ View details+ <Icon icon={ArrowRight} data-icon="inline-end" />+ </Link>+ </Button>+ </AgentCardFooter>+ </AgentCardShell>+ </div>+ );+}++function AgentCardShell({+ name,+ status,+ children,+}: {+ name: string;+ status: string;+ children: ReactNode;+}) {+ return (+ <div className="flex w-full max-w-lg flex-col overflow-hidden rounded-lg border bg-card">+ <div className="flex items-center gap-2 px-4 pt-4">+ <h2 className="min-w-0 flex-1 wrap-break-word font-medium text-sm">+ {name}+ </h2>+ <Badge variant="token">{status}</Badge></div>+ {children}+ </div>+ );+}++function AgentCardFooter({+ note,+ children,+}: {+ note: string;+ children: ReactNode;+}) {+ return (+ <div className="flex flex-col items-stretch gap-3 border-t bg-muted px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4">+ <p className="text-pretty text-muted-foreground text-xs">{note}</p>+ <div className="sm:shrink-0">{children}</div></div>);}@@ -1196,15 +1209,15 @@ function ReviewRow({children,}: {label: string;- value?: string;+ value?: ReactNode;children?: ReactNode;}) {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">+ <div className="flex flex-col gap-0.5 sm:flex-row sm:items-start sm:gap-4">+ <span className="text-muted-foreground text-sm leading-5 sm:w-16 sm:shrink-0">{label}</span>- <div className="min-w-0 flex-1 wrap-break-word font-medium text-sm">+ <div className="min-w-0 flex-1 wrap-break-word font-medium text-sm leading-5">{children ?? value}</div></div>@@ -1246,33 +1259,16 @@ function DeployedAgentCard({return (<div className="flex flex-col gap-[18px]">- <div className="space-y-1">+ <div className="flex flex-col gap-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 integrationaccess, 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+ <AgentCardShell name={agent.name} status="Live">+ <div className="flex flex-col gap-2 p-4">+ <ReviewRowlabel="Next run"value={nextRun ? (@@ -1290,39 +1286,37 @@ function DeployedAgentCard({)}/>- <DeployedStat- label="Execution"- value="Eve runtime · isolated sandbox"- />- <DeployedStat- label="Available to"- value="Everyone on the team"- last- />+ <ReviewRow label="Runs in" value="Eve runtime · isolated sandbox" />+ <ReviewRow label="Owner" value={`Team · ${agent.createdBy.name}`} /></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"+ <AgentCardFooter note="The chat stays private. The agent is team-owned.">+ <div className="flex items-center gap-2">+ <Button+ variant="outline"+ size="sm"+ disabled={runAction.pending}+ aria-busy={runAction.pending}+ onClick={() => runAction.run()}>- <Icon icon={Play} data-icon="inline-start" />- Run now- </AsyncButtonContent>- </Button>- </div>- </div>+ <AsyncButtonContent+ status={runAction.status}+ pendingLabel="Queueing"+ successLabel="Queued"+ errorLabel="Try again"+ >+ <Icon icon={Play} data-icon="inline-start" />+ Run now+ </AsyncButtonContent>+ </Button>+ <Button asChild size="sm">+ <Link href={workspaceUrl(`/agents/${agent.id}`)}>+ Open agent+ <Icon icon={ArrowRight} data-icon="inline-end" />+ </Link>+ </Button>+ </div>+ </AgentCardFooter>+ </AgentCardShell><div><p className="flex h-7 items-center text-muted-foreground text-sm">@@ -1351,30 +1345,6 @@ function DeployedAgentCard({);}-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 ChatUnavailable() {const workspaceUrl = useWorkspaceUrl();diff --git a/apps/app/components/agent-builder/agent-result.tsx b/apps/app/components/agent-builder/agent-result.tsxnew file mode 100644index 00000000..29ebcac4--- /dev/null+++ b/apps/app/components/agent-builder/agent-result.tsx@@ -0,0 +1,93 @@+import { Skeleton } from "@crm/ui/components/skeleton";+import type { ReactNode } from "react";+import { anchorResults } from "@/lib/agent-results";+import {+ type DealListResult,+ dealListResultOf,+ groupDealListPages,+ type TranscriptItem,+} from "@/lib/agent-transcript";+import { DealListResultTable } from "./deal-list-result";++type ResultEntry = {+ anchor: (items: readonly TranscriptItem[]) => Map<string, ReactNode[]>;+ skeleton: ReactNode;+};++function defineResult<T>({+ tool,+ validate,+ group,+ render,+ skeleton,+}: {+ tool: string;+ validate: (output: unknown) => T | null;+ group?: (+ results: readonly { itemId: string; value: T }[],+ ) => readonly { itemId: string; value: T }[];+ render: (result: T, key: string) => ReactNode;+ skeleton: ReactNode;+}): ResultEntry {+ return {+ skeleton,+ anchor: (items) => {+ const anchored = anchorResults({ items, tool, validate, group });+ const rendered = new Map<string, ReactNode[]>();++ for (const [itemId, values] of anchored) {+ rendered.set(+ itemId,+ values.map((value, index) =>+ render(value, `${tool}-${itemId}-${index}`),+ ),+ );+ }++ return rendered;+ },+ };+}++const listSkeleton = (+ <div className="flex flex-col gap-2 rounded-lg border bg-card p-4">+ <Skeleton className="h-4 w-40" />+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-2/3" />+ </div>+);++const REGISTRY: Record<string, ResultEntry> = {+ list_deals: defineResult<DealListResult>({+ tool: "list_deals",+ validate: dealListResultOf,+ group: groupDealListPages,+ render: (result, key) => <DealListResultTable key={key} result={result} />,+ skeleton: listSkeleton,+ }),+};++export function hasAgentResult(tool: string): boolean {+ return tool in REGISTRY;+}++export function agentResultSkeleton(tool: string): ReactNode {+ return REGISTRY[tool]?.skeleton ?? null;+}++export function agentResultsByItem(+ items: readonly TranscriptItem[],+): Map<string, ReactNode[]> {+ const rendered = new Map<string, ReactNode[]>();++ for (const entry of Object.values(REGISTRY)) {+ for (const [itemId, nodes] of entry.anchor(items)) {+ const bucket = rendered.get(itemId);+ if (bucket) bucket.push(...nodes);+ else rendered.set(itemId, nodes);+ }+ }++ return rendered;+}diff --git a/apps/app/components/agent-builder/agent-scope-badges.tsx b/apps/app/components/agent-builder/agent-scope-badges.tsxindex ac3bf0d2..7e30c874 100644--- a/apps/app/components/agent-builder/agent-scope-badges.tsx+++ b/apps/app/components/agent-builder/agent-scope-badges.tsx@@ -1,4 +1,17 @@import { Badge } from "@crm/ui/components/badge";+import GoogleLogo from "@crm/ui/components/brand-logos/google";+import SlackLogo from "@crm/ui/components/brand-logos/slack";+import CompLogo from "@crm/ui/components/logo";+import type { ComponentType, SVGProps } from "react";++const BRANDS: Array<{+ match: RegExp;+ Logo: ComponentType<SVGProps<SVGSVGElement>>;+}> = [+ { match: /\bcrm\b/i, Logo: CompLogo },+ { match: /\bslack\b/i, Logo: SlackLogo },+ { match: /\b(gmail|google)\b/i, Logo: GoogleLogo },+];export function AgentScopeBadges({scopes,@@ -12,17 +25,24 @@ export function AgentScopeBadges({return (<div className="flex min-w-0 flex-wrap gap-1">- {uniqueScopes.map((scope) => (- <Badge- key={scope}- variant="outline"- translate="no"- title={scope}- className="max-w-full rounded-sm text-ellipsis transition-colors focus-visible:ring-2"- >- {scope}- </Badge>- ))}+ {uniqueScopes.map((scope) => {+ const brand = BRANDS.find((candidate) => candidate.match.test(scope));++ return (+ <Badge+ key={scope}+ variant="token"+ translate="no"+ title={scope}+ className="max-w-full"+ >+ {brand ? (+ <brand.Logo aria-hidden="true" data-icon="inline-start" />+ ) : null}+ <span className="truncate">{scope}</span>+ </Badge>+ );+ })}</div>);}diff --git a/apps/app/lib/agent-results.ts b/apps/app/lib/agent-results.tsnew file mode 100644index 00000000..b70410b4--- /dev/null+++ b/apps/app/lib/agent-results.ts@@ -0,0 +1,36 @@+import type { TranscriptItem } from "./agent-transcript";++export type AnchoredResult<T> = { itemId: string; value: T };++export function anchorResults<T>({+ items,+ tool,+ validate,+ group,+}: {+ items: readonly TranscriptItem[];+ tool: string;+ validate: (output: unknown) => T | null;+ group?: (+ results: readonly AnchoredResult<T>[],+ ) => readonly AnchoredResult<T>[];+}): Map<string, T[]> {+ const valid: AnchoredResult<T>[] = [];++ for (const item of items) {+ if (item.kind !== "did" || item.tool !== tool || item.pending) continue;+ const value = validate(item.output);+ if (value !== null) valid.push({ itemId: item.id, value });+ }++ const anchored = group ? group(valid) : valid;+ const byAnchor = new Map<string, T[]>();++ for (const { itemId, value } of anchored) {+ const bucket = byAnchor.get(itemId);+ if (bucket) bucket.push(value);+ else byAnchor.set(itemId, [value]);+ }++ return byAnchor;+}diff --git a/apps/app/lib/agent-tool-display.ts b/apps/app/lib/agent-tool-display.tsnew file mode 100644index 00000000..90016b5b--- /dev/null+++ b/apps/app/lib/agent-tool-display.ts@@ -0,0 +1,41 @@+const ARTIFACT_NAMES: Record<string, string> = {+ "agent/instructions.md": "instructions",+ "agent/manifest.json": "the manifest",+ "agent/README.md": "the readme",+};++type LabelInput = {+ tool: string;+ input: Record<string, unknown> | null;+ label: string;+ pending: boolean;+};++const INPUT_LABELS: Record<+ string,+ (input: Record<string, unknown>, pending: boolean) => string | null+> = {+ write_agent_file: (input, pending) => {+ const path = typeof input.path === "string" ? input.path : null;+ if (!path) return null;+ const name = ARTIFACT_NAMES[path] ?? path;+ return pending ? `Writing ${name}` : `Wrote ${name}`;+ },+ save_agent_draft: (input, pending) => {+ const name = typeof input.name === "string" ? input.name.trim() : "";+ const verb = pending ? "Saving draft" : "Saved draft";+ return name ? `${verb} · ${name}` : verb;+ },+ set_chat_title: (input, pending) => {+ const title = typeof input.title === "string" ? input.title.trim() : "";+ const verb = pending ? "Naming this chat" : "Named this chat";+ return title ? `${verb} · ${title}` : verb;+ },+};++export function toolLabel(item: LabelInput): string {+ const fromInput = item.input+ ? INPUT_LABELS[item.tool]?.(item.input, item.pending)+ : null;+ return fromInput ?? item.label;+}diff --git a/apps/app/lib/agent-transcript.ts b/apps/app/lib/agent-transcript.tsindex cc985657..8c8ef744 100644--- a/apps/app/lib/agent-transcript.ts+++ b/apps/app/lib/agent-transcript.ts@@ -18,11 +18,13 @@ export type TranscriptItem =kind: "did";id: string;label: string;+ input: Record<string, unknown> | null;output: unknown;tone: Tone;pending: boolean;sources: Source[];tool: string;+ errorText: string | null;};export type Tone = "neutral" | "success" | "warning";@@ -239,7 +241,9 @@ export function toTranscript(kind: "did",id,label: describe(part),+ input: input(part),output: output(part),+ errorText: errorTextOf(part),tone: outcomeTone(part),pending:state === "input-streaming" ||@@ -382,6 +386,18 @@ function output(part: EveMessagePart): Record<string, unknown> | null {: null;}+function input(part: EveMessagePart): Record<string, unknown> | null {+ return "input" in part && part.input && typeof part.input === "object"+ ? (part.input as Record<string, unknown>)+ : null;+}++function errorTextOf(part: EveMessagePart): string | null {+ if (!("errorText" in part)) return null;+ const text = part.errorText;+ return typeof text === "string" && text.trim() ? text : null;+}+function recordOf(value: unknown): Record<string, unknown> {return value && typeof value === "object" && !Array.isArray(value)? (value as Record<string, unknown>)@@ -474,6 +490,34 @@ export function dealListResultOf(value: unknown): DealListResult | null {};}+export function groupDealListPages(+ pages: readonly { itemId: string; value: DealListResult }[],+): { itemId: string; value: DealListResult }[] {+ const groups = new Map<+ string,+ { itemId: string; value: DealListResult; order: number }+ >();++ for (const [index, page] of pages.entries()) {+ const key = JSON.stringify(page.value.criteria);+ const previous = groups.get(key);+ const [merged] = mergeDealListResultPages(+ previous ? [previous.value, page.value] : [page.value],+ );+ if (!merged) continue;++ groups.set(key, {+ itemId: page.itemId,+ value: merged,+ order: previous?.order ?? index,+ });+ }++ return [...groups.values()]+ .sort((left, right) => left.order - right.order)+ .map(({ itemId, value }) => ({ itemId, value }));+}+export function mergeDealListResultPages(results: readonly DealListResult[],): DealListResult[] {diff --git a/apps/app/test/agent-results.spec.ts b/apps/app/test/agent-results.spec.tsnew file mode 100644index 00000000..0e781baf--- /dev/null+++ b/apps/app/test/agent-results.spec.ts@@ -0,0 +1,125 @@+import { describe, expect, it } from "bun:test";+import { anchorResults } from "../lib/agent-results";+import {+ type DealListResult,+ dealListResultOf,+ groupDealListPages,+ type TranscriptItem,+} from "../lib/agent-transcript";++const page = (status: string, ids: string[]) => ({+ asOf: "2026-08-07T00:00:00.000Z",+ criteria: {+ status,+ inactiveForDays: null,+ companyId: null,+ ownerId: null,+ },+ deals: ids.map((id) => ({+ id,+ name: id,+ stage: "Discovery",+ amount: null,+ currency: "USD",+ company: { id: "c1", name: "Acme" },+ owner: null,+ daysSinceLastActivity: 3,+ expectedCloseDate: null,+ })),+});++const did = (+ id: string,+ output: unknown,+ extra: Partial<Extract<TranscriptItem, { kind: "did" }>> = {},+): TranscriptItem => ({+ kind: "did",+ id,+ label: "Listed deals",+ input: null,+ output,+ errorText: null,+ tone: "neutral",+ pending: false,+ sources: [],+ tool: "list_deals",+ ...extra,+});++const said = (id: string, text: string): TranscriptItem => ({+ kind: "said",+ id,+ mine: false,+ text,+});++const anchorDeals = (items: readonly TranscriptItem[]) =>+ anchorResults<DealListResult>({+ items,+ tool: "list_deals",+ validate: dealListResultOf,+ group: groupDealListPages,+ });++describe("anchorResults", () => {+ it("leaves a finished result under its own call when a pending one follows", () => {+ const anchored = anchorDeals([+ did("a", page("OPEN", ["d1"])),+ did("b", null, { pending: true, output: null }),+ ]);++ expect([...anchored.keys()]).toEqual(["a"]);+ });++ it("never anchors to a failed call", () => {+ const anchored = anchorDeals([+ did("a", page("OPEN", ["d1"])),+ did("b", { broken: true }, { tone: "warning", errorText: "Nope." }),+ ]);++ expect([...anchored.keys()]).toEqual(["a"]);+ });++ it("keeps two different criteria under their own calls", () => {+ const anchored = anchorDeals([+ did("a", page("OPEN", ["d1"])),+ said("t", "And the won ones:"),+ did("b", page("WON", ["d2"])),+ ]);++ expect([...anchored.keys()]).toEqual(["a", "b"]);+ expect(anchored.get("a")?.[0]?.criteria.status).toBe("OPEN");+ expect(anchored.get("b")?.[0]?.criteria.status).toBe("WON");+ });++ it("anchors paginated pages of one criteria to the final page", () => {+ const anchored = anchorDeals([+ did("a", page("OPEN", ["d1"])),+ did("b", page("OPEN", ["d2"])),+ ]);++ expect([...anchored.keys()]).toEqual(["b"]);+ expect(anchored.get("b")?.[0]?.deals.map((deal) => deal.id)).toEqual([+ "d1",+ "d2",+ ]);+ });++ it("anchors pagination to the last valid page, not a later failure", () => {+ const anchored = anchorDeals([+ did("a", page("OPEN", ["d1"])),+ did("b", page("OPEN", ["d2"])),+ did("c", { broken: true }),+ ]);++ expect([...anchored.keys()]).toEqual(["b"]);+ });++ it("ignores calls belonging to another tool", () => {+ const anchored = anchorDeals([+ did("a", page("OPEN", ["d1"]), { tool: "list_companies" }),+ ]);++ expect(anchored.size).toBe(0);+ });+});diff --git a/apps/app/test/agent-tool-display.spec.ts b/apps/app/test/agent-tool-display.spec.tsnew file mode 100644index 00000000..92fd7452--- /dev/null+++ b/apps/app/test/agent-tool-display.spec.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from "bun:test";+import { toolLabel } from "../lib/agent-tool-display";++const base = { label: "Ran a tool", pending: false };++describe("toolLabel", () => {+ it("names the artifact a builder file write produced", () => {+ expect(+ toolLabel({+ ...base,+ tool: "write_agent_file",+ input: { path: "agent/instructions.md" },+ pending: true,+ }),+ ).toBe("Writing instructions");+ });++ it("switches to the past tense once the write finished", () => {+ expect(+ toolLabel({+ ...base,+ tool: "write_agent_file",+ input: { path: "agent/manifest.json" },+ }),+ ).toBe("Wrote the manifest");+ });++ it("falls back to the raw path for an unmapped artifact", () => {+ expect(+ toolLabel({+ ...base,+ tool: "write_agent_file",+ input: { path: "agent/other.md" },+ }),+ ).toBe("Wrote agent/other.md");+ });++ it("labels the draft save under the tool the builder actually calls", () => {+ expect(+ toolLabel({+ ...base,+ tool: "save_agent_draft",+ input: { name: "Collections nudge" },+ }),+ ).toBe("Saved draft · Collections nudge");+ });++ it("keeps the generic label when the tool has no mapping", () => {+ expect(+ toolLabel({ ...base, tool: "web_search", input: { query: "acme" } }),+ ).toBe("Ran a tool");+ });++ it("keeps the generic label when the input is missing", () => {+ expect(toolLabel({ ...base, tool: "write_agent_file", input: null })).toBe(+ "Ran a tool",+ );+ });+});diff --git a/apps/app/test/agent-transcript.spec.ts b/apps/app/test/agent-transcript.spec.tsindex 09b4d006..147a9365 100644--- a/apps/app/test/agent-transcript.spec.ts+++ b/apps/app/test/agent-transcript.spec.ts@@ -660,3 +660,61 @@ describe("every tool has a line of English", () => {}});});++describe("tool call details", () => {+ it("keeps the tool input so the label can describe the work", () => {+ const [row] = toTranscript([+ message([+ tool("write_agent_file", {+ input: { path: "agent/manifest.json" },+ output: {},+ }),+ ]),+ ]);++ expect(row?.items[0]).toMatchObject({+ kind: "did",+ input: { path: "agent/manifest.json" },+ });+ });++ it("surfaces the failure text instead of dropping it", () => {+ const [row] = toTranscript([+ message([+ tool("write_agent_file", {+ state: "output-error",+ errorText: "Draft is closed.",+ }),+ ]),+ ]);++ expect(row?.items[0]).toMatchObject({+ kind: "did",+ errorText: "Draft is closed.",+ });+ });++ it("leaves errorText null when the call succeeded", () => {+ const [row] = toTranscript([+ message([tool("write_agent_file", { output: {} })]),+ ]);++ expect(row?.items[0]).toMatchObject({ kind: "did", errorText: null });+ });++ it("keeps text, tools and text in the order they happened", () => {+ const [row] = toTranscript([+ message([+ { type: "text", text: "Looking." },+ tool("write_agent_file", { input: { path: "a" }, output: {} }),+ { type: "text", text: "Done." },+ ]),+ ]);++ expect(row?.items.map((item) => item.kind)).toEqual([+ "said",+ "did",+ "said",+ ]);+ });+});diff --git a/packages/ui/src/components/badge.tsx b/packages/ui/src/components/badge.tsxindex ca36ed7c..b5d6737e 100644--- a/packages/ui/src/components/badge.tsx+++ b/packages/ui/src/components/badge.tsx@@ -20,6 +20,7 @@ const badgeVariants = cva("hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",link: "text-primary underline-offset-4 hover:underline",mono: "rounded-sm bg-muted font-mono font-normal text-muted-foreground",+ token: "rounded-sm border-border font-normal text-foreground",},},defaultVariants: {diff --git a/packages/ui/src/components/dot-matrix.tsx b/packages/ui/src/components/dot-matrix.tsxnew file mode 100644index 00000000..60e4a6d0--- /dev/null+++ b/packages/ui/src/components/dot-matrix.tsx@@ -0,0 +1,46 @@+import { cn } from "@crm/ui/lib/utils";++const GRID = 5;+const CELLS = Array.from({ length: GRID * GRID }, (_, index) => index);+const CENTER = (GRID - 1) / 2;+const CYCLE_MS = 1400;++function delayFor(index: number): number {+ const row = Math.floor(index / GRID);+ const column = index % GRID;+ const distance = Math.max(Math.abs(row - CENTER), Math.abs(column - CENTER));+ return (distance / CENTER) * (CYCLE_MS / 2);+}++export function DotMatrix({+ className,+ label = "Loading",+ decorative = false,+}: {+ className?: string;+ label?: string;+ decorative?: boolean;+}) {+ return (+ <span+ aria-hidden={decorative ? "true" : undefined}+ aria-label={decorative ? undefined : label}+ className={cn(+ "grid size-3.5 shrink-0 grid-cols-5 grid-rows-5 gap-px text-current",+ className,+ )}+ role={decorative ? undefined : "status"}+ >+ {CELLS.map((index) => (+ <span+ className="size-0.5 animate-pulse rounded-full bg-current opacity-20 motion-reduce:animate-none"+ key={index}+ style={{+ animationDelay: `${delayFor(index)}ms`,+ animationDuration: `${CYCLE_MS}ms`,+ }}+ />+ ))}+ </span>+ );+}diff --git a/packages/ui/src/components/logo.tsx b/packages/ui/src/components/logo.tsxindex 99c1726c..503c32dd 100644--- a/packages/ui/src/components/logo.tsx+++ b/packages/ui/src/components/logo.tsx@@ -7,8 +7,8 @@ const Logo = (props: React.SVGProps<SVGSVGElement>) => (height={512}viewBox="0 0 512 512"fill="none"- {...props}aria-label="Comp AI Logo"+ {...props}><pathd="m384 99.548 -16.066 -12.508L256.021 0 0 199.096v113.782L256.021 512 512 312.879V199.096zm-127.98 -49.419 79.695 61.975 -40.944 31.803 -3.661 2.837 -35.091 -27.287 -102.399 79.638 35.09 27.287 32.218 25.088 35.09 27.288L358.4 199.074l-35.047 -27.288 3.659 -2.837 40.943 -31.803 79.651 61.952 -40.943 31.852 -150.62 117.163 -79.695 -61.974 -32.218 -25.041 -38.752 -30.125 -40.922 -31.849z"