Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
tsx 368 lines 13.1 KB
Raw
1 'use client';
2
3 import { useState, type ComponentProps } from 'react';
4 import { useRouter } from 'next/navigation';
5 import ReactMarkdown, { type Components } from 'react-markdown';
6 import remarkGfm from 'remark-gfm';
7 import hljs from 'highlight.js';
8 import { Check, Copy, FileText, Search, Wrench } from 'lucide-react';
9
10 export type EagerSource = {
11 title: string;
12 url: string;
13 };
14
15 /**
16 * Renders eager docs search preview links while the assistant is thinking.
17 */
18 export function EagerSourcePreview({ active, sources }: { active?: boolean; sources: EagerSource[] }) {
19 const router = useRouter();
20 if (sources.length === 0) return null;
21
22 const base =
23 'flex flex-wrap items-center gap-x-2 gap-y-1 py-0.5 text-[11px] text-fd-muted-foreground';
24
25 return (
26 <div className={base}>
27 <span className="inline-flex shrink-0 items-center gap-1 text-fd-muted-foreground">
28 <Search className="size-3 text-[var(--composio-brand)]/70" aria-hidden="true" />
29 <span>{active ? 'Searching docs' : 'Searched docs'}</span>
30 </span>
31 {sources.map((source) => {
32 const href = source.url.startsWith('/') ? source.url : undefined;
33 const label = source.title || source.url;
34 if (!href) {
35 return (
36 <span key={source.url} className="truncate">
37 {label}
38 </span>
39 );
40 }
41
42 return (
43 <a
44 key={source.url}
45 href={href}
46 title={href}
47 onClick={(event) => {
48 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return;
49 event.preventDefault();
50 router.push(href);
51 }}
52 className="group inline-flex max-w-full items-center truncate underline-offset-2 transition-colors hover:text-fd-foreground hover:underline"
53 >
54 {label}
55 </a>
56 );
57 })}
58 </div>
59 );
60 }
61
62 /**
63 * Renders the agent's tool activity inline — which docs it searched and which
64 * pages it read — so you can see its "thinking". Returns null for non-tool parts.
65 */
66 export function ToolActivity({ part }: { part: unknown }) {
67 const router = useRouter();
68 const p = part as { type?: string; toolName?: string; input?: Record<string, unknown> };
69 const type = p.type ?? '';
70 const toolName = type === 'dynamic-tool' ? p.toolName : type.startsWith('tool-') ? type.slice(5) : undefined;
71 if (!toolName) return null;
72 const input = p.input ?? {};
73
74 let icon = <Wrench className="size-3" aria-hidden="true" />;
75 let label = `Running ${toolName}`;
76 let href: string | undefined;
77 if (toolName === 'search_docs') {
78 icon = <Search className="size-3" aria-hidden="true" />;
79 const query = typeof input.query === 'string' ? input.query : '';
80 label = query ? `Searched the docs for “${query}”` : 'Searched the docs';
81 } else if (toolName === 'read_doc') {
82 icon = <FileText className="size-3" aria-hidden="true" />;
83 const url = typeof input.url === 'string' ? input.url : '';
84 label = url ? `Read ${url}` : 'Read a page';
85 if (url.startsWith('/')) href = url;
86 }
87
88 const base = 'flex items-center gap-1.5 py-0.5 text-[11px] text-fd-muted-foreground';
89 const inner = (
90 <>
91 <span className="shrink-0 text-[var(--composio-brand)]/70">{icon}</span>
92 <span className="truncate group-hover:underline">{label}</span>
93 </>
94 );
95
96 if (href) {
97 return (
98 <a
99 href={href}
100 title={href}
101 onClick={(event) => {
102 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return;
103 event.preventDefault();
104 router.push(href);
105 }}
106 className={`${base} group cursor-pointer underline-offset-2 transition-colors hover:text-fd-foreground`}
107 >
108 {inner}
109 </a>
110 );
111 }
112 return <div className={base}>{inner}</div>;
113 }
114
115 function isInternalHref(url: string): boolean {
116 if (url.startsWith('/') || url.startsWith('#')) return true;
117 try {
118 return new URL(url).origin === window.location.origin;
119 } catch {
120 return false;
121 }
122 }
123
124 /**
125 * Link renderer for assistant Markdown. Internal docs links navigate
126 * client-side with the router and keep the chat open; external links open in a
127 * new tab. (Modifier-clicks fall through to the browser's default.)
128 */
129 function MarkdownLink({ href, children, node, ...props }: ComponentProps<'a'> & { node?: unknown }) {
130 const router = useRouter();
131 const url = href ?? '';
132 if (url && isInternalHref(url)) {
133 return (
134 <a
135 href={url}
136 onClick={(event) => {
137 if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return;
138 event.preventDefault();
139 router.push(url);
140 }}
141 {...props}
142 >
143 {children}
144 </a>
145 );
146 }
147 return (
148 <a href={url} target="_blank" rel="noreferrer" {...props}>
149 {children}
150 </a>
151 );
152 }
153
154 // Prose renders through react-markdown (we control link behavior and keys);
155 // code blocks render through the custom <CodeBlock> below (highlight.js,
156 // synchronous and browser-safe).
157 const MD_COMPONENTS: Components = { a: MarkdownLink };
158 const MD_PLUGINS = [remarkGfm];
159
160 // Map our fence languages to highlight.js language ids (some, like cURL, aren't
161 // registered grammars and fall back to a near match or auto-detection).
162 const HLJS_LANG: Record<string, string> = {
163 py: 'python',
164 ts: 'typescript', tsx: 'typescript',
165 js: 'javascript', jsx: 'javascript',
166 sh: 'bash', shell: 'bash', zsh: 'bash',
167 curl: 'bash', http: 'bash',
168 };
169
170 function hljsLangFor(lang: string): string | null {
171 const key = lang.toLowerCase();
172 const id = HLJS_LANG[key] ?? key;
173 return hljs.getLanguage(id) ? id : null;
174 }
175
176 /** Renders a code block with highlight.js token markup and a copy button. */
177 function CodeBlock({ lang, code, className }: { lang: string; code: string; className?: string }) {
178 const [copied, setCopied] = useState(false);
179 const id = hljsLangFor(lang);
180 // Use the known grammar when we have one, else auto-detect; never throw.
181 const html = id
182 ? hljs.highlight(code, { language: id, ignoreIllegals: true }).value
183 : hljs.highlightAuto(code).value;
184 return (
185 <div className={'eve-hljs group relative my-2 overflow-hidden rounded-md border border-fd-border bg-fd-muted/30 ' + (className ?? '')}>
186 <button
187 type="button"
188 aria-label="Copy code"
189 onClick={() => {
190 void navigator.clipboard.writeText(code).then(() => {
191 setCopied(true);
192 setTimeout(() => setCopied(false), 1500);
193 });
194 }}
195 className="absolute right-1.5 top-1.5 inline-flex size-6 items-center justify-center rounded text-fd-muted-foreground opacity-0 transition-opacity hover:bg-fd-accent hover:text-fd-foreground group-hover:opacity-100"
196 >
197 {copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
198 </button>
199 <pre className="max-w-full overflow-x-auto p-3 text-[11.5px] leading-relaxed">
200 <code
201 className={'hljs language-' + (id ?? lang)}
202 // highlight.js output is escaped token markup, not user HTML.
203 dangerouslySetInnerHTML={{ __html: html }}
204 />
205 </pre>
206 </div>
207 );
208 }
209
210 /**
211 * Renders an assistant message: Markdown via Streamdown, with consecutive
212 * code blocks in different languages (e.g. Python + TypeScript) grouped into
213 * tabs. Tolerates an unclosed trailing code fence while streaming.
214 */
215
216 const MD_CLASS =
217 'text-[13px] leading-relaxed break-words [&_a]:text-[var(--composio-brand)] [&_a]:underline [&_p]:my-2 [&_ul]:my-2 [&_ol]:my-2 [&_pre]:my-2 [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_pre]:text-[11.5px] [&_pre]:leading-relaxed [&_:not(pre)>code]:rounded [&_:not(pre)>code]:bg-fd-foreground/[0.07] [&_:not(pre)>code]:px-1 [&_:not(pre)>code]:py-0.5 [&_:not(pre)>code]:text-[0.9em]';
218
219 const LANG_LABEL: Record<string, string> = {
220 python: 'Python', py: 'Python',
221 typescript: 'TypeScript', ts: 'TypeScript', tsx: 'TypeScript',
222 javascript: 'JavaScript', js: 'JavaScript', jsx: 'JavaScript',
223 bash: 'Bash', sh: 'Shell', shell: 'Shell', zsh: 'Shell',
224 json: 'JSON', curl: 'cURL', http: 'HTTP', yaml: 'YAML',
225 };
226
227 function labelFor(lang: string): string {
228 const key = lang.toLowerCase();
229 return LANG_LABEL[key] ?? (lang ? lang[0].toUpperCase() + lang.slice(1) : 'Code');
230 }
231
232 /**
233 * Strip the model's native citation tokens. gpt-5.x emits web-search citations
234 * as `\uE200cite\uE202<ref>\uE201` (private-use delimiters). The refs (e.g.
235 * `turn0search0`) don't resolve here, so drop the span — unless it embeds a real
236 * URL, in which case keep it as a Markdown link. Real citations come through as
237 * normal Markdown links from the agent's instructions.
238 */
239 function cleanCitations(text: string): string {
240 return text
241 .replace(/\uE200[\s\S]*?\uE201/g, (span) => {
242 const url = span.match(/(https?:\/\/[^\s\uE200-\uE20F]+|\/[A-Za-z0-9/_#-]+)/);
243 return url ? ` ([source](${url[1]}))` : '';
244 })
245 .replace(/[\uE200-\uE20F]/g, '')
246 .replace(/[ \t]{2,}/g, ' ')
247 .replace(/[ \t]+([.,;:!?])/g, '$1');
248 }
249
250 type Seg = { kind: 'prose'; text: string } | { kind: 'code'; lang: string; code: string };
251
252 /** Split into prose and fenced-code segments, tolerating an unclosed trailing fence. */
253 function parseSegments(text: string): Seg[] {
254 const segs: Seg[] = [];
255 const fenceRe = /```([\w-]*)\n([\s\S]*?)```/g;
256 let last = 0;
257 let m: RegExpExecArray | null;
258 while ((m = fenceRe.exec(text)) !== null) {
259 if (m.index > last) segs.push({ kind: 'prose', text: text.slice(last, m.index) });
260 segs.push({ kind: 'code', lang: m[1] || '', code: m[2].replace(/\n+$/, '') });
261 last = m.index + m[0].length;
262 }
263 const rest = text.slice(last);
264 const open = /```([\w-]*)\n([\s\S]*)$/.exec(rest);
265 if (open) {
266 const before = rest.slice(0, open.index);
267 if (before.trim()) segs.push({ kind: 'prose', text: before });
268 segs.push({ kind: 'code', lang: open[1] || '', code: open[2] });
269 } else if (rest) {
270 segs.push({ kind: 'prose', text: rest });
271 }
272 return segs;
273 }
274
275 /** A prose segment that's just a short language label (e.g. "Python", "**TypeScript**"). */
276 function isThinLabel(text: string): boolean {
277 const t = text.trim();
278 if (t === '') return true;
279 if (t.length > 20) return false;
280 const plain = t.replace(/[*_`#>-]/g, '').trim().toLowerCase();
281 return /^(python|py|typescript|ts|tsx|javascript|js|bash|shell|sh|zsh|json|curl|http|yaml)$/.test(plain);
282 }
283
284 type Block = { lang: string; code: string };
285 type Group =
286 | { kind: 'prose'; text: string }
287 | { kind: 'code'; lang: string; code: string }
288 | { kind: 'tabs'; blocks: Block[] };
289
290 function group(segs: Seg[]): Group[] {
291 const out: Group[] = [];
292 let i = 0;
293 while (i < segs.length) {
294 const seg = segs[i];
295 if (seg.kind === 'prose') {
296 out.push(seg);
297 i++;
298 continue;
299 }
300 const blocks: Block[] = [{ lang: seg.lang, code: seg.code }];
301 let j = i + 1;
302 while (j < segs.length) {
303 const cur = segs[j];
304 const next = segs[j + 1];
305 if (cur.kind === 'prose' && isThinLabel(cur.text) && next && next.kind === 'code') {
306 blocks.push({ lang: next.lang, code: next.code });
307 j += 2;
308 } else if (cur.kind === 'code') {
309 blocks.push({ lang: cur.lang, code: cur.code });
310 j += 1;
311 } else {
312 break;
313 }
314 }
315 const distinct = new Set(blocks.map((b) => labelFor(b.lang)));
316 if (blocks.length >= 2 && distinct.size >= 2) out.push({ kind: 'tabs', blocks });
317 else for (const b of blocks) out.push({ kind: 'code', lang: b.lang, code: b.code });
318 i = j;
319 }
320 return out;
321 }
322
323 function CodeTabs({ blocks }: { blocks: Block[] }) {
324 const [active, setActive] = useState(0);
325 const items = blocks.map((b) => labelFor(b.lang));
326 const current = blocks[Math.min(active, blocks.length - 1)];
327 return (
328 <div className="my-2 overflow-hidden rounded-md border border-fd-border">
329 <div className="flex border-b border-fd-border bg-fd-muted/30">
330 {items.map((label, i) => (
331 <button
332 key={`${label}-${i}`}
333 type="button"
334 onClick={() => setActive(i)}
335 className={
336 'px-3 py-1.5 text-[12px] font-medium transition-colors ' +
337 (i === active
338 ? 'border-b-2 border-[var(--composio-brand)] text-fd-foreground'
339 : 'border-b-2 border-transparent text-fd-muted-foreground hover:text-fd-foreground')
340 }
341 >
342 {label}
343 </button>
344 ))}
345 </div>
346 <CodeBlock lang={current.lang} code={current.code} className="!my-0 rounded-none border-0" />
347 </div>
348 );
349 }
350
351 export function AssistantMessage({ text }: { text: string }) {
352 const groups = group(parseSegments(cleanCitations(text)));
353 return (
354 <div className="flex flex-col">
355 {groups.map((g, i) => {
356 if (g.kind === 'tabs') return <CodeTabs key={i} blocks={g.blocks} />;
357 if (g.kind === 'code') return <CodeBlock key={i} lang={g.lang} code={g.code} />;
358 return (
359 <div key={i} className={MD_CLASS}>
360 <ReactMarkdown remarkPlugins={MD_PLUGINS} components={MD_COMPONENTS}>
361 {g.text}
362 </ReactMarkdown>
363 </div>
364 );
365 })}
366 </div>
367 );
368 }