Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: add a setting to collapse thinking by default (#8385)

Michael Hanb00068e4bc25
diff --git a/studio/frontend/src/components/assistant-ui/reasoning.tsx b/studio/frontend/src/components/assistant-ui/reasoning.tsx
index 328835e841b..b488b1b8aaf 100644
--- a/studio/frontend/src/components/assistant-ui/reasoning.tsx
+++ b/studio/frontend/src/components/assistant-ui/reasoning.tsx
@@ -11,7 +11,13 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
-import { resolveReasoningGroupDuration } from "@/features/chat";
+import {
+ resolveReasoningGroupDuration,
+ resolveReasoningOpen,
+ resolveReasoningToggle,
+ startsNewReasoningRound,
+ useChatPreferencesStore,
+} from "@/features/chat";
import { useCollapseScrollLock } from "@/hooks/use-collapse-scroll-lock";
import { cn } from "@/lib/utils";
import {
@@ -347,6 +353,10 @@ const ReasoningGroupImpl: ReasoningGroupComponent = ({
);
});
+ const collapseByDefault = useChatPreferencesStore(
+ (state) => state.collapseThinkingByDefault,
+ );
+
const [manualOpen, setManualOpen] = useState(false);
const [dismissedWhileStreaming, setDismissedWhileStreaming] = useState(false);
const [retainStreamingHeight, setRetainStreamingHeight] = useState(false);
@@ -367,12 +377,16 @@ const ReasoningGroupImpl: ReasoningGroupComponent = ({
// Reset per-round open state. manualOpen is sticky and regenerate reuses this
// instance, so a hand-opened block would stay pinned open and never collapse.
- useEffect(() => {
- if (isReasoningStreaming) {
+ // Adjusted during render, not in an effect: React re-runs this component
+ // before committing, so a stale open never reaches the DOM.
+ const [wasStreaming, setWasStreaming] = useState(isReasoningStreaming);
+ if (wasStreaming !== isReasoningStreaming) {
+ setWasStreaming(isReasoningStreaming);
+ if (startsNewReasoningRound(isReasoningStreaming, wasStreaming)) {
setDismissedWhileStreaming(false);
setManualOpen(false);
}
- }, [isReasoningStreaming]);
+ }
// Keep the streaming height cap until the automatic close finishes. Removing
// it on the completion frame expands long reasoning to its full height before
@@ -385,23 +399,32 @@ const ReasoningGroupImpl: ReasoningGroupComponent = ({
return () => window.clearTimeout(timeout);
}, [isReasoningStreaming]);
- // Open while streaming (unless dismissed), or once manually opened.
- const isOpen = (isReasoningStreaming && !dismissedWhileStreaming) || manualOpen;
+ // Open while streaming (unless dismissed), or once manually opened. With
+ // collapse by default on, only a manual open shows the block.
+ const isOpen = resolveReasoningOpen({
+ isStreaming: isReasoningStreaming,
+ collapseByDefault,
+ dismissedWhileStreaming,
+ manualOpen,
+ });
const variant = isOpen ? "outline" : "ghost";
// Allow closing during streaming (matches ChatGPT).
const handleOpenChange = useCallback(
(open: boolean) => {
- if (isReasoningStreaming) {
- setDismissedWhileStreaming(!open);
- } else {
- if (open) {
- setRetainStreamingHeight(false);
- }
- setManualOpen(open);
+ const next = resolveReasoningToggle(open, {
+ isStreaming: isReasoningStreaming,
+ collapseByDefault,
+ });
+ if (next.releaseStreamingHeight) {
+ setRetainStreamingHeight(false);
+ }
+ setManualOpen(next.manualOpen);
+ if (next.dismissedWhileStreaming !== undefined) {
+ setDismissedWhileStreaming(next.dismissedWhileStreaming);
}
},
- [isReasoningStreaming],
+ [isReasoningStreaming, collapseByDefault],
);
return (
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index a46860c1c7e..4d42153b287 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -156,6 +156,12 @@ export {
} from "./utils/chat-thread-tombstones";
export { emitChatAttachmentDeleted } from "./utils/chat-attachment-events";
export { resolveReasoningGroupDuration } from "./utils/reasoning-duration";
+export {
+ reasoningAutoOpensWhileStreaming,
+ resolveReasoningOpen,
+ resolveReasoningToggle,
+ startsNewReasoningRound,
+} from "./utils/reasoning-visibility";
export { ArtifactCard } from "./artifacts/artifact-card";
export { ResearchMessage } from "./components/research-message";
export {
diff --git a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
index 5b5011a78f5..74fd37d1280 100644
--- a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
@@ -8,6 +8,8 @@ import { persist } from "zustand/middleware";
// confirmDeleteChats: when off, deleting a chat skips the confirm dialog.
// showModelDisclaimer: when off, hide the "LLMs can make mistakes" footer note.
// showResponseModel: when on, assistant responses show the producing model.
+// collapseThinkingByDefault: when on, thinking stays collapsed instead of
+// streaming open.
export interface ChatPreferencesState {
confirmDeleteChats: boolean;
setConfirmDeleteChats: (value: boolean) => void;
@@ -15,6 +17,8 @@ export interface ChatPreferencesState {
setShowModelDisclaimer: (value: boolean) => void;
showResponseModel: boolean;
setShowResponseModel: (value: boolean) => void;
+ collapseThinkingByDefault: boolean;
+ setCollapseThinkingByDefault: (value: boolean) => void;
}
export const useChatPreferencesStore = create<ChatPreferencesState>()(
@@ -29,6 +33,9 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
showResponseModel: false,
setShowResponseModel: (showResponseModel) =>
set({ showResponseModel }),
+ collapseThinkingByDefault: false,
+ setCollapseThinkingByDefault: (collapseThinkingByDefault) =>
+ set({ collapseThinkingByDefault }),
}),
{
name: "unsloth_chat_preferences",
@@ -39,6 +46,7 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
confirmDeleteChats: saved?.confirmDeleteChats ?? true,
showModelDisclaimer: saved?.showModelDisclaimer ?? true,
showResponseModel: saved?.showResponseModel ?? false,
+ collapseThinkingByDefault: saved?.collapseThinkingByDefault ?? false,
};
},
},
diff --git a/studio/frontend/src/features/chat/utils/reasoning-visibility.ts b/studio/frontend/src/features/chat/utils/reasoning-visibility.ts
new file mode 100644
index 00000000000..588fd228aa9
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/reasoning-visibility.ts
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Open/closed rules for a reasoning group, kept out of the component so the
+// streaming and preference interplay stays testable.
+export interface ReasoningOpenStateInput {
+ /** Group is receiving reasoning deltas. */
+ isStreaming: boolean;
+ /** Settings -> Chat: keep thinking collapsed instead of streaming it open. */
+ collapseByDefault: boolean;
+ /** User closed the auto-opened block mid stream. */
+ dismissedWhileStreaming: boolean;
+ /** User opened the block by hand. */
+ manualOpen: boolean;
+}
+
+/**
+ * Thinking auto opens while it streams and collapses when it finishes, unless
+ * the preference is on: then only an explicit open shows it, in either phase.
+ */
+export function resolveReasoningOpen({
+ isStreaming,
+ collapseByDefault,
+ dismissedWhileStreaming,
+ manualOpen,
+}: ReasoningOpenStateInput): boolean {
+ if (manualOpen) {
+ return true;
+ }
+ if (collapseByDefault) {
+ return false;
+ }
+ return isStreaming && !dismissedWhileStreaming;
+}
+
+/** Whether the block opens on its own for this round, so a toggle dismisses it. */
+export function reasoningAutoOpensWhileStreaming(
+ isStreaming: boolean,
+ collapseByDefault: boolean,
+): boolean {
+ return isStreaming && !collapseByDefault;
+}
+
+/**
+ * A new round starts when streaming resumes. Regenerate reuses the component,
+ * so last round's open state has to clear in that same render, not in an
+ * effect, or the block paints open before collapsing.
+ */
+export function startsNewReasoningRound(
+ isStreaming: boolean,
+ wasStreaming: boolean,
+): boolean {
+ return isStreaming && !wasStreaming;
+}
+
+export interface ReasoningToggleResult {
+ /** Sticky user open. Cleared on close so a preference flip cannot pin it. */
+ manualOpen: boolean;
+ /** Set only when the block auto opens, since that is what gets dismissed. */
+ dismissedWhileStreaming?: boolean;
+ /** Drop the streaming height cap so a hand-opened block shows in full. */
+ releaseStreamingHeight: boolean;
+}
+
+/** Resolves a trigger click into the next open state. */
+export function resolveReasoningToggle(
+ open: boolean,
+ {
+ isStreaming,
+ collapseByDefault,
+ }: Pick<ReasoningOpenStateInput, "isStreaming" | "collapseByDefault">,
+): ReasoningToggleResult {
+ const autoOpens = reasoningAutoOpensWhileStreaming(
+ isStreaming,
+ collapseByDefault,
+ );
+ return {
+ manualOpen: open && !autoOpens,
+ ...(autoOpens ? { dismissedWhileStreaming: !open } : {}),
+ releaseStreamingHeight: open && !autoOpens,
+ };
+}
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 27db153920a..9a0d82e5d4c 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -94,6 +94,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.general.chatDefaults",
"settings.general.autoTitleNewChats",
"settings.profile.greetingSloth",
+ "settings.chat.thinking.collapseByDefault",
"settings.chat.artifacts.title",
"settings.chat.artifacts.collapseHtmlBlocks",
"settings.chat.artifacts.allowNetworkAccess",
diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
index 37da7d8f4a6..ab0642f6445 100644
--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
@@ -24,10 +24,7 @@ import { Columns2Icon } from "lucide-react";
import { useEffect } from "react";
import type { ReactNode } from "react";
import { SettingsRow } from "../components/settings-row";
-import {
- SettingsGroupDivider,
- SettingsSection,
-} from "../components/settings-section";
+import { SettingsSection } from "../components/settings-section";
// Adjustable "+" menu items shown in settings, in display order. Icons mirror
// the ones used in the composer + menu itself.
@@ -176,6 +173,12 @@ export function ChatTab() {
const setShowResponseModel = useChatPreferencesStore(
(state) => state.setShowResponseModel,
);
+ const collapseThinkingByDefault = useChatPreferencesStore(
+ (state) => state.collapseThinkingByDefault,
+ );
+ const setCollapseThinkingByDefault = useChatPreferencesStore(
+ (state) => state.setCollapseThinkingByDefault,
+ );
useEffect(() => {
void hydratePersistedSettings();
@@ -236,7 +239,18 @@ export function ChatTab() {
/>
</SettingsRow>
))}
- <SettingsGroupDivider />
+ </SettingsSection>
+
+ <SettingsSection title={t("settings.general.chatDefaults")}>
+ <SettingsRow
+ label={t("settings.chat.thinking.collapseByDefault")}
+ description={t("settings.chat.thinking.collapseByDefaultDescription")}
+ >
+ <Switch
+ checked={collapseThinkingByDefault}
+ onCheckedChange={setCollapseThinkingByDefault}
+ />
+ </SettingsRow>
<SettingsRow
label={t("settings.chat.modelDisclaimer")}
description={t("settings.chat.modelDisclaimerDescription")}
@@ -255,9 +269,6 @@ export function ChatTab() {
onCheckedChange={setShowResponseModel}
/>
</SettingsRow>
- </SettingsSection>
-
- <SettingsSection title={t("settings.general.chatDefaults")}>
<SettingsRow
label={t("settings.general.autoTitleNewChats")}
description={t("settings.general.autoTitleNewChatsDescription")}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 159474d4853..0760a6f316c 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -895,6 +895,11 @@ export const ar = {
modelDisclaimer: "إظهار إخلاء مسؤولية النموذج",
modelDisclaimerDescription:
'إظهار عبارة "LLMs can make mistakes" أسفل مربع المحادثة.',
+ thinking: {
+ collapseByDefault: "طيّ التفكير افتراضيًا",
+ collapseByDefaultDescription:
+ "إبقاء التفكير مطويًا أثناء تفكير النموذج بدلًا من فتحه تلقائيًا. وسّع أي كتلة لقراءتها.",
+ },
artifacts: {
title: "Canvas",
collapseHtmlBlocks: "طي كتل HTML",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 94f77831c4d..cbd7b54756d 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -928,6 +928,11 @@ export const de = {
modelDisclaimer: "Modell-Hinweis anzeigen",
modelDisclaimerDescription:
"Zeigt „LLMs können Fehler machen“ unter dem Chatfeld an.",
+ thinking: {
+ collapseByDefault: "Denken standardmäßig einklappen",
+ collapseByDefaultDescription:
+ "Das Denken bleibt eingeklappt, während das Modell denkt, statt automatisch aufzuklappen. Zum Lesen einen Block ausklappen.",
+ },
artifacts: {
title: "Canvas",
collapseHtmlBlocks: "HTML-Blöcke einklappen",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 6f5c86fc9af..9c79bd8861a 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -889,6 +889,11 @@ export const en = {
modelDisclaimer: "Show model disclaimer",
modelDisclaimerDescription:
'Show "LLMs can make mistakes" under the chat box.',
+ thinking: {
+ collapseByDefault: "Collapse Thinking by default",
+ collapseByDefaultDescription:
+ "Keep reasoning collapsed while the model thinks instead of streaming it open. Expand any block to read it.",
+ },
artifacts: {
title: "Canvas",
collapseHtmlBlocks: "Collapse HTML blocks",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index d2f068f61ad..7da367d09ab 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -919,6 +919,11 @@ export const es = {
modelDisclaimer: "Mostrar aviso del modelo",
modelDisclaimerDescription:
'Muestra "Los LLM pueden cometer errores" bajo el cuadro de chat.',
+ thinking: {
+ collapseByDefault: "Contraer el razonamiento de forma predeterminada",
+ collapseByDefaultDescription:
+ "Mantén el razonamiento contraído mientras el modelo piensa, en lugar de abrirlo automáticamente. Expande cualquier bloque para leerlo.",
+ },
artifacts: {
title: "Canvas",
collapseHtmlBlocks: "Contraer bloques HTML",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index d1e670aaba8..b85b0a13bb6 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -925,6 +925,11 @@ export const fr = {
modelDisclaimer: "Afficher l'avertissement du modèle",
modelDisclaimerDescription:
'Afficher "Les LLM peuvent faire des erreurs" sous la zone de discussion.',
+ thinking: {
+ collapseByDefault: "Replier la réflexion par défaut",
+ collapseByDefaultDescription:
+ "Garde la réflexion repliée pendant que le modèle réfléchit, au lieu de l’ouvrir automatiquement. Dépliez un bloc pour le lire.",
+ },
artifacts: {
title: "Canvas",
collapseHtmlBlocks: "Réduire les blocs HTML",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 207490fbee4..2fe220669c3 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -901,6 +901,11 @@ export const hi = {
modelDisclaimer: "मॉडल अस्वीकरण दिखाएं",
modelDisclaimerDescription:
'चैट बॉक्स के नीचे "LLMs can make mistakes" दिखाएं।',
+ thinking: {
+ collapseByDefault: "थिंकिंग को डिफ़ॉल्ट रूप से संक्षिप्त रखें",
+ collapseByDefaultDescription:
+ "मॉडल के सोचते समय रीज़निंग अपने आप खुलने के बजाय संक्षिप्त रहती है। पढ़ने के लिए किसी भी ब्लॉक को विस्तृत करें।",
+ },
artifacts: {
title: "Canvas",
collapseHtmlBlocks: "HTML ब्लॉक संक्षिप्त करें",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 95c6ff1624d..c2271eed04d 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -895,6 +895,11 @@ export const it = {
modelDisclaimer: "Mostra l'avviso sul modello",
modelDisclaimerDescription:
"Mostra «Gli LLM possono commettere errori» sotto il campo della chat.",
+ thinking: {
+ collapseByDefault: "Comprimi il ragionamento per impostazione predefinita",
+ collapseByDefaultDescription:
+ "Mantieni il ragionamento compresso mentre il modello pensa, invece di aprirlo automaticamente. Espandi un blocco per leggerlo.",
+ },
artifacts: {
title: "Canvas",
collapseHtmlBlocks: "Comprimi i blocchi HTML",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 2996b716e23..18bbb04b024 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -882,6 +882,11 @@ export const ja = {
"アシスタントの応答にモデルのメタデータを表示します。",
modelDisclaimer: "モデルの免責事項を表示",
modelDisclaimerDescription: 'チャットボックスの下に "LLMs can make mistakes" と表示します。',
+ thinking: {
+ collapseByDefault: "思考をデフォルトで折りたたむ",
+ collapseByDefaultDescription:
+ "モデルの思考中も自動で展開せず、折りたたんだままにします。読みたいときはブロックを展開してください。",
+ },
artifacts: {
title: "Canvas",
collapseHtmlBlocks: "HTMLブロックを折りたたむ",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index c61b5c2076c..148179e0bda 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -893,6 +893,11 @@ export const ko = {
modelDisclaimer: "모델 고지 표시",
modelDisclaimerDescription:
'채팅 상자 아래에 "LLMs can make mistakes" 문구를 표시합니다.',
+ thinking: {
+ collapseByDefault: "기본적으로 사고 과정 접기",
+ collapseByDefaultDescription:
+ "모델이 생각하는 동안 사고 과정을 자동으로 펼치지 않고 접어 둡니다. 읽으려면 블록을 펼치세요.",
+ },
artifacts: {
title: "Canvas",
collapseHtmlBlocks: "HTML 블록 접기",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 6d0f510e965..ee8da9090a2 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -907,6 +907,11 @@ export const ptBR = {
modelDisclaimer: "Mostrar aviso do modelo",
modelDisclaimerDescription:
'Mostra "LLMs podem cometer erros" abaixo da caixa de chat.',
+ thinking: {
+ collapseByDefault: "Recolher o raciocínio por padrão",
+ collapseByDefaultDescription:
+ "Mantém o raciocínio recolhido enquanto o modelo pensa, em vez de abri-lo automaticamente. Expanda um bloco para lê-lo.",
+ },
artifacts: {
title: "Canvas",
collapseHtmlBlocks: "Recolher blocos HTML",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index e39bdbf087a..88b2d233b0f 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -905,6 +905,11 @@ export const ru = {
modelDisclaimer: "Показывать предупреждение о модели",
modelDisclaimerDescription:
"Показывать сообщение «LLM могут ошибаться» под полем ввода.",
+ thinking: {
+ collapseByDefault: "Сворачивать размышления по умолчанию",
+ collapseByDefaultDescription:
+ "Размышления остаются свёрнутыми, пока модель думает, вместо автоматического раскрытия. Разверните блок, чтобы прочитать его.",
+ },
artifacts: {
title: "Canvas",
collapseHtmlBlocks: "Сворачивать блоки HTML",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index f3e892e5839..d1ad1436cdd 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -870,6 +870,11 @@ export const zhCN = {
modelDisclaimer: "显示模型免责声明",
modelDisclaimerDescription:
"在聊天框下方显示“LLM 可能会出错”。",
+ thinking: {
+ collapseByDefault: "默认折叠思考过程",
+ collapseByDefaultDescription:
+ "模型思考时保持折叠,而不是自动展开。需要阅读时展开对应区块。",
+ },
artifacts: {
title: "Canvas",
collapseHtmlBlocks: "折叠 HTML 块",
diff --git a/studio/frontend/tests/reasoning-collapse-preference.test.ts b/studio/frontend/tests/reasoning-collapse-preference.test.ts
new file mode 100644
index 00000000000..abfbda41df3
--- /dev/null
+++ b/studio/frontend/tests/reasoning-collapse-preference.test.ts
@@ -0,0 +1,183 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ reasoningAutoOpensWhileStreaming,
+ resolveReasoningOpen,
+ resolveReasoningToggle,
+ startsNewReasoningRound,
+} from "../src/features/chat/utils/reasoning-visibility.ts";
+
+// Mirrors the component: toggle results feed straight back into the open state.
+function applyToggle(
+ state: {
+ isStreaming: boolean;
+ collapseByDefault: boolean;
+ dismissedWhileStreaming: boolean;
+ manualOpen: boolean;
+ },
+ open: boolean,
+) {
+ const next = resolveReasoningToggle(open, state);
+ return {
+ ...state,
+ manualOpen: next.manualOpen,
+ dismissedWhileStreaming:
+ next.dismissedWhileStreaming ?? state.dismissedWhileStreaming,
+ };
+}
+
+test("thinking streams open and auto-collapses when the preference is off", () => {
+ const base = { collapseByDefault: false, manualOpen: false };
+ assert.equal(
+ resolveReasoningOpen({
+ ...base,
+ isStreaming: true,
+ dismissedWhileStreaming: false,
+ }),
+ true,
+ );
+ // Closing mid-stream keeps it closed for the rest of the round.
+ assert.equal(
+ resolveReasoningOpen({
+ ...base,
+ isStreaming: true,
+ dismissedWhileStreaming: true,
+ }),
+ false,
+ );
+ assert.equal(
+ resolveReasoningOpen({
+ ...base,
+ isStreaming: false,
+ dismissedWhileStreaming: false,
+ }),
+ false,
+ );
+});
+
+test("thinking stays collapsed in both phases when the preference is on", () => {
+ const base = { collapseByDefault: true, dismissedWhileStreaming: false };
+ assert.equal(
+ resolveReasoningOpen({ ...base, isStreaming: true, manualOpen: false }),
+ false,
+ );
+ assert.equal(
+ resolveReasoningOpen({ ...base, isStreaming: false, manualOpen: false }),
+ false,
+ );
+ // A hand-opened block still wins, including while it is streaming.
+ assert.equal(
+ resolveReasoningOpen({ ...base, isStreaming: true, manualOpen: true }),
+ true,
+ );
+ assert.equal(
+ resolveReasoningOpen({ ...base, isStreaming: false, manualOpen: true }),
+ true,
+ );
+});
+
+test("auto-open applies only while streaming with the preference off", () => {
+ assert.equal(reasoningAutoOpensWhileStreaming(true, false), true);
+ assert.equal(reasoningAutoOpensWhileStreaming(true, true), false);
+ assert.equal(reasoningAutoOpensWhileStreaming(false, false), false);
+ assert.equal(reasoningAutoOpensWhileStreaming(false, true), false);
+});
+
+test("a hand-opened block closes again in every phase", () => {
+ for (const isStreaming of [true, false]) {
+ for (const collapseByDefault of [true, false]) {
+ let state = {
+ isStreaming,
+ collapseByDefault,
+ dismissedWhileStreaming: false,
+ manualOpen: false,
+ };
+ state = applyToggle(state, true);
+ assert.equal(
+ resolveReasoningOpen(state),
+ true,
+ `open failed for streaming=${isStreaming} collapse=${collapseByDefault}`,
+ );
+ state = applyToggle(state, false);
+ assert.equal(
+ resolveReasoningOpen(state),
+ false,
+ `close failed for streaming=${isStreaming} collapse=${collapseByDefault}`,
+ );
+ }
+ }
+});
+
+test("closing still works after the preference flips mid stream", () => {
+ // Collapsed by default, opened by hand while the model is thinking.
+ let state = {
+ isStreaming: true,
+ collapseByDefault: true,
+ dismissedWhileStreaming: false,
+ manualOpen: false,
+ };
+ state = applyToggle(state, true);
+ assert.equal(resolveReasoningOpen(state), true);
+
+ // Preference turned off from settings without leaving the stream.
+ state = { ...state, collapseByDefault: false };
+ assert.equal(resolveReasoningOpen(state), true);
+
+ // The sticky open has to clear here, or the block cannot be collapsed again.
+ state = applyToggle(state, false);
+ assert.equal(state.manualOpen, false);
+ assert.equal(resolveReasoningOpen(state), false);
+});
+
+test("a round starts only when streaming resumes", () => {
+ assert.equal(startsNewReasoningRound(true, false), true);
+ // Still the same round, so a hand-opened block stays open.
+ assert.equal(startsNewReasoningRound(true, true), false);
+ assert.equal(startsNewReasoningRound(false, true), false);
+ assert.equal(startsNewReasoningRound(false, false), false);
+});
+
+test("regenerating drops the previous round's manual open", () => {
+ // Block opened by hand after the last round finished.
+ let state = {
+ isStreaming: false,
+ collapseByDefault: true,
+ dismissedWhileStreaming: false,
+ manualOpen: true,
+ };
+ assert.equal(resolveReasoningOpen(state), true);
+
+ // Regenerate restarts streaming on the same component instance.
+ const wasStreaming = state.isStreaming;
+ state = { ...state, isStreaming: true };
+ assert.equal(startsNewReasoningRound(state.isStreaming, wasStreaming), true);
+ state = { ...state, manualOpen: false, dismissedWhileStreaming: false };
+ assert.equal(resolveReasoningOpen(state), false);
+});
+
+test("streaming height cap is released only for a hand-opened block", () => {
+ assert.equal(
+ resolveReasoningToggle(true, { isStreaming: true, collapseByDefault: true })
+ .releaseStreamingHeight,
+ true,
+ );
+ // Re-opening an auto-opened block keeps the cap, so live text stays scrolled.
+ assert.equal(
+ resolveReasoningToggle(true, {
+ isStreaming: true,
+ collapseByDefault: false,
+ }).releaseStreamingHeight,
+ false,
+ );
+ assert.equal(
+ resolveReasoningToggle(false, {
+ isStreaming: false,
+ collapseByDefault: false,
+ }).releaseStreamingHeight,
+ false,
+ );
+});