Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(chat): add toggle for folding interim text into reasoning trace (#8363)
Akarshan Biswas17d7e6f00cac
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsxindex 54dfca453..662498ae0 100644--- a/web-app/src/containers/MessageItem.tsx+++ b/web-app/src/containers/MessageItem.tsx@@ -95,6 +95,9 @@ 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()@@ -590,15 +593,58 @@ export const MessageItem = memo(const renderedParts = useMemo(() => {const parts = message.parts as any[]const elements: React.ReactNode[] = []+ const isCotPart = (t: string) =>+ t === CONTENT_TYPE.REASONING || t.startsWith('tool-')++ // Split mode: walk parts sequentially and flush the 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 = []+ }- // 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.+ 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 = -1for (let i = 0; i < parts.length; i++) {- const t = parts[i].type- if (t === CONTENT_TYPE.REASONING || t.startsWith('tool-')) {+ if (isCotPart(parts[i].type)) {lastCotAnchor = i}}@@ -635,7 +681,13 @@ export const MessageItem = memo(return elements// eslint-disable-next-line react-hooks/exhaustive-deps- }, [message.parts, isStreaming, isReasoningAtBottom, grounding])+ }, [+ message.parts,+ isStreaming,+ isReasoningAtBottom,+ grounding,+ foldInterstitialReasoning,+ ])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 288b0f09a..fe80f5201 100644--- a/web-app/src/containers/__tests__/MessageItem.test.tsx+++ b/web-app/src/containers/__tests__/MessageItem.test.tsx@@ -112,6 +112,7 @@ vi.mock('@/hooks/useToolApproval', () => ({// Import after mocksimport { MessageItem } from '../MessageItem'+import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'const makeMsg = (overrides: any = {}) => ({id: 'msg-1',@@ -126,6 +127,7 @@ describe('MessageItem', () => {vi.clearAllMocks()selectedModelRef.current = { id: 'm1' }pendingApprovalsRef.current = {}+ useInterfaceSettings.setState({ foldInterstitialReasoning: true })})it('renders assistant text via RenderMarkdown', () => {@@ -336,6 +338,82 @@ describe('MessageItem', () => {expect(screen.getByTestId('cot')).toBeInTheDocument()})+ describe('foldInterstitialReasoning toggle', () => {+ const interstitialMsg = () =>+ makeMsg({+ parts: [+ { type: 'reasoning', text: 'first thought' },+ { type: 'text', text: 'interim answer' },+ { type: 'reasoning', text: 'second thought' },+ { type: 'text', text: 'final answer' },+ ],+ }) 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 })+ render(+ <MessageItem+ message={interstitialMsg()}+ isFirstMessage+ isLastMessage+ status={'ready' as any}+ />+ )+ // Trace splits into two groups around the interim answer.+ expect(screen.getAllByTestId('cot')).toHaveLength(2)+ // Both interim and final render in the message body.+ const bodies = screen.getAllByTestId('render-markdown')+ expect(bodies).toHaveLength(2)+ expect(bodies[0]).toHaveTextContent('interim answer')+ expect(bodies[1]).toHaveTextContent('final answer')+ })++ it('skips empty interim text parts when split mode is off', () => {+ useInterfaceSettings.setState({ foldInterstitialReasoning: false })+ render(+ <MessageItem+ message={+ makeMsg({+ parts: [+ { type: 'reasoning', text: 'thinking' },+ { type: 'text', text: ' ' },+ { type: 'text', text: 'final' },+ ],+ }) as any+ }+ isFirstMessage+ isLastMessage+ status={'ready' as any}+ />+ )+ // Blank interim text does not flush the trace into a second group.+ expect(screen.getAllByTestId('cot')).toHaveLength(1)+ const bodies = screen.getAllByTestId('render-markdown')+ expect(bodies).toHaveLength(1)+ expect(bodies[0]).toHaveTextContent('final')+ })+ })+it('renders tool error when state is output-error', () => {render(<MessageItemdiff --git a/web-app/src/hooks/useInterfaceSettings.ts b/web-app/src/hooks/useInterfaceSettings.tsindex 134c175c7..f6eb82173 100644--- a/web-app/src/hooks/useInterfaceSettings.ts+++ b/web-app/src/hooks/useInterfaceSettings.ts@@ -111,12 +111,14 @@ 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}@@ -129,6 +131,7 @@ type InterfaceSettingsPersistedSlice = Omit<| 'setShowTokenSpeed'| 'setColoredUserBubble'| 'setRenderHtmlArtifacts'+ | 'setFoldInterstitialReasoning'>export const fontSizeOptions = [@@ -149,6 +152,7 @@ const createDefaultInterfaceValues = (): InterfaceSettingsPersistedSlice => {showTokenSpeed: true,coloredUserBubble: true,renderHtmlArtifacts: false,+ foldInterstitialReasoning: true,}}@@ -187,6 +191,7 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(showTokenSpeed: true,coloredUserBubble: true,renderHtmlArtifacts: false,+ foldInterstitialReasoning: true,})},@@ -222,6 +227,10 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(setRenderHtmlArtifacts: (render) => {set({ renderHtmlArtifacts: render })},++ setFoldInterstitialReasoning: (fold) => {+ set({ foldInterstitialReasoning: fold })+ },}},{@@ -234,6 +243,7 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(showTokenSpeed: state.showTokenSpeed,coloredUserBubble: state.coloredUserBubble,renderHtmlArtifacts: state.renderHtmlArtifacts,+ foldInterstitialReasoning: state.foldInterstitialReasoning,}),// Apply settings when hydrating from storageonRehydrateStorage: () => (state) => {@@ -274,6 +284,10 @@ 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 4bb4abc22..791753b72 100644--- a/web-app/src/locales/en/settings.json+++ b/web-app/src/locales/en/settings.json@@ -102,6 +102,8 @@"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 81d1791d8..c4a65c600 100644--- a/web-app/src/routes/settings/interface.tsx+++ b/web-app/src/routes/settings/interface.tsx@@ -28,6 +28,8 @@ function InterfaceSettings() {setColoredUserBubble,renderHtmlArtifacts,setRenderHtmlArtifacts,+ foldInterstitialReasoning,+ setFoldInterstitialReasoning,} = useInterfaceSettings()return (@@ -101,6 +103,18 @@ 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')}