Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat: implement initial Chain of Thought (#7897)
Akarshan Biswasa2e05222a1b7
diff --git a/web-app/src/components/ai-elements/chain-of-thought.tsx b/web-app/src/components/ai-elements/chain-of-thought.tsxnew file mode 100644index 000000000..4c35cb632--- /dev/null+++ b/web-app/src/components/ai-elements/chain-of-thought.tsx@@ -0,0 +1,323 @@+/* eslint-disable react-refresh/only-export-components */+import { useControllableState } from '@radix-ui/react-use-controllable-state'+import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+} from '@/components/ui/collapsible'+import { cn } from '@/lib/utils'+import {+ SparklesIcon,+ ChevronDownIcon,+ CheckCircle2Icon,+ CircleDotIcon,+ CircleIcon,+ SearchIcon,+ ExternalLinkIcon,+} from 'lucide-react'+import type { ComponentProps, ReactNode } from 'react'+import {+ createContext,+ memo,+ useContext,+ useEffect,+ useMemo,+} from 'react'+import { Streamdown } from 'streamdown'+import { Shimmer } from './shimmer'++// ── Types ──────────────────────────────────────────────────────────────────++export type ChainOfThoughtStepStatus = 'complete' | 'active' | 'pending'++// ── Context ────────────────────────────────────────────────────────────────++type ChainOfThoughtContextValue = {+ isOpen: boolean+ setIsOpen: (open: boolean) => void+ isStreaming: boolean+}++const ChainOfThoughtContext = createContext<ChainOfThoughtContextValue | null>(+ null+)++export const useChainOfThought = () => {+ const context = useContext(ChainOfThoughtContext)+ if (!context) {+ throw new Error(+ 'ChainOfThought components must be used within ChainOfThought'+ )+ }+ return context+}++// ── ChainOfThought (root) ──────────────────────────────────────────────────++export type ChainOfThoughtProps = ComponentProps<typeof Collapsible> & {+ isStreaming?: boolean+ /** When true the collapsible auto-collapses (e.g. text content appeared after this CoT group). */+ shouldCollapse?: boolean+ open?: boolean+ defaultOpen?: boolean+ onOpenChange?: (open: boolean) => void+}++export const ChainOfThought = memo(+ ({+ className,+ isStreaming = false,+ shouldCollapse = false,+ open,+ defaultOpen = true,+ onOpenChange,+ children,+ ...props+ }: ChainOfThoughtProps) => {+ const [isOpen, setIsOpen] = useControllableState({+ prop: open,+ defaultProp: defaultOpen,+ onChange: onOpenChange,+ })++ // Auto-collapse once text content appears after this CoT group+ useEffect(() => {+ if (shouldCollapse) {+ setIsOpen(false)+ }+ }, [shouldCollapse, setIsOpen])++ const handleOpenChange = (newOpen: boolean) => {+ setIsOpen(newOpen)+ }++ const contextValue = useMemo(+ () => ({ isStreaming, isOpen, setIsOpen }),+ [isStreaming, isOpen]+ )++ return (+ <ChainOfThoughtContext.Provider value={contextValue}>+ <Collapsible+ className={cn('not-prose mb-4', className)}+ onOpenChange={handleOpenChange}+ open={isOpen}+ {...props}+ >+ {children}+ </Collapsible>+ </ChainOfThoughtContext.Provider>+ )+ }+)++// ── ChainOfThoughtHeader ───────────────────────────────────────────────────++export type ChainOfThoughtHeaderProps = ComponentProps<+ typeof CollapsibleTrigger+> & {+ title?: string+}++export const ChainOfThoughtHeader = memo(+ ({ className, title, children, ...props }: ChainOfThoughtHeaderProps) => {+ const { isStreaming, isOpen } = useChainOfThought()++ return (+ <CollapsibleTrigger+ className={cn(+ 'flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground',+ className+ )}+ {...props}+ >+ {children ?? (+ <>+ <SparklesIcon className="size-4" />+ {isStreaming ? (+ <Shimmer duration={1}>Reasoning...</Shimmer>+ ) : (+ <p>{title ?? 'Reasoned through the problem'}</p>+ )}+ <ChevronDownIcon+ className={cn(+ 'size-4 transition-transform',+ isOpen ? 'rotate-180' : 'rotate-0'+ )}+ />+ </>+ )}+ </CollapsibleTrigger>+ )+ }+)++// ── ChainOfThoughtContent ──────────────────────────────────────────────────++export type ChainOfThoughtContentProps = ComponentProps<+ typeof CollapsibleContent+>++export const ChainOfThoughtContent = memo(+ ({ className, children, ...props }: ChainOfThoughtContentProps) => (+ <CollapsibleContent+ className={cn(+ 'mt-4 text-sm relative',+ 'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in',+ className+ )}+ {...props}+ >+ <div className="ml-2 pl-4 border-l-2 border-dotted space-y-3">+ {children}+ </div>+ </CollapsibleContent>+ )+)++// ── ChainOfThoughtText ─────────────────────────────────────────────────────++export type ChainOfThoughtTextProps = ComponentProps<+ typeof CollapsibleContent+> & {+ children: string+}++export const ChainOfThoughtText = memo(+ ({ className, children, ...props }: ChainOfThoughtTextProps) => (+ <CollapsibleContent+ className={cn(+ 'mt-4 text-sm relative',+ 'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in',+ className+ )}+ {...props}+ >+ <div className="ml-2 pl-4 border-l-2 border-dotted">+ <Streamdown animate={true} animationDuration={500}>+ {children}+ </Streamdown>+ </div>+ </CollapsibleContent>+ )+)++// ── ChainOfThoughtStep ─────────────────────────────────────────────────────++export type ChainOfThoughtStepProps = ComponentProps<'div'> & {+ icon?: ReactNode+ label: string+ status: ChainOfThoughtStepStatus+}++const statusIcons: Record<ChainOfThoughtStepStatus, ReactNode> = {+ complete: <CheckCircle2Icon className="size-4 text-green-500 shrink-0" />,+ active: (+ <CircleDotIcon className="size-4 text-blue-500 animate-pulse shrink-0" />+ ),+ pending: <CircleIcon className="size-4 text-muted-foreground/50 shrink-0" />,+}++export const ChainOfThoughtStep = memo(+ ({ className, icon, label, status, children, ...props }: ChainOfThoughtStepProps) => (+ <div+ className={cn(+ 'flex flex-col gap-2',+ className+ )}+ {...props}+ >+ <div className="flex items-start gap-2">+ {icon ?? statusIcons[status]}+ <span+ className={cn(+ 'text-sm leading-snug',+ status === 'active' && 'text-foreground',+ status === 'pending' && 'text-muted-foreground/50'+ )}+ >+ {label}+ </span>+ </div>+ {children && <div className="ml-6">{children}</div>}+ </div>+ )+)++// ── ChainOfThoughtSearchResults ────────────────────────────────────────────++export type ChainOfThoughtSearchResultsProps = ComponentProps<'div'> & {+ title?: string+}++export const ChainOfThoughtSearchResults = memo(+ ({+ className,+ title,+ children,+ ...props+ }: ChainOfThoughtSearchResultsProps) => (+ <div className={cn('space-y-1.5', className)} {...props}>+ {title && (+ <h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">+ {title}+ </h4>+ )}+ <div className="flex flex-wrap gap-1.5">{children}</div>+ </div>+ )+)++// ── ChainOfThoughtSearchResult ─────────────────────────────────────────────++export type ChainOfThoughtSearchResultProps = ComponentProps<'a'>++export const ChainOfThoughtSearchResult = memo(+ ({ className, children, href, ...props }: ChainOfThoughtSearchResultProps) => (+ <a+ href={href}+ target="_blank"+ rel="noopener noreferrer"+ className={cn(+ 'inline-flex items-center gap-1 rounded-full border px-2.5 py-0.5 text-xs text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground',+ className+ )}+ {...props}+ >+ <SearchIcon className="size-3 shrink-0" />+ <span className="truncate max-w-[200px]">{children}</span>+ <ExternalLinkIcon className="size-3 shrink-0 opacity-50" />+ </a>+ )+)++// ── ChainOfThoughtImage ────────────────────────────────────────────────────++export type ChainOfThoughtImageProps = ComponentProps<'figure'> & {+ caption?: string+ children: ReactNode+}++export const ChainOfThoughtImage = memo(+ ({ className, caption, children, ...props }: ChainOfThoughtImageProps) => (+ <figure className={cn('space-y-1.5', className)} {...props}>+ {children}+ {caption && (+ <figcaption className="text-xs text-muted-foreground text-center">+ {caption}+ </figcaption>+ )}+ </figure>+ )+)++// ── Display names ──────────────────────────────────────────────────────────++ChainOfThought.displayName = 'ChainOfThought'+ChainOfThoughtHeader.displayName = 'ChainOfThoughtHeader'+ChainOfThoughtContent.displayName = 'ChainOfThoughtContent'+ChainOfThoughtText.displayName = 'ChainOfThoughtText'+ChainOfThoughtStep.displayName = 'ChainOfThoughtStep'+ChainOfThoughtSearchResults.displayName = 'ChainOfThoughtSearchResults'+ChainOfThoughtSearchResult.displayName = 'ChainOfThoughtSearchResult'+ChainOfThoughtImage.displayName = 'ChainOfThoughtImage'diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsxindex e9ab0c250..1d3f6572d 100644--- a/web-app/src/containers/MessageItem.tsx+++ b/web-app/src/containers/MessageItem.tsx@@ -5,10 +5,11 @@ import { RenderMarkdown } from './RenderMarkdown'import { cn } from '@/lib/utils'import { twMerge } from 'tailwind-merge'import {- Reasoning,- ReasoningContent,- ReasoningTrigger,-} from '@/components/ai-elements/reasoning'+ ChainOfThought,+ ChainOfThoughtContent,+ ChainOfThoughtHeader,+} from '@/components/ai-elements/chain-of-thought'+import { Streamdown } from 'streamdown'import {Tool,ToolContent,@@ -265,54 +266,7 @@ export const MessageItem = memo(return null}- const renderReasoningPart = (- part: { type: 'reasoning'; text: string },- partIndex: number- ) => {- const isLastPart = partIndex === message.parts.length - 1- const shouldBeOpen = isStreaming && isLastPart-- return (- <Reasoning- key={`${message.id}-${partIndex}`}- className="w-full text-muted-foreground"- isStreaming={isStreaming && isLastPart}- defaultOpen={shouldBeOpen}- >- <ReasoningTrigger />- <div className="relative">- {isStreaming && (- <div className="absolute top-0 left-0 right-0 h-8 bg-linear-to-br from-neutral-50 mask-t-from-98% dark:from-background to-transparent pointer-events-none z-10" />- )}- <div- ref={isStreaming ? reasoningContainerRef : null}- onScroll={isStreaming ? onReasoningScroll : undefined}- className={twMerge(- 'w-full overflow-auto relative',- isStreaming- ? 'max-h-64 opacity-70 mt-2 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden'- : 'h-auto opacity-100'- )}- >- <ReasoningContent>{part.text}</ReasoningContent>- </div>- {isStreaming && !isReasoningAtBottom && (- <Button- className="absolute bottom-2 left-[50%] translate-x-[-50%] rounded-full size-7 z-10"- onClick={onReasoningScrollToBottom}- size="icon"- type="button"- variant="outline"- >- <IconArrowDown className="size-3" />- </Button>- )}- </div>- </Reasoning>- )- }-- const renderToolPart = (part: any, partIndex: number) => {+ const renderToolInline = (part: any, partIndex: number) => {if (!part.type.startsWith('tool-') || !('state' in part)) {return null}@@ -322,7 +276,7 @@ export const MessageItem = memo(<Toolkey={`${message.id}-${partIndex}`}state={part.state}- className="mb-4"+ className="mb-2"><ToolHeadertitle={toolName}@@ -358,25 +312,134 @@ export const MessageItem = memo()}- return (- <div className="w-full mb-4">+ // Group consecutive reasoning + tool parts into a single CoT block.+ // Empty text parts and step-start markers (inserted by the AI SDK during+ // multi-step tool use) are absorbed so they don't split the group.+ const isCotPart = (part: any) =>+ part.type === CONTENT_TYPE.REASONING ||+ part.type.startsWith('tool-') ||+ part.type === 'step-start' ||+ (part.type === CONTENT_TYPE.TEXT && (!part.text || part.text.trim() === ''))++ type PartEntry = { part: any; index: number }++ const renderCotGroup = (+ entries: PartEntry[],+ groupKey: string,+ hasFollowingContent: boolean+ ) => {+ const lastEntryIndex = entries[entries.length - 1].index+ const groupIsStreaming =+ isStreaming && lastEntryIndex === message.parts.length - 1- {/* Render message parts */}- {message.parts.map((part, i) => {+ return (+ <ChainOfThought+ key={groupKey}+ className="w-full text-muted-foreground"+ isStreaming={groupIsStreaming}+ shouldCollapse={hasFollowingContent}+ defaultOpen={true}+ >+ <ChainOfThoughtHeader />+ <ChainOfThoughtContent>+ {entries.map(({ part, index: partIndex }) => {+ if (part.type === CONTENT_TYPE.REASONING) {+ const isLastMsgPart =+ partIndex === message.parts.length - 1+ const partIsStreaming = isStreaming && isLastMsgPart++ return (+ <div+ key={`${message.id}-r-${partIndex}`}+ className="relative"+ >+ {partIsStreaming && (+ <div className="absolute top-0 left-0 right-0 h-8 bg-linear-to-br from-neutral-50 mask-t-from-98% dark:from-background to-transparent pointer-events-none z-10" />+ )}+ <div+ ref={partIsStreaming ? reasoningContainerRef : null}+ onScroll={+ partIsStreaming ? onReasoningScroll : undefined+ }+ className={twMerge(+ 'w-full overflow-auto relative',+ partIsStreaming+ ? 'max-h-64 opacity-70 mt-2 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden'+ : 'h-auto opacity-100'+ )}+ >+ <Streamdown+ animate={true}+ animationDuration={500}+ >+ {part.text}+ </Streamdown>+ </div>+ {partIsStreaming && !isReasoningAtBottom && (+ <Button+ className="absolute bottom-2 left-[50%] translate-x-[-50%] rounded-full size-7 z-10"+ onClick={onReasoningScrollToBottom}+ size="icon"+ type="button"+ variant="outline"+ >+ <IconArrowDown className="size-3" />+ </Button>+ )}+ </div>+ )+ }++ // Tool part inside CoT+ return renderToolInline(part, partIndex)+ })}+ </ChainOfThoughtContent>+ </ChainOfThought>+ )+ }++ const renderedParts = useMemo(() => {+ const elements: React.ReactNode[] = []+ let cotBuffer: PartEntry[] = []++ const flushCot = (hasFollowing: boolean) => {+ if (cotBuffer.length === 0) return+ const key = `${message.id}-cot-${cotBuffer[0].index}`+ elements.push(renderCotGroup(cotBuffer, key, hasFollowing))+ cotBuffer = []+ }++ for (let i = 0; i < message.parts.length; i++) {+ const part = message.parts[i] as any+ if (isCotPart(part)) {+ cotBuffer.push({ part, index: i })+ } else {+ flushCot(true) // text/file follows → collapse the CoTswitch (part.type) {case CONTENT_TYPE.TEXT:- return renderTextPart(part as { type: 'text'; text: string }, i)- case CONTENT_TYPE.FILE:- return renderFilePart(part as any, i)- case CONTENT_TYPE.REASONING:- return renderReasoningPart(- part as { type: 'reasoning'; text: string },- i+ elements.push(+ renderTextPart(part as { type: 'text'; text: string }, i))+ break+ case CONTENT_TYPE.FILE:+ elements.push(renderFilePart(part as any, i))+ breakdefault:- return renderToolPart(part, i)+ break}- })}+ }+ }+ flushCot(false) // end of message, no following content → keep open++ return elements+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [message.parts, isStreaming, isReasoningAtBottom])++ return (+ <div className="w-full mb-4">++ {/* Render message parts */}+ {renderedParts}{/* Message actions for user messages */}{message.role === 'user' && !hideActions && (