CodeWhale icon indicating copy to clipboard operation
CodeWhale copied to clipboard

bug: thinking collapse - multiple root causes causing thinking blocks to freeze, truncate silently, or drop reasoning_content

Open zhou-changjian opened this issue 6 months ago • 8 comments

Problem

Users experience thinking collapse — a family of related defects where the model's reasoning (thinking) blocks either (a) freeze with a live spinner that never resolves, (b) get silently truncated to ≤4 lines with no clear expand affordance during streaming, or (c) disappear entirely from the API message history, causing HTTP 400 errors on the next turn.

Four distinct root causes have been identified through code analysis.


Root Cause 1: Thinking block stuck in streaming: true when ThinkingComplete is missed

Location: crates/tui/src/tui/ui.rs — apply_engine_error_to_app

When a network interruption or mid-stream disconnect occurs, the ThinkingComplete event is never delivered to the UI event loop. The HistoryCell::Thinking { streaming: true, duration_secs: None } stays in the active_cell forever. The spinner never stops. The block never gets a duration stamp and stays ThinkingVisualState::Live with status: "live".

The test flush_active_cell_finalizes_unclosed_thinking_block acknowledges this defensively but only covers the flush_active_cell path. The error-recovery path through apply_engine_error_to_app clears streaming_thinking_active_entry = None without finalizing the cell:

// ui.rs — apply_engine_error_to_app
app.streaming_state.reset();
app.streaming_message_index = None;
app.streaming_thinking_active_entry = None;  // clears pointer but never finalizes the cell

Impact: After any API error or stream drop during a thinking phase, the thinking cell renders with a permanent live spinner.


Root Cause 2: streaming_state.reset() on ThinkingStarted drops buffered tail content

Location: crates/tui/src/tui/ui.rs — EngineEvent::ThinkingStarted handler

EngineEvent::ThinkingStarted { .. } => {
    app.reasoning_buffer.clear();
    app.reasoning_header = None;
    app.thinking_started_at = Some(Instant::now());
    app.streaming_state.reset();          // unconditional reset
    app.streaming_state.start_thinking(0, None);
    let _ = ensure_streaming_thinking_active_entry(app);
}

streaming_state.reset() is called unconditionally. In a multi-block turn (V4 interleaved thinking), if a second ThinkingStarted arrives while the first block is still streaming, the uncommitted tail text in streaming_state for the first block is silently discarded.

Impact: In multi-round tool-call turns with interleaved thinking, the last few tokens of each thinking block may be silently truncated.


Root Cause 3: last_reasoning race between ThinkingComplete and MessageComplete

Location: crates/tui/src/tui/ui.rs — event dispatch loop

ThinkingComplete sets app.last_reasoning. MessageComplete reads and clears app.last_reasoning to build the ContentBlock::Thinking for api_messages.

If MessageComplete is processed before ThinkingComplete (possible when the engine channel drains events in burst order), last_reasoning is None at MessageComplete time, and the thinking block is not included in the API message history:

// EngineEvent::MessageComplete
let thinking = app.last_reasoning.take();  // could be None if ThinkingComplete hasn't arrived yet
if let Some(thinking) = thinking {
    blocks.push(ContentBlock::Thinking { thinking });
}

Impact: Thinking content is stripped from api_messages. On the next turn, DeepSeek V4 returns HTTP 400 (missing reasoning_content), or the model loses continuity of its own reasoning chain.


Root Cause 4 (UX): Hard truncation to 4 rendered lines with no streaming expand affordance

Location: crates/tui/src/tui/history.rs — THINKING_SUMMARY_LINE_LIMIT = 4

Completed thinking blocks are unconditionally collapsed to 4 rendered lines:

const THINKING_SUMMARY_LINE_LIMIT: usize = 4;

if collapsed && rendered.len() > THINKING_SUMMARY_LINE_LIMIT {
    rendered.truncate(THINKING_SUMMARY_LINE_LIMIT);
    truncated = true;
}

The affordance "thinking collapsed; press Ctrl+O for full text" is only shown when !streaming && (truncated || ...). During live streaming this line is suppressed entirely — users watching a long thinking block receive no indication that content is being hidden.

Impact: Users see partial thinking output during streaming with no signal that more exists or how to see it.


Acceptance Criteria

  • [ ] RC1: When a stream error fires while a thinking block is active (streaming_thinking_active_entry.is_some()), apply_engine_error_to_app must call finalize_streaming_thinking_active_entry (or equivalent) before clearing the pointer, so the block is stamped as interrupted rather than left frozen with a live spinner.

  • [ ] RC2: The ThinkingStarted handler must flush any uncommitted tail text from streaming_state into the current active thinking cell before calling streaming_state.reset(), or skip the reset entirely when a thinking entry is already active.

  • [ ] RC3: The event dispatch loop must guarantee that ThinkingComplete is always processed before MessageComplete for the same turn. Acceptable approaches: (a) enforce event emission order in the engine, (b) have MessageComplete inline-drain a pending thinking finalization when streaming_thinking_active_entry is still set, or (c) unify into a single ThinkingAndMessageComplete event.

  • [ ] RC4 (UX): During streaming of a thinking block that exceeds THINKING_SUMMARY_LINE_LIMIT, display a live affordance (e.g. "… (N more lines)") so the user knows the block is being truncated and can navigate to the full text.


Reproduction Steps (RC1 — easiest to reproduce)

  1. Start a session with deepseek-v4-pro (thinking enabled).
  2. Submit a complex multi-step prompt that triggers a long reasoning block.
  3. While the thinking spinner is active (… thinking · live), press Esc to cancel.
  4. Observe: the thinking cell retains the live spinner and status: "live" permanently instead of transitioning to interrupted/partial.

Affected Files

  • crates/tui/src/tui/ui.rs — RC1, RC2, RC3
  • crates/tui/src/tui/history.rs — RC4 (THINKING_SUMMARY_LINE_LIMIT)

Models Affected

Any V4 thinking-mode model: deepseek-v4-pro, deepseek-v4-flash with thinking enabled.

zhou-changjian avatar May 06 '26 11:05 zhou-changjian

thank you! very helpful

Hmbown avatar May 06 '26 21:05 Hmbown

thank you so much -very helpful

Hmbown avatar May 06 '26 21:05 Hmbown

so helpful I thought to comment it twice! haha!

Hmbown avatar May 06 '26 21:05 Hmbown

Status update for v0.8.17: one concrete root cause from this thread was fixed. Streaming thinking blocks now finalize cleanly on stream errors/restarts instead of leaving partial reasoning orphaned in StreamingState.

I am leaving the issue open because the original report describes multiple failure modes, including freeze/truncation/reasoning replay behavior. v0.8.17 should reduce one visible class of stuck thinking blocks, but we still need fresh repros on the latest build before calling the whole issue closed.

Hmbown avatar May 07 '26 19:05 Hmbown

Code review 确认了这四个根因的代码位置:

  • RC1: ui.rs — apply_engine_error_to_app 清除 streaming_thinking_active_entry 但未调用 finalize_streaming_thinking_active_entry
  • RC2: ui.rs — ThinkingStarted handler 无条件调用 streaming_state.reset(),丢弃前一个 block 的缓冲内容
  • RC3: ui.rs — ThinkingComplete 和 MessageComplete 处理顺序不保证,last_reasoning.take() 可能在 ThinkingComplete 设置之前执行
  • RC4: history.rs — THINKING_SUMMARY_LINE_LIMIT = 4 硬截断,流式期间无扩展提示

issue 描述和 acceptance criteria 非常清晰,建议的修复路径合理。

punkcanyang avatar May 10 '26 15:05 punkcanyang

@punkcanyang @Hmbown 十分感谢你们团队的工作,我十分开心能够贡献出自己的力量。事实上,我目前正在基于 DeepSeek TUI 的设计理念,希望在 VSCode 中新建一个 Copilot(我目前正在开发,暂定取名为 Deep Copilot)。我也很乐意加入到 DeepSeek TUI 的贡献团队中。

@punkcanyang @Hmbown Thank you so much for the team's work. I'm very happy to be able to contribute. In fact, I'm currently building a Copilot in VSCode based on the design philosophy of DeepSeek TUI (it's currently under development, tentatively named Deep Copilot). I would love to join the DeepSeek TUI contributor team — I'm wondering if there might be an opportunity to do so.

zhou-changjian avatar May 10 '26 15:05 zhou-changjian

Thanks for the detailed report. Could you confirm if this issue still reproduces on the newly released v0.8.27?

Hmbown avatar May 10 '26 21:05 Hmbown

Closing as completed after the #3016 verification pass on current main.

Root-cause map:

  • RC1 frozen spinner after stream error/restart: fixed by 343314548 (fix(thinking): finalize streaming thinking block on stream errors and restarts). Verified today with cargo test -p codewhale-tui --bin codewhale-tui --locked engine_error_finalizes_active_thinking_block -- --nocapture.
  • RC2 second ThinkingStarted dropping buffered tail: current streaming_thinking::start_block finalizes and stashes the active block before reset. Verified today with cargo test -p codewhale-tui --bin codewhale-tui --locked second_thinking_block_appends_new_entry -- --nocapture.
  • RC3 MessageComplete before ThinkingComplete dropping reasoning and causing next-turn 400s: fixed by 741f36d2b (fix(ui): drain active thinking entry on MessageComplete). Verified today with cargo test -p codewhale-tui --bin codewhale-tui --locked message_complete_drain_preserves_thinking -- --nocapture and cargo test -p codewhale-tui --test reasoning_content_replayed_after_tool_call --locked -- --nocapture.
  • RC4 hard streaming truncation with no affordance: fixed by ca5204e31 (fix(ui): stream thinking content during collapsed view). Verified today with cargo test -p codewhale-tui --bin codewhale-tui --locked render_thinking_streaming_truncated -- --nocapture.

Additional current-main verification from #3016: stream_decoder passed, including Moonshot/Kimi multi-chunk reasoning_content routing, and responses:: passed for the Codex Responses reasoning path. Esc/local cancellation coverage also passed via local_cancel_marks_late_stream_events_for_suppression, issue_2739_esc_cancel_preserves_session_messages_before_clear, and next_escape_action_cancels_when_loading_with_empty_input.

Thanks @ZhouChaunge for the detailed original report and @punkcanyang for the root-cause confirmation. Please reopen or file a fresh issue with logs if a current build still leaves a thinking block live or drops reasoning_content after a tool-call turn.

Hmbown avatar Jun 26 '26 03:06 Hmbown