Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(chat): thread reasoning rail through tool calls, drop interim-fold setting
Akarshan Biswasd51dd582bedf
diff --git a/web-app/src/components/ai-elements/reasoning-timeline.tsx b/web-app/src/components/ai-elements/reasoning-timeline.tsxindex 6378309b0..642993eba 100644--- a/web-app/src/components/ai-elements/reasoning-timeline.tsx+++ b/web-app/src/components/ai-elements/reasoning-timeline.tsx@@ -1,44 +1,39 @@import { memo } from 'react'+import type React from 'react'import { cn } from '@/lib/utils'import { splitReasoningParagraphs } from '@/lib/reasoning'type StepRowProps = {- text: string+ text?: stringconnector?: boolean+ children?: React.ReactNode}-const StepRow = ({ text, connector = false }: StepRowProps) => (+/**+ * One step on the dotted timeline rail: a dot plus content, with an optional+ * dotted connector descending to the next step. Pass `text` for a plain+ * reasoning paragraph, or `children` to host arbitrary content (e.g. a tool+ * call) on the same continuous rail.+ */+export const StepRow = ({ text, connector = false, children }: 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>+ {children ? (+ <div className="min-w-0 flex-1">{children}</div>+ ) : (+ <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@@ -69,5 +64,4 @@ export const ReasoningActiveStep = memo(({ text }: { text: string }) => {)})-ReasoningTimeline.displayName = 'ReasoningTimeline'ReasoningActiveStep.displayName = 'ReasoningActiveStep'diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsxindex 8c8c845d1..74c29c0bd 100644--- a/web-app/src/containers/MessageItem.tsx+++ b/web-app/src/containers/MessageItem.tsx@@ -1,5 +1,5 @@/* eslint-disable @typescript-eslint/no-explicit-any */-import { memo, useState, useCallback, useEffect } from 'react'+import { memo, useState, useCallback, useEffect, cloneElement } from 'react'import type { UIMessage, ChatStatus } from 'ai'import { RenderMarkdown } from './RenderMarkdown'import { cn } from '@/lib/utils'@@ -44,8 +44,8 @@ import type { RagCitation } from '@/components/Citations'import { useGroundingStore } from '@/stores/grounding-store'import { injectCitationMarkers } from '@/lib/grounding'import {- ReasoningTimeline,ReasoningActiveStep,+ StepRow,} from '@/components/ai-elements/reasoning-timeline'import { splitReasoningParagraphs } from '@/lib/reasoning'@@ -100,9 +100,6 @@ export const MessageItem = memo(}: MessageItemProps) => {const selectedModel = useModelProvider((state) => state.selectedModel)const coloredUserBubble = useInterfaceSettings((s) => s.coloredUserBubble)- const foldInterstitialReasoning = useInterfaceSettings(- (s) => s.foldInterstitialReasoning- )const metadata = message.metadata as Record<string, unknown> | undefinedconst messageError = useMessageErrors((s) => s.errors[message.id])const createdAt = (metadata?.createdAt as Date) ?? new Date()@@ -530,6 +527,58 @@ export const MessageItem = memo(const forceOpen = awaitingApprovalconst shouldCollapse = hasFollowingContent || !hasDisplayableContent+ // Done/historical: flatten every entry (reasoning paragraphs, tool calls,+ // interstitial text, files) into steps on a single continuous dotted rail,+ // so a tool call between two reasoning paragraphs stays threaded instead of+ // restarting the rail.+ const renderTimeline = (rows: PartEntry[]) => {+ const steps: React.ReactNode[] = []+ for (const { part, index: partIndex } of rows) {+ if (part.type === CONTENT_TYPE.REASONING) {+ for (const [pi, para] of splitReasoningParagraphs(+ part.text ?? ''+ ).entries()) {+ steps.push(+ <StepRow key={`${message.id}-r-${partIndex}-${pi}`} text={para} />+ )+ }+ continue+ }+ if (part.type === CONTENT_TYPE.TEXT) {+ if (!part.text || part.text.trim() === '') continue+ steps.push(+ <StepRow key={`${message.id}-it-${partIndex}`} text={part.text} />+ )+ continue+ }+ if (part.type === CONTENT_TYPE.FILE) {+ const node = renderFilePart(part, partIndex)+ if (node)+ steps.push(+ <StepRow key={`${message.id}-f-${partIndex}`}>{node}</StepRow>+ )+ continue+ }+ const toolNode = renderToolInline(part, partIndex)+ if (toolNode)+ steps.push(+ <StepRow key={`${message.id}-t-${partIndex}`}>{toolNode}</StepRow>+ )+ }+ if (steps.length === 0) return null+ return (+ <ol className="relative flex flex-col gap-2.5">+ {steps.map((step, i) =>+ step && typeof step === 'object' && 'props' in step+ ? cloneElement(step as React.ReactElement<{ connector?: boolean }>, {+ connector: i < steps.length - 1,+ })+ : step+ )}+ </ol>+ )+ }+return (<ChainOfThoughtkey={groupKey}@@ -544,74 +593,69 @@ export const MessageItem = memo(completedVerb={hasTools ? 'Worked' : 'Thought'}/><ChainOfThoughtContent>- {visibleEntries.map(({ part, index: partIndex }) => {- if (part.type === CONTENT_TYPE.REASONING) {- const isLastMsgPart =- partIndex === message.parts.length - 1- const partIsStreaming = isStreaming && isLastMsgPart-- // 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- key={`${message.id}-r-${partIndex}`}- className="relative"- >- <div- ref={reasoningContainerRef}- onScroll={onReasoningScroll}- className={twMerge(- 'w-full overflow-auto relative max-h-40',- '[scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden'- )}- >- <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"+ {groupIsStreaming+ ? visibleEntries.map(({ part, index: partIndex }) => {+ if (part.type === CONTENT_TYPE.REASONING) {+ const partIsStreaming =+ isStreaming && partIndex === message.parts.length - 1++ // Streaming: show only the current paragraph as a single+ // active step (bounded height, swaps as each paragraph+ // completes).+ if (partIsStreaming) {+ return (+ <div+ key={`${message.id}-r-${partIndex}`}+ className="relative">- <IconArrowDown className="size-3" />- </Button>- )}- </div>- )- }+ <div+ ref={reasoningContainerRef}+ onScroll={onReasoningScroll}+ className={twMerge(+ 'w-full overflow-auto relative max-h-40',+ '[scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden'+ )}+ >+ <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>+ )+ }- return (- <div key={`${message.id}-r-${partIndex}`} className="relative">- <ReasoningTimeline text={part.text} />- </div>- )- }+ return null+ }- // Interstitial narration emitted between steps — fold into the trace- if (part.type === CONTENT_TYPE.TEXT) {- if (!part.text || part.text.trim() === '') return null- return (- <div- key={`${message.id}-it-${partIndex}`}- dir="auto"- className="select-text whitespace-pre-wrap wrap-break-word text-sm text-main-view-fg/70"- >- {part.text}- </div>- )- }+ if (part.type === CONTENT_TYPE.TEXT) {+ if (!part.text || part.text.trim() === '') return null+ return (+ <div+ key={`${message.id}-it-${partIndex}`}+ dir="auto"+ className="select-text whitespace-pre-wrap wrap-break-word text-sm text-main-view-fg/70"+ >+ {part.text}+ </div>+ )+ }- if (part.type === CONTENT_TYPE.FILE) {- return renderFilePart(part, partIndex)- }+ if (part.type === CONTENT_TYPE.FILE) {+ return renderFilePart(part, partIndex)+ }- // Tool part inside CoT- return renderToolInline(part, partIndex)- })}+ return renderToolInline(part, partIndex)+ })+ : renderTimeline(visibleEntries)}</ChainOfThoughtContent></ChainOfThought>)@@ -623,98 +667,47 @@ export const MessageItem = memo(const isCotPart = (t: string) =>t === CONTENT_TYPE.REASONING || t.startsWith('tool-')- // Split mode: walk parts sequentially and flush the trace whenever a+ // Walk parts sequentially and flush the reasoning/tool trace whenever a// non-empty answer (text/file) interrupts it, so content emitted between- // two reasoning blocks renders as a normal message instead of folding in.- if (!foldInterstitialReasoning) {- let cotEntries: PartEntry[] = []- let groupSeq = 0- const flushCot = (hasFollowing: boolean) => {- if (cotEntries.length === 0) return- elements.push(- renderCotGroup(- cotEntries,- `${message.id}-cot-${groupSeq++}`,- hasFollowing- )- )- cotEntries = []- }-- for (let i = 0; i < parts.length; i++) {- const part = parts[i]- const t = part.type as string- if (isCotPart(t)) {- cotEntries.push({ part, index: i })- continue- }- if (t === CONTENT_TYPE.TEXT) {- if (!part.text || part.text.trim() === '') continue- flushCot(true)- elements.push(- renderTextPart(part as { type: 'text'; text: string }, i)- )- continue- }- if (t === CONTENT_TYPE.FILE) {- flushCot(true)- elements.push(renderFilePart(part as any, i))- }- }- flushCot(false)- return elements- }-- // Fold mode (default): anchor the working trace at the last reasoning/tool- // part — everything up to it (reasoning, tools, step-start markers,- // interstitial narration) folds into a single collapsible CoT group; only- // the trailing answer text/files render in the main message body.- let lastCotAnchor = -1- for (let i = 0; i < parts.length; i++) {- if (isCotPart(parts[i].type)) {- lastCotAnchor = i- }- }-- if (lastCotAnchor >= 0) {- const cotEntries: PartEntry[] = []- for (let i = 0; i <= lastCotAnchor; i++) {- cotEntries.push({ part: parts[i], index: i })- }+ // two reasoning blocks renders as a normal message.+ let cotEntries: PartEntry[] = []+ let groupSeq = 0+ const flushCot = (hasFollowing: boolean) => {+ if (cotEntries.length === 0) returnelements.push(renderCotGroup(cotEntries,- `${message.id}-cot`,- lastCotAnchor < parts.length - 1+ `${message.id}-cot-${groupSeq++}`,+ hasFollowing))+ cotEntries = []}- for (let i = lastCotAnchor + 1; i < parts.length; i++) {+ for (let i = 0; i < parts.length; i++) {const part = parts[i]- switch (part.type) {- case CONTENT_TYPE.TEXT:- elements.push(- renderTextPart(part as { type: 'text'; text: string }, i)- )- break- case CONTENT_TYPE.FILE:- elements.push(renderFilePart(part as any, i))- break- default:- break+ const t = part.type as string+ if (isCotPart(t)) {+ cotEntries.push({ part, index: i })+ continue+ }+ if (t === CONTENT_TYPE.TEXT) {+ if (!part.text || part.text.trim() === '') continue+ flushCot(true)+ elements.push(+ renderTextPart(part as { type: 'text'; text: string }, i)+ )+ continue+ }+ if (t === CONTENT_TYPE.FILE) {+ flushCot(true)+ elements.push(renderFilePart(part as any, i))}}-+ flushCot(false)return elements// eslint-disable-next-line react-hooks/exhaustive-deps- }, [- message.parts,- isStreaming,- isReasoningAtBottom,- grounding,- foldInterstitialReasoning,- ])+ }, [message.parts, isStreaming, isReasoningAtBottom, grounding])const versionNav =versionInfo && versionInfo.count > 1 && onSwitchVersion ? (diff --git a/web-app/src/containers/__tests__/MessageItem.test.tsx b/web-app/src/containers/__tests__/MessageItem.test.tsxindex baec86464..ce3955161 100644--- a/web-app/src/containers/__tests__/MessageItem.test.tsx+++ b/web-app/src/containers/__tests__/MessageItem.test.tsx@@ -112,7 +112,6 @@ vi.mock('@/hooks/useToolApprovalRequests', () => ({// Import after mocksimport { MessageItem } from '../MessageItem'-import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'const makeMsg = (overrides: any = {}) => ({id: 'msg-1',@@ -127,7 +126,6 @@ describe('MessageItem', () => {vi.clearAllMocks()selectedModelRef.current = { id: 'm1' }pendingApprovalsRef.current = {}- useInterfaceSettings.setState({ foldInterstitialReasoning: true })})it('renders assistant text via RenderMarkdown', () => {@@ -338,7 +336,7 @@ describe('MessageItem', () => {expect(screen.getByTestId('cot')).toBeInTheDocument()})- describe('foldInterstitialReasoning toggle', () => {+ describe('interim reasoning text', () => {const interstitialMsg = () =>makeMsg({parts: [@@ -349,28 +347,7 @@ describe('MessageItem', () => {],}) as any- it('folds interim text between reasoning blocks into the trace when on', () => {- useInterfaceSettings.setState({ foldInterstitialReasoning: true })- render(- <MessageItem- message={interstitialMsg()}- isFirstMessage- isLastMessage- status={'ready' as any}- />- )- // Single trace anchored at the last reasoning part.- expect(screen.getAllByTestId('cot')).toHaveLength(1)- // Interim text is folded in, so only the final answer hits the body renderer.- const bodies = screen.getAllByTestId('render-markdown')- expect(bodies).toHaveLength(1)- expect(bodies[0]).toHaveTextContent('final answer')- // Interim narration is present, but inside the trace (not a body message).- expect(screen.getByText('interim answer')).toBeInTheDocument()- })-- it('renders interim text as a normal message and splits the trace when off', () => {- useInterfaceSettings.setState({ foldInterstitialReasoning: false })+ it('renders interim text as a normal message and splits the trace', () => {render(<MessageItemmessage={interstitialMsg()}@@ -388,8 +365,7 @@ describe('MessageItem', () => {expect(bodies[1]).toHaveTextContent('final answer')})- it('skips empty interim text parts when split mode is off', () => {- useInterfaceSettings.setState({ foldInterstitialReasoning: false })+ it('skips empty interim text parts', () => {render(<MessageItemmessage={diff --git a/web-app/src/hooks/useInterfaceSettings.ts b/web-app/src/hooks/useInterfaceSettings.tsindex f4e20ccda..650ad9be0 100644--- a/web-app/src/hooks/useInterfaceSettings.ts+++ b/web-app/src/hooks/useInterfaceSettings.ts@@ -112,14 +112,12 @@ interface InterfaceSettingsState {showTokenSpeed: booleancoloredUserBubble: booleanrenderHtmlArtifacts: boolean- foldInterstitialReasoning: booleansetFontSize: (size: FontSize) => voidsetAccentColor: (color: AccentColorValue) => voidsetNotificationPosition: (position: NotificationPosition) => voidsetShowTokenSpeed: (show: boolean) => voidsetColoredUserBubble: (colored: boolean) => voidsetRenderHtmlArtifacts: (render: boolean) => void- setFoldInterstitialReasoning: (fold: boolean) => voidresetInterface: () => void}@@ -132,7 +130,6 @@ type InterfaceSettingsPersistedSlice = Omit<| 'setShowTokenSpeed'| 'setColoredUserBubble'| 'setRenderHtmlArtifacts'- | 'setFoldInterstitialReasoning'>export const fontSizeOptions = [@@ -153,7 +150,6 @@ const createDefaultInterfaceValues = (): InterfaceSettingsPersistedSlice => {showTokenSpeed: true,coloredUserBubble: true,renderHtmlArtifacts: false,- foldInterstitialReasoning: true,}}@@ -192,7 +188,6 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(showTokenSpeed: true,coloredUserBubble: true,renderHtmlArtifacts: false,- foldInterstitialReasoning: true,})},@@ -228,10 +223,6 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(setRenderHtmlArtifacts: (render) => {set({ renderHtmlArtifacts: render })},-- setFoldInterstitialReasoning: (fold) => {- set({ foldInterstitialReasoning: fold })- },}},{@@ -245,7 +236,6 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(showTokenSpeed: state.showTokenSpeed,coloredUserBubble: state.coloredUserBubble,renderHtmlArtifacts: state.renderHtmlArtifacts,- foldInterstitialReasoning: state.foldInterstitialReasoning,}),// Apply settings when hydrating from storageonRehydrateStorage: () => (state) => {@@ -286,10 +276,6 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(if (typeof state.renderHtmlArtifacts !== 'boolean') {state.renderHtmlArtifacts = false}-- if (typeof state.foldInterstitialReasoning !== 'boolean') {- state.foldInterstitialReasoning = true- }}// Return the state to be used for hydrationdiff --git a/web-app/src/locales/en/settings.json b/web-app/src/locales/en/settings.jsonindex 791753b72..4bb4abc22 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -102,8 +102,6 @@"coloredUserBubbleDesc": "Use the accent color as the background of your messages. When off, they match assistant messages with plain text on a neutral background.","renderHtmlArtifacts": "Render HTML & SVG artifacts","renderHtmlArtifactsDesc": "Add a Preview tab to HTML and SVG code blocks. HTML runs the model-generated page in a sandboxed frame that executes its own scripts but cannot access Jan, your files, or the network; SVG renders statically with scripts disabled. Off by default.",- "foldInterstitialReasoning": "Fold interim text into reasoning",- "foldInterstitialReasoningDesc": "When on, any answer text a model emits between two reasoning steps is folded into the collapsible reasoning trace, and only the final answer shows in the message body. Turn off to show that interim text as a normal message.","windowBackground": "Window Background","windowBackgroundDesc": "Set the app window's background color.","appMainView": "App Main View",diff --git a/web-app/src/routes/settings/interface.tsx b/web-app/src/routes/settings/interface.tsxindex c4a65c600..81d1791d8 100644--- a/web-app/src/routes/settings/interface.tsx+++ b/web-app/src/routes/settings/interface.tsx@@ -28,8 +28,6 @@ function InterfaceSettings() {setColoredUserBubble,renderHtmlArtifacts,setRenderHtmlArtifacts,- foldInterstitialReasoning,- setFoldInterstitialReasoning,} = useInterfaceSettings()return (@@ -103,18 +101,6 @@ function InterfaceSettings() {/>}/>- <CardItem- title={t('settings:interface.foldInterstitialReasoning')}- description={t(- 'settings:interface.foldInterstitialReasoningDesc'- )}- actions={- <Switch- checked={foldInterstitialReasoning}- onCheckedChange={setFoldInterstitialReasoning}- />- }- /><CardItemtitle={t('settings:interface.resetToDefault')}description={t('settings:interface.resetToDefaultDesc')}