@devries-cameron20 / composio Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
tsx 319 lines 8.88 KB
Raw
1 "use client"
2
3 import { motion, useReducedMotion } from "motion/react"
4 import * as React from "react"
5
6 import { cn } from "@/lib/utils"
7
8 import { Message } from "./message"
9 import { BusyIndicator, ThinkingIndicator } from "../ui/thinking-indicator"
10 import { StreamText, estimateStreamDurationMs, type TextStreamMode } from "../ui/stream-text"
11
12 const SESSION_EASE = [0.23, 1, 0.32, 1] as const
13
14 function isSentPrompt(child: React.ReactNode) {
15 if (!React.isValidElement(child)) return false
16 return child.type === Message
17 }
18
19 function isThinkingIndicator(child: React.ReactNode) {
20 if (!React.isValidElement(child)) return false
21 return child.type === ThinkingIndicator || child.type === BusyIndicator
22 }
23
24 function isStreamText(child: React.ReactNode) {
25 if (!React.isValidElement(child)) return false
26 return child.type === StreamText
27 }
28
29 /** Tail lines (e.g. live thinking) skip the streaming queue and stay last. */
30 function isSessionTail(child: React.ReactNode) {
31 if (!React.isValidElement(child)) return false
32 return (child.props as { sessionTail?: boolean }).sessionTail === true
33 }
34
35 function sessionItemKey(resetKey: React.Key, index: number) {
36 return `${String(resetKey)}-${index}`
37 }
38
39 function usesManualSessionInset(child: React.ReactNode) {
40 if (!React.isValidElement(child)) return false
41 const props = child.props as {
42 "data-session-inset"?: string
43 sessionInset?: "manual"
44 }
45 return (
46 props["data-session-inset"] === "manual" || props.sessionInset === "manual"
47 )
48 }
49
50 function shouldApplySessionInset(child: React.ReactNode) {
51 if (isSentPrompt(child)) return false
52 if (isThinkingIndicator(child)) return false
53 if (usesManualSessionInset(child)) return false
54 return true
55 }
56
57 function getScrollContainer(node: HTMLElement | null) {
58 return node?.closest(".terminal-body-scroll") as HTMLElement | null
59 }
60
61 function getPauseAfter(child: React.ReactNode, fallbackMs: number) {
62 if (!React.isValidElement(child)) return fallbackMs
63
64 const props = child.props as {
65 sessionPause?: number
66 duration?: string
67 streaming?: boolean
68 steps?: unknown[]
69 name?: string
70 file?: string
71 children?: string
72 level?: string
73 }
74
75 if (typeof props.sessionPause === "number") return props.sessionPause
76
77 if (isStreamText(child)) {
78 const streamProps = child.props as {
79 mode?: TextStreamMode
80 speed?: number
81 children?: string
82 segmentDelay?: number
83 fadeDuration?: number
84 }
85 if (typeof streamProps.children === "string") {
86 return estimateStreamDurationMs(streamProps.children, {
87 mode: streamProps.mode,
88 speed: streamProps.speed,
89 segmentDelay: streamProps.segmentDelay,
90 fadeDuration: streamProps.fadeDuration,
91 })
92 }
93 }
94
95 if (typeof props.duration === "string") {
96 const match = props.duration.match(/([\d.]+)\s*s/)
97 if (match?.[1]) return Math.round(parseFloat(match[1]) * 1000)
98 }
99
100 if (props.streaming && Array.isArray(props.steps)) {
101 return props.steps.length * 420 + 240
102 }
103
104 if (props.streaming && props.name) return 820
105
106 if (typeof props.file === "string") return 520
107
108 if (props.streaming && typeof props.children === "string") {
109 const lines = props.children.split("\n").filter((line) => line.trim().length > 0)
110 return lines.length * 300 + 240
111 }
112
113 if (props.level) return 320
114
115 if (isSentPrompt(child)) return 280
116
117 return fallbackMs
118 }
119
120 export type SessionLineProps = {
121 children: React.ReactNode
122 className?: string
123 onReveal?: () => void
124 }
125
126 /** Animate a single session line on mount. */
127 export function SessionLine({
128 children,
129 className,
130 onReveal,
131 }: SessionLineProps) {
132 const reduceMotion = useReducedMotion()
133
134 React.useEffect(() => {
135 if (reduceMotion) onReveal?.()
136 }, [onReveal, reduceMotion])
137
138 if (reduceMotion) {
139 return <div className={className}>{children}</div>
140 }
141
142 return (
143 <motion.div
144 className={className}
145 initial={{ opacity: 0, y: 4 }}
146 animate={{ opacity: 1, y: 0 }}
147 transition={{
148 duration: 0.2,
149 ease: SESSION_EASE,
150 }}
151 onAnimationComplete={onReveal}
152 >
153 {children}
154 </motion.div>
155 )
156 }
157
158 export type SessionContentProps = {
159 children: React.ReactNode
160 className?: string
161 /** Fallback pause between items when streaming (seconds). */
162 stagger?: number
163 /** Seconds before the first streamed item appears. */
164 delay?: number
165 /** Change to replay the enter sequence. */
166 resetKey?: React.Key
167 /** Keep the scroll container pinned to the bottom as lines appear. */
168 autoScroll?: boolean
169 /** Reveal children one at a time like a live agent session. */
170 streaming?: boolean
171 }
172
173 /** Staggered enter animation for agent session content. */
174 export function SessionContent({
175 children,
176 className,
177 stagger = 0.45,
178 delay = 0,
179 resetKey = "session",
180 autoScroll = false,
181 streaming = false,
182 }: SessionContentProps) {
183 const reduceMotion = useReducedMotion()
184 const sessionRef = React.useRef<HTMLDivElement>(null)
185 const allItems = React.Children.toArray(children).filter(Boolean)
186 const bodyItems = allItems.filter((child) => !isSessionTail(child))
187 const tailItems = allItems.filter((child) => isSessionTail(child))
188 const itemsRef = React.useRef(bodyItems)
189 React.useEffect(() => {
190 itemsRef.current = bodyItems
191 })
192
193 const [revealedCount, setRevealedCount] = React.useState(0)
194
195 // Replay the staggered reveal when the reset key or body count changes.
196 const revealKey = `${String(resetKey)}:${bodyItems.length}:${streaming}:${reduceMotion}`
197 const [prevRevealKey, setPrevRevealKey] = React.useState(revealKey)
198 if (revealKey !== prevRevealKey) {
199 setPrevRevealKey(revealKey)
200 setRevealedCount(0)
201 }
202
203 const scrollToBottom = React.useCallback(
204 (behavior?: ScrollBehavior) => {
205 const scrollEl = getScrollContainer(sessionRef.current)
206 const resolved =
207 behavior ?? (reduceMotion || streaming ? "auto" : "smooth")
208 scrollEl?.scrollTo({ top: scrollEl.scrollHeight, behavior: resolved })
209 },
210 [reduceMotion, streaming]
211 )
212
213 React.useEffect(() => {
214 if (!streaming || reduceMotion) return
215
216 let cancelled = false
217 const timers: number[] = []
218
219 const showThrough = (count: number) => {
220 if (cancelled) return
221 setRevealedCount(count)
222 if (autoScroll) scrollToBottom(count === 1 ? "auto" : "smooth")
223 }
224
225 const revealFrom = (index: number) => {
226 if (cancelled || index >= itemsRef.current.length) return
227 showThrough(index + 1)
228
229 if (index + 1 >= itemsRef.current.length) return
230
231 const pause = getPauseAfter(itemsRef.current[index], stagger * 1000)
232 timers.push(window.setTimeout(() => revealFrom(index + 1), pause))
233 }
234
235 timers.push(
236 window.setTimeout(() => revealFrom(0), Math.max(0, delay * 1000))
237 )
238
239 return () => {
240 cancelled = true
241 timers.forEach((timer) => window.clearTimeout(timer))
242 }
243 }, [
244 streaming,
245 resetKey,
246 bodyItems.length,
247 delay,
248 stagger,
249 reduceMotion,
250 autoScroll,
251 scrollToBottom,
252 ])
253
254 React.useEffect(() => {
255 if (!autoScroll || streaming) return
256 scrollToBottom("auto")
257 }, [autoScroll, streaming, bodyItems.length, tailItems.length, resetKey, scrollToBottom])
258
259 // Pin to bottom while transcript height grows (StreamText typing, etc.).
260 React.useEffect(() => {
261 if (!autoScroll) return
262 const node = sessionRef.current
263 if (!node) return
264
265 const observer = new ResizeObserver(() => {
266 scrollToBottom(streaming ? "auto" : "smooth")
267 })
268 observer.observe(node)
269 return () => observer.disconnect()
270 }, [autoScroll, scrollToBottom, streaming, resetKey])
271
272 const handleLineReveal = React.useCallback(() => {
273 if (autoScroll) scrollToBottom()
274 }, [autoScroll, scrollToBottom])
275
276 const visibleBodyItems =
277 streaming && !reduceMotion ? bodyItems.slice(0, revealedCount) : bodyItems
278
279 const renderTailItems = () =>
280 tailItems.map((child, index) => (
281 <div
282 key={sessionItemKey(`${String(resetKey)}-tail`, index)}
283 className={shouldApplySessionInset(child) ? "terminal-session-inset" : undefined}
284 >
285 {child}
286 </div>
287 ))
288
289 if (reduceMotion) {
290 return (
291 <div ref={sessionRef} className={cn("terminal-session", className)}>
292 {visibleBodyItems.map((child, index) => (
293 <div
294 key={sessionItemKey(resetKey, index)}
295 className={shouldApplySessionInset(child) ? "terminal-session-inset" : undefined}
296 >
297 {child}
298 </div>
299 ))}
300 {renderTailItems()}
301 </div>
302 )
303 }
304
305 return (
306 <div ref={sessionRef} className={cn("terminal-session", className)}>
307 {visibleBodyItems.map((child, index) => (
308 <SessionLine
309 key={sessionItemKey(resetKey, index)}
310 className={shouldApplySessionInset(child) ? "terminal-session-inset" : undefined}
311 onReveal={autoScroll && !streaming ? handleLineReveal : undefined}
312 >
313 {child}
314 </SessionLine>
315 ))}
316 {renderTailItems()}
317 </div>
318 )
319 }