Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(chat): stepped reasoning timeline with paragraph accumulator

Akarshan Biswas3530291f191b
diff --git a/web-app/src/components/ai-elements/chain-of-thought.tsx b/web-app/src/components/ai-elements/chain-of-thought.tsx
index 30c81db55..7d4580ad4 100644
--- a/web-app/src/components/ai-elements/chain-of-thought.tsx
+++ b/web-app/src/components/ai-elements/chain-of-thought.tsx
@@ -73,7 +73,7 @@ export const ChainOfThought = memo(
({
className,
isStreaming = false,
- shouldCollapse = false,
+ shouldCollapse,
forceOpen = false,
open,
defaultOpen = true,
@@ -87,14 +87,16 @@ export const ChainOfThought = memo(
onChange: onOpenChange,
})
- // Auto-collapse once text content appears after this CoT group, unless
- // something inside still needs the user's attention (forceOpen).
+ // Follow the caller's open intent. forceOpen pins it open (e.g. a tool
+ // awaiting approval). When shouldCollapse is a boolean, track it two-way so
+ // the trace opens as a step gains content and collapses when it has none or
+ // the answer begins; when undefined the caller isn't controlling collapse,
+ // so defaultOpen / manual toggle is left untouched. Re-applied only on
+ // input change, preserving a manual toggle between changes.
useEffect(() => {
- if (forceOpen) {
- setIsOpen(true)
- } else if (shouldCollapse) {
- setIsOpen(false)
- }
+ if (forceOpen) setIsOpen(true)
+ else if (shouldCollapse === true) setIsOpen(false)
+ else if (shouldCollapse === false) setIsOpen(true)
}, [forceOpen, shouldCollapse, setIsOpen])
const handleOpenChange = (newOpen: boolean) => {
@@ -123,7 +125,12 @@ export const ChainOfThought = memo(
return (
<ChainOfThoughtContext.Provider value={contextValue}>
<Collapsible
- className={cn('not-prose', className)}
+ className={cn(
+ 'not-prose rounded-2xl transition-colors',
+ // Card frame only while expanded; collapsed shows a bare summary row.
+ 'data-[state=open]:border data-[state=open]:border-border/50 data-[state=open]:bg-main-view-fg/2 data-[state=open]:p-3',
+ className
+ )}
onOpenChange={handleOpenChange}
open={isOpen}
{...props}
@@ -209,9 +216,7 @@ export const ChainOfThoughtContent = memo(
)}
{...props}
>
- <div className="ml-2 pl-4 border-l-2 border-dotted space-y-3">
- {children}
- </div>
+ <div className="space-y-3">{children}</div>
</CollapsibleContent>
)
)
diff --git a/web-app/src/components/ai-elements/reasoning-timeline.tsx b/web-app/src/components/ai-elements/reasoning-timeline.tsx
new file mode 100644
index 000000000..6378309b0
--- /dev/null
+++ b/web-app/src/components/ai-elements/reasoning-timeline.tsx
@@ -0,0 +1,73 @@
+import { memo } from 'react'
+import { cn } from '@/lib/utils'
+import { splitReasoningParagraphs } from '@/lib/reasoning'
+
+type StepRowProps = {
+ text: string
+ connector?: boolean
+}
+
+const StepRow = ({ text, connector = false }: StepRowProps) => (
+ <li className="relative flex gap-2.5">
+ {connector && (
+ <span className="absolute left-[3px] top-3.5 -bottom-2.5 border-l border-dotted border-border" />
+ )}
+ <span className="relative z-10 mt-1.5 size-1.5 shrink-0 rounded-full bg-muted-foreground/40" />
+ <div
+ dir="auto"
+ className="select-text whitespace-pre-wrap wrap-break-word text-sm text-main-view-fg/70"
+ >
+ {text}
+ </div>
+ </li>
+)
+
+/**
+ * Full stepped reasoning trace — one dot-railed step per paragraph, joined by a
+ * single dotted connector. Shown when reasoning has finished (or for historical
+ * messages) where the whole trace is revealed on expand.
+ */
+export const ReasoningTimeline = memo(({ text }: { text: string }) => {
+ const steps = splitReasoningParagraphs(text)
+ if (steps.length === 0) return null
+ return (
+ <ol className="relative flex flex-col gap-2.5">
+ {steps.map((step, i) => (
+ <StepRow key={i} text={step} connector={i < steps.length - 1} />
+ ))}
+ </ol>
+ )
+})
+
+/**
+ * While reasoning streams, show only the most recently *completed* paragraph as
+ * plain text — never the paragraph currently being written. As the model
+ * finishes each paragraph and starts the next, the derived last-completed
+ * paragraph swaps, so exactly one bounded block is visible at a time instead of
+ * the whole growing trace.
+ */
+export const ReasoningActiveStep = memo(({ text }: { text: string }) => {
+ const steps = splitReasoningParagraphs(text)
+ // The final element is the in-progress paragraph; the one before it is the
+ // last paragraph the model has actually finished.
+ const completed = steps.slice(0, -1)
+ const current = completed[completed.length - 1] ?? ''
+ if (!current) return null
+ // Key by paragraph index so each swap remounts the block, replaying the
+ // fade/collapse enter transition as one paragraph gives way to the next.
+ return (
+ <div
+ key={completed.length}
+ dir="auto"
+ className={cn(
+ 'select-text whitespace-pre-wrap wrap-break-word text-sm text-main-view-fg/70',
+ 'animate-in fade-in-0 slide-in-from-top-1 duration-300 ease-out'
+ )}
+ >
+ {current}
+ </div>
+ )
+})
+
+ReasoningTimeline.displayName = 'ReasoningTimeline'
+ReasoningActiveStep.displayName = 'ReasoningActiveStep'
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 8e5f90efa..8c8c845d1 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -43,6 +43,11 @@ import { parseCitationsFromToolOutput } from '@/lib/citation-parser'
import type { RagCitation } from '@/components/Citations'
import { useGroundingStore } from '@/stores/grounding-store'
import { injectCitationMarkers } from '@/lib/grounding'
+import {
+ ReasoningTimeline,
+ ReasoningActiveStep,
+} from '@/components/ai-elements/reasoning-timeline'
+import { splitReasoningParagraphs } from '@/lib/reasoning'
const CHAT_STATUS = {
STREAMING: 'streaming',
@@ -476,10 +481,6 @@ export const MessageItem = memo(
const groupIsStreaming =
isStreaming && lastEntryIndex === message.parts.length - 1
- // Keep the trace expanded while a tool is still running or awaiting the
- // user's approval — collapsing it would hide the approval controls.
- const keepOpen = hasPendingToolCall || awaitingApproval
-
// While streaming, surface only the latest step (current reasoning
// paragraph or tool call) so each step replaces the previous one rather
// than the whole trace scrolling by. The full trace renders once done.
@@ -510,17 +511,36 @@ export const MessageItem = memo(
meaningful.length > 0 &&
meaningful[meaningful.length - 1].part.type.startsWith('tool-')
+ // Only reasoning text is worth expanding for — a tool-only step collapses
+ // to the header. While streaming that means the current step is a
+ // reasoning paragraph that has completed at least once (something for
+ // ReasoningActiveStep to render); once done, any reasoning text qualifies.
+ const hasDisplayableContent = groupIsStreaming
+ ? lastMeaningful?.part.type === CONTENT_TYPE.REASONING &&
+ splitReasoningParagraphs(lastMeaningful.part.text ?? '').length >= 2
+ : entries.some(
+ (e) =>
+ e.part.type === CONTENT_TYPE.REASONING &&
+ Boolean(e.part.text && e.part.text.trim())
+ )
+
+ // Force open only while a tool awaits approval — its approve/deny controls
+ // live inside the collapsible and must stay mounted. A running (already
+ // approved) tool does not force it open, so tool-only steps collapse.
+ const forceOpen = awaitingApproval
+ const shouldCollapse = hasFollowingContent || !hasDisplayableContent
+
return (
<ChainOfThought
key={groupKey}
className="w-full text-muted-foreground"
isStreaming={groupIsStreaming}
- shouldCollapse={hasFollowingContent && !keepOpen}
- forceOpen={keepOpen}
- defaultOpen={true}
+ shouldCollapse={shouldCollapse}
+ forceOpen={forceOpen}
+ defaultOpen={hasDisplayableContent && !hasFollowingContent}
>
<ChainOfThoughtHeader
- streamingLabel={currentStepIsTool ? 'Using tools...' : 'Reasoning...'}
+ streamingLabel={currentStepIsTool ? 'Using tools...' : 'Thinking'}
completedVerb={hasTools ? 'Worked' : 'Thought'}
/>
<ChainOfThoughtContent>
@@ -530,44 +550,43 @@ export const MessageItem = memo(
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" />
- )}
+ // Streaming: show only the current paragraph as a single
+ // active step (bounded height, swaps as each paragraph
+ // completes). Done/historical: full dot-railed step timeline.
+ if (partIsStreaming) {
+ return (
<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'
- )}
+ key={`${message.id}-r-${partIndex}`}
+ className="relative"
>
<div
- dir="auto"
- className="select-text whitespace-pre-wrap wrap-break-word text-sm text-main-view-fg/70"
+ ref={reasoningContainerRef}
+ onScroll={onReasoningScroll}
+ className={twMerge(
+ 'w-full overflow-auto relative max-h-40',
+ '[scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden'
+ )}
>
- {part.text}
+ <ReasoningActiveStep text={part.text} />
</div>
+ {!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>
- {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>
- )}
+ )
+ }
+
+ return (
+ <div key={`${message.id}-r-${partIndex}`} className="relative">
+ <ReasoningTimeline text={part.text} />
</div>
)
}
@@ -739,7 +758,9 @@ export const MessageItem = memo(
message.role === 'assistant' &&
!awaitingApproval &&
(hasPendingToolCall || status === CHAT_STATUS.SUBMITTED) && (
- <PromptProgress hideIdle={hasPendingToolCall} />
+ <div className="mt-2">
+ <PromptProgress hideIdle={hasPendingToolCall} />
+ </div>
)}
{typeof messageError === 'string' && messageError.length > 0 && (
diff --git a/web-app/src/lib/__tests__/reasoning.test.ts b/web-app/src/lib/__tests__/reasoning.test.ts
new file mode 100644
index 000000000..dc1850f13
--- /dev/null
+++ b/web-app/src/lib/__tests__/reasoning.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest'
+import { splitReasoningParagraphs } from '../reasoning'
+
+describe('splitReasoningParagraphs', () => {
+ it('returns [] for empty/whitespace input', () => {
+ expect(splitReasoningParagraphs('')).toEqual([])
+ expect(splitReasoningParagraphs(' \n ')).toEqual([])
+ })
+
+ it('splits on blank lines, keeping single newlines within a step', () => {
+ const text = 'First thought\nstill first\n\nSecond thought'
+ expect(splitReasoningParagraphs(text)).toEqual([
+ 'First thought\nstill first',
+ 'Second thought',
+ ])
+ })
+
+ it('collapses runs of 3+ newlines into one boundary', () => {
+ expect(splitReasoningParagraphs('a\n\n\n\nb')).toEqual(['a', 'b'])
+ })
+
+ it('treats a trailing in-progress paragraph as the last element', () => {
+ const streaming = 'Done paragraph\n\nHalf-written para'
+ const parts = splitReasoningParagraphs(streaming)
+ expect(parts).toHaveLength(2)
+ expect(parts[parts.length - 1]).toBe('Half-written para')
+ })
+
+ it('returns a single step when there are no blank lines', () => {
+ expect(splitReasoningParagraphs('one continuous thought')).toEqual([
+ 'one continuous thought',
+ ])
+ })
+
+ it('ignores blank-line-only gaps between paragraphs with trailing spaces', () => {
+ expect(splitReasoningParagraphs('a \n \nb')).toEqual(['a', 'b'])
+ })
+})
diff --git a/web-app/src/lib/reasoning.ts b/web-app/src/lib/reasoning.ts
new file mode 100644
index 000000000..63ee92623
--- /dev/null
+++ b/web-app/src/lib/reasoning.ts
@@ -0,0 +1,16 @@
+/**
+ * Split a reasoning trace into paragraph "steps". Models separate distinct
+ * thoughts with a blank line, so a run of 2+ newlines starts a new step; a
+ * single newline stays within the current step (soft wrap / list item).
+ *
+ * Because the caller passes the full accumulated text on every streaming tick,
+ * the last element is the paragraph currently being written; earlier elements
+ * are completed steps. No external accumulator state is needed.
+ */
+export function splitReasoningParagraphs(text: string): string[] {
+ if (!text) return []
+ return text
+ .split(/\n[ \t]*\n+/)
+ .map((p) => p.replace(/\s+$/, ''))
+ .filter((p) => p.trim().length > 0)
+}