cc 1 settimana fa
parent
commit
3c70027f0c
72 ha cambiato i file con 5369 aggiunte e 54 eliminazioni
  1. 24 0
      ai-electron/frontend/src/workbench/api/chat.ts
  2. 52 2
      ai-electron/frontend/src/workbench/components/AiMarkdown.vue
  3. 218 0
      ai-electron/frontend/src/workbench/components/chat/ChatEcharts.vue
  4. 240 0
      ai-electron/frontend/src/workbench/components/chat/PlanApprovalCard.vue
  5. 224 0
      ai-electron/frontend/src/workbench/components/chat/ProcessPanel.vue
  6. 456 0
      ai-electron/frontend/src/workbench/components/chat/ProcessStepItem.vue
  7. 91 0
      ai-electron/frontend/src/workbench/components/chat/ThinkingDetail.vue
  8. 277 0
      ai-electron/frontend/src/workbench/components/chat/processTypes.ts
  9. 80 0
      ai-electron/frontend/src/workbench/styles/workbench.less
  10. 6 1
      ai-electron/frontend/src/workbench/views/agent/memory/index.vue
  11. 1 1
      ai-electron/frontend/src/workbench/views/agent/pack/index.vue
  12. 346 9
      ai-electron/frontend/src/workbench/views/chat/index.vue
  13. 29 0
      ai-electron/frontend/src/workbench/views/model/config/index.vue
  14. 29 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/config/AiProperties.java
  15. 14 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/controller/AiChatController.java
  16. 2 1
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AgentAssembler.java
  17. 12 11
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AgentModelFactory.java
  18. 92 17
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiChatFacade.java
  19. 36 2
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiExpertResumeDriver.java
  20. 55 5
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiIntegrationDriver.java
  21. 582 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiProcessTimeline.java
  22. 6 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiRouteContext.java
  23. 139 2
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiRouteOrchestrator.java
  24. 87 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiStepConclusionRefiner.java
  25. 172 1
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiStreamEventBridge.java
  26. 16 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiStreamState.java
  27. 113 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiTurnFinisher.java
  28. 14 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/RouteDecisionTool.java
  29. 1 1
      ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/ToolLabelResolver.java
  30. 103 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiMessageStep.java
  31. 8 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiModelConfig.java
  32. 5 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/bo/AiModelConfigBo.java
  33. 98 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiMessageStepVo.java
  34. 5 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiModelConfigVo.java
  35. 18 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/mapper/AiAuditRetentionMapper.java
  36. 17 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/mapper/AiMessageStepMapper.java
  37. 58 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/IAiMessageStepService.java
  38. 9 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/IAiSessionService.java
  39. 3 1
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiAuditRetentionServiceImpl.java
  40. 116 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiMessageStepServiceImpl.java
  41. 1 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiModelConfigServiceImpl.java
  42. 18 0
      ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiSessionServiceImpl.java
  43. 891 0
      docs/design/chat-process-timeline-plan.md
  44. BIN
      gui-test-screenshots/drawer-fixed-header.png
  45. BIN
      gui-test-screenshots/drawer-state.png
  46. BIN
      gui-test-screenshots/memory-scope-names.png
  47. 52 0
      sql/ai_message_step.sql
  48. 4 0
      sql/ai_model_enable_thinking.sql
  49. 371 0
      test-reports-20261119-process-display/build-report.mjs
  50. 178 0
      test-reports-20261119-process-display/report.html
  51. BIN
      test-reports-20261119-process-display/shots/01-collapsed-summaries.png
  52. BIN
      test-reports-20261119-process-display/shots/02-expanded-thinking.png
  53. BIN
      test-reports-20261119-process-display/shots/03-expert-output.png
  54. BIN
      test-reports-20261119-process-display/shots/04-expert-raw-subtools.png
  55. BIN
      test-reports-20261119-process-display/shots/05-expert-detail.png
  56. BIN
      test-reports-20261119-process-display/shots/06-live-streaming.png
  57. BIN
      test-reports-20261119-process-display/shots/07-hitl-waiting.png
  58. BIN
      test-reports-20261119-process-display/shots/08-legacy-session.png
  59. BIN
      test-reports-20261119-process-display/shots/09-model-thinking-config.png
  60. BIN
      test-reports-20261119-process-display/shots/10-agent-chat-chart.png
  61. BIN
      test-reports-20261119-process-display/shots/11-agent-html-artifact.png
  62. BIN
      test-reports-20261119-process-display/shots/modal-01-fullscreen-filled.png
  63. BIN
      test-reports-20261119-process-display/shots/modal-02-html-fullscreen.png
  64. BIN
      test-reports-20261119-process-display/shots/plan-00-state.png
  65. BIN
      test-reports-20261119-process-display/shots/plan-01-before-rawjson.png
  66. BIN
      test-reports-20261119-process-display/shots/plan-02-after-card.png
  67. BIN
      test-reports-20261119-process-display/shots/plan-03-md-rendered.png
  68. BIN
      test-reports-20261119-process-display/shots/plan-04-plandoc-rendered.png
  69. BIN
      test-reports-20261119-process-display/shots/report-charts.png
  70. BIN
      test-reports-20261119-process-display/shots/report-gallery.png
  71. BIN
      test-reports-20261119-process-display/shots/report-hero.png
  72. BIN
      test-reports-20261119-process-display/shots/report-pipeline.png

+ 24 - 0
ai-electron/frontend/src/workbench/api/chat.ts

@@ -239,6 +239,30 @@ export function listChatRouteRuns(sessionId: Id): Promise<AiRouteRunDetailVO[]>
   return aiGet<AiRouteRunDetailVO[]>(`/ai/chat/session/${sessionId}/routeRuns`);
 }
 
+/** 消息执行步骤(思考过程 + 分步结论);仅新数据有行,存量旧消息无步骤 */
+export interface ChatMessageStepVO {
+  id?: Id;
+  sessionId?: Id;
+  messageId?: Id;
+  seq?: number;
+  stepKey: string;
+  kind: 'thinking' | 'route' | 'tool' | 'expert' | 'confirm' | 'integration';
+  speaker?: 'entry' | 'expert';
+  expertName?: string;
+  agentId?: Id;
+  title?: string;
+  status: string;
+  conclusion?: string;
+  /** 后端返回 JSON 字符串,前端解析为详情对象 */
+  detailJson?: string;
+  durationMs?: number;
+  createTime?: string;
+}
+
+export function listChatSteps(sessionId: Id): Promise<ChatMessageStepVO[]> {
+  return aiGet<ChatMessageStepVO[]>(`/ai/chat/session/${sessionId}/steps`);
+}
+
 export function sendChatMessage(
   sessionId: Id,
   data: { content?: string; attachmentIds?: Id[] },

+ 52 - 2
ai-electron/frontend/src/workbench/components/AiMarkdown.vue

@@ -1,11 +1,17 @@
 <template>
-  <div class="ai-markdown" v-html="html"></div>
+  <div class="ai-markdown">
+    <template v-for="(block, i) in blocks" :key="i">
+      <ChatEcharts v-if="block.type === 'echarts'" :code="block.code" />
+      <div v-else v-html="renderMd(block.text)"></div>
+    </template>
+  </div>
 </template>
 
 <script lang="ts" setup name="AiMarkdown">
   import { computed } from 'vue';
   import hljs from 'highlight.js/lib/common';
   import MarkdownIt from 'markdown-it';
+  import ChatEcharts from './chat/ChatEcharts.vue';
 
   const props = defineProps<{ content?: string }>();
 
@@ -107,7 +113,51 @@
     );
   };
 
-  const html = computed(() => md.render(normalizeMarkdown(props.content || '')));
+  /**
+   * 把内容切分为「markdown 段」与「echarts 图表块」。
+   *
+   * echarts / chart 围栏抽离为独立 Vue 组件(活图表);其余围栏(html 预览、代码高亮)
+   * 原样保留在 markdown 段内交由 fence 规则处理。流式期未闭合的 echarts 围栏也会抽出,
+   * 由 ChatEcharts 以「生成中」占位优雅降级。
+   */
+  type Block = { type: 'md'; text: string } | { type: 'echarts'; code: string };
+  const splitBlocks = (source: string): Block[] => {
+    const blocks: Block[] = [];
+    const lines = source.split('\n');
+    let md: string[] = [];
+    const flush = () => {
+      if (md.length) {
+        blocks.push({ type: 'md', text: md.join('\n') });
+        md = [];
+      }
+    };
+    let i = 0;
+    while (i < lines.length) {
+      const m = lines[i].match(/^\s{0,3}(`{3,}|~{3,})\s*(\S+)?/);
+      if (m) {
+        const marker = m[1].charAt(0);
+        const lang = (m[2] || '').toLowerCase();
+        const closeRe = new RegExp(`^\\s{0,3}${marker === '`' ? '`' : '~'}{3,}\\s*$`);
+        let j = i + 1;
+        while (j < lines.length && !closeRe.test(lines[j])) j++;
+        if (lang === 'echarts' || lang === 'chart') {
+          flush();
+          blocks.push({ type: 'echarts', code: lines.slice(i + 1, j).join('\n') });
+        } else {
+          md.push(...lines.slice(i, Math.min(j + 1, lines.length)));
+        }
+        i = j + 1;
+      } else {
+        md.push(lines[i]);
+        i++;
+      }
+    }
+    flush();
+    return blocks;
+  };
+
+  const blocks = computed<Block[]>(() => splitBlocks(props.content || ''));
+  const renderMd = (text: string) => md.render(normalizeMarkdown(text));
 </script>
 
 <style scoped lang="less">

+ 218 - 0
ai-electron/frontend/src/workbench/components/chat/ChatEcharts.vue

@@ -0,0 +1,218 @@
+<template>
+  <div class="chat-echarts">
+    <div class="chat-echarts__bar">
+      <span class="chat-echarts__dot"></span>
+      <span class="chat-echarts__title">图表</span>
+      <span v-if="chartType" class="chat-echarts__type">{{ chartType }}</span>
+      <button class="chat-echarts__act" type="button" @click="showSource = !showSource">
+        {{ showSource ? '返回图表' : '查看源码' }}
+      </button>
+    </div>
+    <div v-show="!showSource" class="chat-echarts__stage">
+      <div v-if="!option" class="chat-echarts__pending">
+        <span class="chat-echarts__spinner"></span>
+        图表生成中…
+      </div>
+      <div v-else ref="chartRef" class="chat-echarts__canvas"></div>
+    </div>
+    <pre v-show="showSource" class="chat-echarts__source"><code>{{ code }}</code></pre>
+  </div>
+</template>
+
+<script setup lang="ts">
+  /**
+   * 聊天总结处的 ECharts 图表渲染块。
+   *
+   * Agent 在回答中输出 ```echarts 围栏(ECharts option JSON),本组件把它渲染为活图表:
+   * 流式期 JSON 未闭合时显示「图表生成中」占位,闭合后初始化;option 变化时 setOption 更新;
+   * 容器尺寸变化时 resize;卸载时 dispose,避免重复初始化与内存泄漏。
+   */
+  import { computed, onBeforeUnmount, onMounted, ref, watch, nextTick } from 'vue';
+  import echarts from '@/core/utils/lib/echarts';
+
+  const props = defineProps<{ code?: string }>();
+
+  const chartRef = ref<HTMLDivElement | null>(null);
+  const showSource = ref(false);
+  let chart: ReturnType<typeof echarts.init> | null = null;
+  let ro: ResizeObserver | null = null;
+
+  const option = computed<Record<string, any> | null>(() => {
+    const raw = (props.code || '').trim();
+    if (!raw) return null;
+    try {
+      const parsed = JSON.parse(raw);
+      if (parsed && typeof parsed === 'object') {
+        // 兼容 {option:{...}} 与直接 option 两种写法
+        const opt = parsed.option && typeof parsed.option === 'object' ? parsed.option : parsed;
+        if (opt && (opt.series || opt.xAxis || opt.yAxis || opt.radar || opt.geo)) return opt;
+      }
+      return null;
+    } catch {
+      return null;
+    }
+  });
+
+  const chartType = computed(() => {
+    const s = option.value?.series;
+    const first = Array.isArray(s) ? s[0] : s;
+    const t = first?.type;
+    const map: Record<string, string> = {
+      bar: '柱状图',
+      line: '折线图',
+      pie: '饼图',
+      radar: '雷达图',
+      scatter: '散点图',
+      map: '地图',
+      pictorialBar: '象形柱图',
+    };
+    return t ? map[t] || t : '';
+  });
+
+  function render() {
+    const el = chartRef.value;
+    const opt = option.value;
+    if (!el || !opt) return;
+    if (!chart) {
+      chart = echarts.init(el, undefined, { renderer: 'svg' });
+    }
+    chart.setOption(opt, { notMerge: true });
+    chart.resize();
+  }
+
+  function dispose() {
+    if (ro) {
+      ro.disconnect();
+      ro = null;
+    }
+    if (chart) {
+      chart.dispose();
+      chart = null;
+    }
+  }
+
+  onMounted(() => {
+    nextTick(render);
+    if (typeof ResizeObserver !== 'undefined') {
+      ro = new ResizeObserver(() => chart && chart.resize());
+      const el = chartRef.value;
+      if (el) ro.observe(el);
+    }
+  });
+
+  watch(option, () => nextTick(render));
+
+  onBeforeUnmount(dispose);
+</script>
+
+<style scoped lang="less">
+  .chat-echarts {
+    margin: 12px 0;
+    overflow: hidden;
+    background: #fff;
+    border: 1px solid var(--wb-border, #e5e9f2);
+    border-radius: 12px;
+
+    &__bar {
+      display: flex;
+      align-items: center;
+      gap: 8px;
+      padding: 8px 12px;
+      font-size: 12px;
+      color: var(--wb-text-2, #64748b);
+      background: var(--wb-primary-soft, #e8eefc);
+      border-bottom: 1px solid var(--wb-border, #e5e9f2);
+    }
+
+    &__dot {
+      width: 8px;
+      height: 8px;
+      border-radius: 50%;
+      background: var(--wb-primary, #2a50ec);
+      box-shadow: 0 0 0 3px rgba(42, 80, 236, 0.15);
+    }
+
+    &__title {
+      font-weight: 600;
+      color: var(--wb-text, #1f2937);
+    }
+
+    &__type {
+      padding: 1px 8px;
+      font-size: 11px;
+      color: var(--wb-primary, #2a50ec);
+      background: #fff;
+      border: 1px solid var(--wb-border, #e5e9f2);
+      border-radius: 999px;
+    }
+
+    &__act {
+      margin-left: auto;
+      padding: 2px 10px;
+      font-size: 12px;
+      color: var(--wb-text-2, #64748b);
+      background: #fff;
+      border: 1px solid var(--wb-border, #e5e9f2);
+      border-radius: 6px;
+      cursor: pointer;
+      transition: 0.15s;
+
+      &:hover {
+        color: var(--wb-primary, #2a50ec);
+        border-color: var(--wb-primary, #2a50ec);
+      }
+    }
+
+    &__stage {
+      position: relative;
+      min-height: 320px;
+    }
+
+    &__canvas {
+      width: 100%;
+      height: 320px;
+    }
+
+    &__pending {
+      display: flex;
+      align-items: center;
+      justify-content: center;
+      gap: 10px;
+      height: 320px;
+      font-size: 13px;
+      color: var(--wb-text-muted, #94a3b8);
+    }
+
+    &__spinner {
+      width: 16px;
+      height: 16px;
+      border: 2px solid var(--wb-border, #e5e9f2);
+      border-top-color: var(--wb-primary, #2a50ec);
+      border-radius: 50%;
+      animation: ce-spin 0.8s linear infinite;
+    }
+
+    &__source {
+      margin: 0;
+      max-height: 320px;
+      overflow: auto;
+      padding: 12px 14px;
+      background: #f8fafc;
+      font-size: 12px;
+      line-height: 1.6;
+
+      code {
+        background: transparent;
+        padding: 0;
+        white-space: pre-wrap;
+        word-break: break-all;
+      }
+    }
+  }
+
+  @keyframes ce-spin {
+    to {
+      transform: rotate(360deg);
+    }
+  }
+</style>

+ 240 - 0
ai-electron/frontend/src/workbench/components/chat/PlanApprovalCard.vue

@@ -0,0 +1,240 @@
+<template>
+  <div class="plan-card" :class="`plan-card--${part.confirmState}`">
+    <div class="plan-card__head">
+      <span class="plan-card__icon"><Icon icon="i-mdi:clipboard-list-outline" /></span>
+      <div class="plan-card__titles">
+        <span class="plan-card__title">研判方案待批准</span>
+        <span class="plan-card__sub">计划模式 · 批准后退出计划模式并开始执行</span>
+      </div>
+      <a-tag class="plan-card__tag" :color="stateColor">{{ stateLabel }}</a-tag>
+    </div>
+
+    <div class="plan-card__body">
+      <div class="plan-card__summary">{{ summary || '(计划摘要为空,请查看完整计划文档)' }}</div>
+
+      <div class="plan-card__meta">
+        <button class="plan-card__doc" type="button" @click="$emit('open-doc')">
+          <Icon icon="i-mdi:file-document-outline" />
+          查看完整计划文档
+        </button>
+        <button class="plan-card__raw-toggle" type="button" @click="showRaw = !showRaw">
+          {{ showRaw ? '收起原始参数' : '原始参数' }}
+        </button>
+      </div>
+      <pre v-show="showRaw" class="plan-card__raw">{{ rawInput }}</pre>
+    </div>
+
+    <div v-if="part.confirmState === 'pending'" class="plan-card__actions">
+      <a-button type="primary" @click="$emit('approve')">
+        <template #icon><Icon icon="i-mdi:check-circle-outline" /></template>
+        批准并执行
+      </a-button>
+      <a-button danger @click="$emit('reject')">
+        <template #icon><Icon icon="i-mdi:close-circle-outline" /></template>
+        拒绝
+      </a-button>
+    </div>
+    <div v-else-if="part.confirmState === 'rejected'" class="plan-card__tip">
+      已拒绝{{ part.confirmReason ? `:${part.confirmReason}` : '' }}。计划未执行。
+    </div>
+    <div v-else-if="part.confirmState === 'expired'" class="plan-card__tip">
+      计划批准已失效(过期或被新请求替代),请重新提问。
+    </div>
+    <div v-else class="plan-card__tip plan-card__tip--ok">已批准,计划进入执行阶段。</div>
+  </div>
+</template>
+
+<script setup lang="ts">
+  /**
+   * 计划模式专用批准卡:把 plan_exit 的 summary 以可读 prose 呈现(替代通用确认卡的 raw JSON),
+   * 提供「查看完整计划文档」入口与批准/拒绝动作;原始参数折叠留证。
+   */
+  import { computed, ref } from 'vue';
+  import { Button as AButton, Tag as ATag } from 'ant-design-vue';
+  import { Icon } from '@/core/components/Icon';
+
+  const props = defineProps<{ part: any }>();
+  defineEmits<{ (e: 'approve'): void; (e: 'reject'): void; (e: 'open-doc'): void }>();
+
+  const showRaw = ref(false);
+
+  const planCall = computed(() =>
+    (props.part?.toolCalls ?? []).find(
+      (c: any) => c.toolName === 'plan_exit' || /批准计划/.test(c.toolLabel || ''),
+    ),
+  );
+
+  const summary = computed(() => {
+    const input = planCall.value?.input;
+    if (!input) return '';
+    if (typeof input === 'string') {
+      try {
+        const p = JSON.parse(input);
+        return p?.summary || p?.plan || input;
+      } catch {
+        return input;
+      }
+    }
+    return input.summary || input.plan || '';
+  });
+
+  const rawInput = computed(() => {
+    const input = planCall.value?.input;
+    if (input == null) return '';
+    return typeof input === 'string' ? input : JSON.stringify(input, null, 2);
+  });
+
+  const stateLabel = computed(() => {
+    const m: Record<string, string> = { pending: '待批准', approved: '已批准', rejected: '已拒绝', expired: '已失效' };
+    return m[props.part?.confirmState] || props.part?.confirmState;
+  });
+  const stateColor = computed(() => {
+    const m: Record<string, string> = { pending: 'warning', approved: 'success', rejected: 'error', expired: 'default' };
+    return m[props.part?.confirmState] || 'default';
+  });
+</script>
+
+<style scoped lang="less">
+  .plan-card {
+    margin: 10px 0;
+    overflow: hidden;
+    border: 1px solid var(--wb-border, #e5e9f2);
+    border-radius: 12px;
+    background: #fff;
+    box-shadow: 0 2px 10px rgba(42, 80, 236, 0.06);
+
+    &__head {
+      display: flex;
+      align-items: center;
+      gap: 10px;
+      padding: 12px 14px;
+      background: linear-gradient(120deg, var(--wb-primary-soft, #e8eefc), #f5f3ff 70%);
+      border-bottom: 1px solid var(--wb-border, #e5e9f2);
+    }
+
+    &__icon {
+      display: grid;
+      place-items: center;
+      width: 34px;
+      height: 34px;
+      flex: none;
+      border-radius: 10px;
+      color: #fff;
+      background: linear-gradient(135deg, var(--wb-primary, #2a50ec), #7c3aed);
+      box-shadow: 0 3px 10px rgba(42, 80, 236, 0.3);
+      font-size: 18px;
+    }
+
+    &__titles {
+      display: flex;
+      flex-direction: column;
+      min-width: 0;
+    }
+
+    &__title {
+      font-size: 14.5px;
+      font-weight: 700;
+      color: var(--wb-text, #1f2937);
+    }
+
+    &__sub {
+      font-size: 11.5px;
+      color: var(--wb-text-2, #64748b);
+    }
+
+    &__tag {
+      margin-left: auto;
+      margin-inline-end: 0;
+    }
+
+    &__body {
+      padding: 14px;
+    }
+
+    &__summary {
+      max-height: 260px;
+      overflow: auto;
+      padding: 12px 14px;
+      font-size: 13.5px;
+      line-height: 1.8;
+      color: var(--wb-text, #1f2937);
+      background: #f8fafc;
+      border: 1px solid var(--wb-border, #e5e9f2);
+      border-left: 3px solid var(--wb-primary, #2a50ec);
+      border-radius: 0 8px 8px 0;
+      white-space: pre-wrap;
+      word-break: break-word;
+    }
+
+    &__meta {
+      display: flex;
+      align-items: center;
+      gap: 10px;
+      margin-top: 10px;
+    }
+
+    &__doc {
+      display: inline-flex;
+      align-items: center;
+      gap: 6px;
+      padding: 5px 12px;
+      font-size: 12.5px;
+      font-weight: 600;
+      color: var(--wb-primary, #2a50ec);
+      background: var(--wb-primary-soft, #e8eefc);
+      border: 1px solid rgba(42, 80, 236, 0.25);
+      border-radius: 8px;
+      cursor: pointer;
+      transition: 0.15s;
+
+      &:hover {
+        background: #dbe6ff;
+        border-color: var(--wb-primary, #2a50ec);
+      }
+    }
+
+    &__raw-toggle {
+      margin-left: auto;
+      padding: 4px 10px;
+      font-size: 12px;
+      color: var(--wb-text-muted, #94a3b8);
+      background: transparent;
+      border: 1px solid var(--wb-border, #e5e9f2);
+      border-radius: 6px;
+      cursor: pointer;
+
+      &:hover {
+        color: var(--wb-text-2, #64748b);
+      }
+    }
+
+    &__raw {
+      margin: 10px 0 0;
+      max-height: 200px;
+      overflow: auto;
+      padding: 10px 12px;
+      font-size: 12px;
+      background: #f8fafc;
+      border: 1px solid var(--wb-border, #e5e9f2);
+      border-radius: 8px;
+      white-space: pre-wrap;
+      word-break: break-all;
+    }
+
+    &__actions {
+      display: flex;
+      gap: 10px;
+      padding: 0 14px 14px;
+    }
+
+    &__tip {
+      padding: 0 14px 14px;
+      font-size: 12.5px;
+      color: var(--wb-text-2, #64748b);
+
+      &--ok {
+        color: var(--wb-success, #16a34a);
+      }
+    }
+  }
+</style>

+ 224 - 0
ai-electron/frontend/src/workbench/components/chat/ProcessPanel.vue

@@ -0,0 +1,224 @@
+<template>
+  <div class="process-panel" :class="{ 'is-streaming': streaming }">
+    <div
+      class="process-panel__head"
+      role="button"
+      tabindex="0"
+      :aria-expanded="expanded"
+      @click="$emit('toggle')"
+      @keydown.enter.prevent="$emit('toggle')"
+      @keydown.space.prevent="$emit('toggle')"
+    >
+      <Icon class="process-panel__arrow" :class="{ 'is-expanded': expanded }" icon="i-mdi:chevron-right" />
+      <template v-if="streaming">
+        <span class="process-panel__pulse"></span>
+        <span class="process-panel__live">
+          {{ summary.activeTitle ? `正在:${summary.activeTitle}` : '正在执行…' }}
+        </span>
+      </template>
+      <template v-else>
+        <Icon
+          class="process-panel__done-icon"
+          :class="{ 'is-waiting': hasWaiting }"
+          :icon="aborted ? 'i-mdi:stop-circle-outline' : hasWaiting ? 'i-mdi:clock-outline' : 'i-mdi:check-circle-outline'"
+        />
+        <span class="process-panel__summary">{{ summaryText }}</span>
+      </template>
+      <span class="process-panel__hint">{{ expanded ? '收起' : '展开' }}</span>
+    </div>
+
+    <div v-show="expanded" class="process-panel__body">
+      <ProcessStepItem
+        v-for="step in steps"
+        :key="step.stepKey"
+        :step="step"
+        :linked-part="findLinkedPart(parts, step)"
+      />
+      <div v-if="overflow" class="process-panel__overflow">步骤过多,仅展示前 {{ steps.length }} 步</div>
+      <div v-if="sessionId && !streaming" class="process-panel__footer">
+        <a class="process-panel__trace-link" @click.stop="openTrace">
+          <Icon icon="i-mdi:timeline-text-outline" />
+          查看审计链路
+        </a>
+      </div>
+    </div>
+  </div>
+</template>
+
+<script setup lang="ts">
+  /**
+   * 「执行过程」统一折叠容器(ChatGPT/DeepSeek 式摘要行 + Manus 式步骤时间线)。
+   * 流式中头部显示当前活动步;完成后折叠为一行摘要,点击展开回看。
+   */
+  import { computed } from 'vue';
+  import { useRouter } from 'vue-router';
+  import { Icon } from '@/core/components/Icon';
+  import ProcessStepItem from './ProcessStepItem.vue';
+  import { findLinkedPart, formatDuration, summarizeSteps, type ProcessStep } from './processTypes';
+
+  const props = defineProps<{
+    steps: ProcessStep[];
+    streaming?: boolean;
+    aborted?: boolean;
+    /** 总耗时(后端 Long→String 序列化,可能是字符串;formatDuration 内部归一) */
+    durationMs?: number | string;
+    /** 既有消息 parts(tool 步实时入参/出参的关联数据源) */
+    parts?: any[];
+    expanded?: boolean;
+    /** 步骤数超出上限(摘要显示 200+) */
+    overflow?: boolean;
+    /** 会话主键(审计链路互跳) */
+    sessionId?: string | number;
+  }>();
+
+  defineEmits<{ (e: 'toggle'): void }>();
+
+  const router = useRouter();
+
+  /** 跳转审计链路页(按会话过滤,trace 页读取 query.sessionId) */
+  function openTrace() {
+    if (!props.sessionId) return;
+    router.push({ name: 'WorkbenchAuditTrace', query: { sessionId: String(props.sessionId) } });
+  }
+
+  const summary = computed(() => summarizeSteps(props.steps ?? []));
+
+  const hasWaiting = computed(() => (props.steps ?? []).some((s) => s.status === 'waiting'));
+
+  const summaryText = computed(() => {
+    const { count, thinkingMs, hasThinking } = summary.value;
+    const countText = props.overflow ? `${count}+ 个步骤` : `${count} 个步骤`;
+    const prefix = hasThinking && thinkingMs > 0 ? `已深度思考 ${formatDuration(thinkingMs)} · ` : '';
+    if (props.aborted) {
+      return `${prefix}已中止 · 完成 ${countText}`;
+    }
+    // 暂停等待人工确认:明确提示等待态(确认步 waiting)
+    if ((props.steps ?? []).some((s) => s.status === 'waiting')) {
+      return `${prefix}等待你确认 · 共 ${countText}`;
+    }
+    const duration = props.durationMs != null ? ` · 用时 ${formatDuration(props.durationMs)}` : '';
+    return `${prefix}已完成 ${countText}${duration}`;
+  });
+</script>
+
+<style scoped lang="less">
+  .process-panel {
+    margin-bottom: 10px;
+    border: 1px solid var(--wb-border);
+    border-radius: var(--wb-radius);
+    background: linear-gradient(135deg, var(--wb-primary-soft), transparent 65%);
+    overflow: hidden;
+
+    &__head {
+      display: flex;
+      align-items: center;
+      gap: 7px;
+      padding: 8px 12px;
+      cursor: pointer;
+      user-select: none;
+
+      &:hover {
+        background: rgba(42, 80, 236, 0.05);
+      }
+    }
+
+    &__arrow {
+      flex: none;
+      font-size: 15px;
+      color: var(--wb-text-muted);
+      transition: transform 0.2s ease;
+
+      &.is-expanded {
+        transform: rotate(90deg);
+      }
+    }
+
+    &__pulse {
+      flex: none;
+      width: 8px;
+      height: 8px;
+      border-radius: 50%;
+      background: var(--wb-primary);
+      animation: panel-pulse 1.2s ease-in-out infinite;
+    }
+
+    &__live {
+      font-size: 12.5px;
+      font-weight: 600;
+      color: var(--wb-primary);
+      white-space: nowrap;
+      overflow: hidden;
+      text-overflow: ellipsis;
+    }
+
+    &__done-icon {
+      flex: none;
+      font-size: 15px;
+      color: var(--wb-success);
+
+      &.is-waiting {
+        color: var(--wb-warning);
+      }
+    }
+
+    &.is-streaming &__done-icon {
+      color: var(--wb-primary);
+    }
+
+    &__summary {
+      flex: 1 1 auto;
+      min-width: 0;
+      font-size: 12.5px;
+      color: var(--wb-text-2);
+      white-space: nowrap;
+      overflow: hidden;
+      text-overflow: ellipsis;
+    }
+
+    &__hint {
+      flex: none;
+      font-size: 11.5px;
+      color: var(--wb-text-muted);
+    }
+
+    &__body {
+      padding: 2px 12px 10px 12px;
+      border-top: 1px dashed var(--wb-border);
+    }
+
+    &__overflow {
+      padding: 6px 0 0 18px;
+      font-size: 11.5px;
+      color: var(--wb-text-muted);
+    }
+
+    &__footer {
+      padding: 6px 0 0 18px;
+    }
+
+    &__trace-link {
+      display: inline-flex;
+      align-items: center;
+      gap: 4px;
+      font-size: 11.5px;
+      color: var(--wb-primary);
+      cursor: pointer;
+
+      &:hover {
+        text-decoration: underline;
+      }
+    }
+  }
+
+  @keyframes panel-pulse {
+    0%,
+    100% {
+      opacity: 1;
+      transform: scale(1);
+    }
+    50% {
+      opacity: 0.45;
+      transform: scale(0.8);
+    }
+  }
+</style>

+ 456 - 0
ai-electron/frontend/src/workbench/components/chat/ProcessStepItem.vue

@@ -0,0 +1,456 @@
+<template>
+  <div class="process-step" :class="`process-step--${step.status}`">
+    <div
+      class="process-step__head"
+      role="button"
+      tabindex="0"
+      :aria-expanded="effectiveExpanded"
+      @click="toggle"
+      @keydown.enter.prevent="toggle"
+      @keydown.space.prevent="toggle"
+    >
+      <span class="process-step__rail">
+        <span class="process-step__dot" :class="{ 'is-running': step.status === 'running' }"></span>
+      </span>
+      <Icon class="process-step__arrow" :class="{ 'is-expanded': effectiveExpanded }" icon="i-mdi:chevron-right" />
+      <Icon class="process-step__icon" :icon="stepIcon(step.kind)" />
+      <span class="process-step__title" :class="{ 'is-running': step.status === 'running' }">
+        {{ step.title }}
+      </span>
+      <a-tag class="process-step__tag" :color="stepStatusColor(step.status)">
+        {{ stepStatusLabel(step.status) }}
+      </a-tag>
+      <span v-if="step.durationMs != null" class="process-step__duration">{{ formatDuration(step.durationMs) }}</span>
+      <span v-if="step.conclusion" class="process-step__conclusion" :title="step.conclusion">
+        {{ step.conclusion }}
+      </span>
+    </div>
+
+    <div v-show="effectiveExpanded" class="process-step__body">
+      <!-- 思考:markdown 全文 + 光标 + 耗时 -->
+      <ThinkingDetail
+        v-if="step.kind === 'thinking'"
+        :text="step.thinkingText"
+        :streaming="step.status === 'running'"
+        :duration-ms="step.durationMs"
+      />
+
+      <!-- 工具:入参 / 结果摘要(实时取关联 tool part,回放取 detail) -->
+      <template v-else-if="step.kind === 'tool'">
+        <div class="process-step__section">
+          <div class="process-step__label">调用入参</div>
+          <pre class="process-step__code process-scroll">{{ toolInput || '{}' }}</pre>
+        </div>
+        <div v-if="toolOutput" class="process-step__section">
+          <div class="process-step__label">结果摘要</div>
+          <pre class="process-step__code process-scroll">{{ toolOutput }}</pre>
+        </div>
+      </template>
+
+      <!-- 专家:实时镜像 / 原文 + 子工具列表(仅名称/状态/耗时,零入参出参泄漏) -->
+      <template v-else-if="step.kind === 'expert'">
+        <div class="process-step__section">
+          <div class="process-step__label">
+            {{ step.status === 'running' ? '专家输出(实时)' : '专家原始结论(原文留证)' }}
+          </div>
+          <pre class="process-step__code process-scroll">{{ step.mirrorText || '(暂无可展示的结论原文)' }}</pre>
+        </div>
+        <div v-if="subTools.length" class="process-step__section">
+          <div class="process-step__label">专家内部工具</div>
+          <div class="process-step__subtools">
+            <span v-for="(tool, index) in subTools" :key="index" class="process-step__subtool">
+              <Icon icon="i-mdi:tools" />
+              {{ toolLabel(tool.toolName) }}
+              <a-tag :color="tool.state === 'SUCCESS' ? 'success' : tool.state ? 'error' : 'default'">
+                {{ tool.state === 'SUCCESS' ? '成功' : tool.state || '进行中' }}
+              </a-tag>
+              <span v-if="tool.durationMs != null" class="process-step__subtool-ms">{{ tool.durationMs }} ms</span>
+            </span>
+          </div>
+        </div>
+        <div v-if="step.detail?.validationError" class="process-step__error">
+          <Icon icon="i-mdi:alert-circle-outline" />
+          <span>{{ step.detail.validationError }}</span>
+        </div>
+      </template>
+
+      <!-- 路由:判定理由 / 置信度 / 任务片段 -->
+      <template v-else-if="step.kind === 'route'">
+        <div class="process-step__kv">
+          <span v-if="step.detail?.action">动作:{{ actionLabel(step.detail.action) }}</span>
+          <span v-if="step.detail?.confidence != null">置信度:{{ step.detail.confidence }}</span>
+        </div>
+        <div v-if="step.detail?.reason" class="process-step__section">
+          <div class="process-step__label">判定理由</div>
+          <div class="process-step__text">{{ step.detail.reason }}</div>
+        </div>
+        <div v-if="step.detail?.taskContext" class="process-step__section">
+          <div class="process-step__label">任务片段</div>
+          <pre class="process-step__code process-scroll">{{ step.detail.taskContext }}</pre>
+        </div>
+      </template>
+
+      <!-- 确认:只读镜像(交互按钮在正文流原位的确认卡片) -->
+      <template v-else-if="step.kind === 'confirm'">
+        <div class="process-step__section">
+          <div class="process-step__label">待确认操作</div>
+          <div v-for="call in step.detail?.toolCalls ?? []" :key="call.toolCallId" class="process-step__confirm-item">
+            {{ call.toolLabel || call.toolName }}
+          </div>
+          <div v-if="!step.detail?.toolCalls?.length" class="process-step__text">(详见下方确认卡片)</div>
+        </div>
+        <div v-if="decisionsText" class="process-step__text">{{ decisionsText }}</div>
+      </template>
+
+      <!-- 整合:汇总说明 -->
+      <template v-else-if="step.kind === 'integration'">
+        <div v-if="step.detail?.text" class="process-step__section">
+          <div class="process-step__label">整合说明</div>
+          <pre class="process-step__code process-scroll">{{ step.detail.text }}</pre>
+        </div>
+      </template>
+
+      <div v-if="hasCopyable" class="process-step__actions">
+        <a-button size="small" type="text" @click.stop="copyDetail">
+          <template #icon><Icon icon="i-mdi:content-copy" /></template>
+          {{ copied ? '已复制' : '复制详情' }}
+        </a-button>
+      </div>
+    </div>
+  </div>
+</template>
+
+<script setup lang="ts">
+  /**
+   * 过程步骤节点:图标 + 标题 + 状态 + 耗时 + 一行结论,展开按 kind 分发详情。
+   * thinking 步流式中自动展开(用户手动操作后让位);其余默认折叠。
+   */
+  import { computed, ref } from 'vue';
+  import { Button as AButton, Tag as ATag } from 'ant-design-vue';
+  import { Icon } from '@/core/components/Icon';
+  import { toolLabel } from '@/core/http/aiConstants';
+  import ThinkingDetail from './ThinkingDetail.vue';
+  import {
+    formatDuration,
+    stepIcon,
+    stepStatusColor,
+    stepStatusLabel,
+    type ProcessStep,
+  } from './processTypes';
+
+  const props = defineProps<{
+    step: ProcessStep;
+    /** 关联的既有 tool part(实时链路入参/出参数据源) */
+    linkedPart?: any;
+  }>();
+
+  const userToggled = ref(false);
+  const manualExpanded = ref(false);
+  const copied = ref(false);
+
+  const effectiveExpanded = computed(() => {
+    if (userToggled.value) return manualExpanded.value;
+    // 思考步流式中自动展开,便于实时看到推理
+    if (props.step.kind === 'thinking' && props.step.status === 'running') return true;
+    return manualExpanded.value;
+  });
+
+  function toggle() {
+    userToggled.value = true;
+    manualExpanded.value = !effectiveExpanded.value;
+  }
+
+  const toolInput = computed(() => props.linkedPart?.input || props.step.detail?.input || '');
+  const toolOutput = computed(() => props.linkedPart?.output || props.step.detail?.output || '');
+
+  const subTools = computed(() => props.step.detail?.tools ?? []);
+
+  const decisionsText = computed(() => {
+    const decisions = props.step.detail?.decisions;
+    if (!Array.isArray(decisions) || !decisions.length) return '';
+    return decisions
+      .map((d: any) => (d.confirmed ? '已允许执行' : `已拒绝${d.reason ? `:${d.reason}` : ''}`))
+      .join(';');
+  });
+
+  const hasCopyable = computed(() => {
+    const s = props.step;
+    if (s.kind === 'thinking') return !!s.thinkingText;
+    if (s.kind === 'expert') return !!s.mirrorText;
+    if (s.kind === 'tool') return !!(toolInput.value || toolOutput.value);
+    if (s.kind === 'route') return !!s.detail?.reason;
+    if (s.kind === 'integration') return !!s.detail?.text;
+    return false;
+  });
+
+  function actionLabel(action: string): string {
+    const map: Record<string, string> = { self: '数剑自答', route: '咨询专家', pinned: '指定专家' };
+    return map[action] ?? action;
+  }
+
+  async function copyDetail() {
+    const s = props.step;
+    let text = '';
+    if (s.kind === 'thinking') text = s.thinkingText ?? '';
+    else if (s.kind === 'expert') text = s.mirrorText ?? '';
+    else if (s.kind === 'tool') text = `入参:\n${toolInput.value}\n\n结果:\n${toolOutput.value}`;
+    else if (s.kind === 'route') text = s.detail?.reason ?? '';
+    else if (s.kind === 'integration') text = s.detail?.text ?? '';
+    try {
+      await navigator.clipboard.writeText(text);
+      copied.value = true;
+      setTimeout(() => (copied.value = false), 1500);
+    } catch {
+      // 剪贴板不可用(非安全上下文)时静默降级
+    }
+  }
+</script>
+
+<style scoped lang="less">
+  .process-step {
+    position: relative;
+    padding-left: 18px;
+
+    &__rail {
+      position: absolute;
+      left: 5px;
+      top: 0;
+      bottom: 0;
+      width: 1px;
+      background: var(--wb-border);
+    }
+
+    &:last-child &__rail {
+      bottom: auto;
+      height: 18px;
+    }
+
+    &__dot {
+      position: absolute;
+      left: -3px;
+      top: 12px;
+      width: 7px;
+      height: 7px;
+      border-radius: 50%;
+      background: var(--wb-text-muted);
+      border: 1px solid var(--wb-bg-card);
+
+      &.is-running {
+        background: var(--wb-primary);
+        animation: step-pulse 1.2s ease-in-out infinite;
+      }
+    }
+
+    &--success &__dot {
+      background: var(--wb-success);
+    }
+    &--error &__dot,
+    &--rejected &__dot {
+      background: var(--wb-error);
+    }
+    &--waiting &__dot {
+      background: var(--wb-warning);
+    }
+
+    &__head {
+      display: flex;
+      align-items: center;
+      gap: 6px;
+      padding: 6px 8px 6px 0;
+      cursor: pointer;
+      border-radius: 6px;
+      min-width: 0;
+
+      &:hover {
+        background: var(--wb-primary-soft);
+      }
+    }
+
+    &__arrow {
+      flex: none;
+      font-size: 14px;
+      color: var(--wb-text-muted);
+      transition: transform 0.2s ease;
+
+      &.is-expanded {
+        transform: rotate(90deg);
+      }
+    }
+
+    &__icon {
+      flex: none;
+      font-size: 15px;
+      color: var(--wb-primary);
+    }
+
+    &__title {
+      flex: none;
+      max-width: 46%;
+      font-size: 13px;
+      font-weight: 600;
+      color: var(--wb-text);
+      white-space: nowrap;
+      overflow: hidden;
+      text-overflow: ellipsis;
+
+      &.is-running {
+        background: linear-gradient(90deg, var(--wb-text) 40%, var(--wb-primary) 50%, var(--wb-text) 60%);
+        background-size: 200% 100%;
+        -webkit-background-clip: text;
+        background-clip: text;
+        -webkit-text-fill-color: transparent;
+        animation: step-shimmer 1.8s linear infinite;
+      }
+    }
+
+    &__tag {
+      flex: none;
+      margin-inline-end: 0;
+      font-size: 11px;
+      line-height: 18px;
+    }
+
+    &__duration {
+      flex: none;
+      font-size: 11.5px;
+      color: var(--wb-text-muted);
+    }
+
+    &__conclusion {
+      flex: 1 1 auto;
+      min-width: 0;
+      font-size: 12px;
+      color: var(--wb-text-2);
+      white-space: nowrap;
+      overflow: hidden;
+      text-overflow: ellipsis;
+    }
+
+    &__body {
+      padding: 4px 8px 10px 20px;
+    }
+
+    &__section {
+      margin-bottom: 8px;
+    }
+
+    &__label {
+      font-size: 11.5px;
+      color: var(--wb-text-muted);
+      margin-bottom: 4px;
+    }
+
+    &__code {
+      margin: 0;
+      max-height: 220px;
+      overflow: auto;
+      padding: 8px 10px;
+      background: var(--wb-bg-card);
+      border: 1px solid var(--wb-border);
+      border-radius: 6px;
+      font-size: 12px;
+      line-height: 1.6;
+      color: var(--wb-text-2);
+      white-space: pre-wrap;
+      word-break: break-all;
+      font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
+    }
+
+    &__text {
+      font-size: 12.5px;
+      color: var(--wb-text-2);
+      line-height: 1.7;
+    }
+
+    &__kv {
+      display: flex;
+      gap: 14px;
+      font-size: 12px;
+      color: var(--wb-text-2);
+      margin-bottom: 6px;
+    }
+
+    &__subtools {
+      display: flex;
+      flex-wrap: wrap;
+      gap: 6px;
+    }
+
+    &__subtool {
+      display: inline-flex;
+      align-items: center;
+      gap: 4px;
+      padding: 2px 8px;
+      font-size: 12px;
+      color: var(--wb-text-2);
+      background: var(--wb-bg-card);
+      border: 1px solid var(--wb-border);
+      border-radius: 6px;
+    }
+
+    &__subtool-ms {
+      font-size: 11px;
+      color: var(--wb-text-muted);
+    }
+
+    &__error {
+      display: flex;
+      align-items: center;
+      gap: 4px;
+      margin-top: 6px;
+      font-size: 12px;
+      color: var(--wb-error);
+    }
+
+    &__confirm-item {
+      font-size: 12.5px;
+      color: var(--wb-text);
+      padding: 2px 0;
+    }
+
+    &__actions {
+      margin-top: 4px;
+    }
+  }
+
+  @keyframes step-pulse {
+    0%,
+    100% {
+      box-shadow: 0 0 0 0 rgba(42, 80, 236, 0.35);
+    }
+    50% {
+      box-shadow: 0 0 0 4px rgba(42, 80, 236, 0);
+    }
+  }
+
+  @keyframes step-shimmer {
+    0% {
+      background-position: 200% 0;
+    }
+    100% {
+      background-position: -200% 0;
+    }
+  }
+
+  // 窄屏:标题收窄、结论换行独占一行,避免挤压溢出
+  @media (max-width: 900px) {
+    .process-step {
+      &__title {
+        max-width: 38%;
+      }
+
+      &__head {
+        flex-wrap: wrap;
+      }
+
+      &__conclusion {
+        flex-basis: 100%;
+        padding-left: 20px;
+      }
+
+      &__body {
+        padding-left: 12px;
+      }
+    }
+  }
+</style>

+ 91 - 0
ai-electron/frontend/src/workbench/components/chat/ThinkingDetail.vue

@@ -0,0 +1,91 @@
+<template>
+  <div class="thinking-detail">
+    <div ref="scrollRef" class="thinking-detail__scroll process-scroll" @scroll="onScroll">
+      <AiMarkdown :content="text || ''" />
+      <span v-if="streaming" class="thinking-detail__cursor"></span>
+    </div>
+    <div v-if="!streaming && durationMs != null" class="thinking-detail__footer">
+      思考了 {{ seconds }} 秒
+    </div>
+  </div>
+</template>
+
+<script setup lang="ts">
+  /**
+   * 思考步详情:markdown 渲染推理全文 + 流式光标 + 耗时脚注。
+   * 流式中自动滚到底(仅当用户未向上回看时),尊重阅读位置。
+   */
+  import { computed, nextTick, ref, watch } from 'vue';
+  import AiMarkdown from '../AiMarkdown.vue';
+
+  const props = defineProps<{
+    text?: string;
+    streaming?: boolean;
+    durationMs?: number;
+  }>();
+
+  const scrollRef = ref<HTMLElement | null>(null);
+  const stickToBottom = ref(true);
+
+  const seconds = computed(() => Math.max(1, Math.round(Number(props.durationMs ?? 0) / 1000)));
+
+  function onScroll() {
+    const el = scrollRef.value;
+    if (!el) return;
+    stickToBottom.value = el.scrollHeight - el.scrollTop - el.clientHeight < 24;
+  }
+
+  watch(
+    () => props.text,
+    async () => {
+      if (!props.streaming || !stickToBottom.value) return;
+      await nextTick();
+      const el = scrollRef.value;
+      if (el) el.scrollTop = el.scrollHeight;
+    },
+  );
+
+  defineExpose({ onScroll });
+</script>
+
+<style scoped lang="less">
+  .thinking-detail {
+    &__scroll {
+      max-height: 240px;
+      overflow-y: auto;
+      padding: 8px 10px;
+      background: var(--wb-bg-card);
+      border: 1px solid var(--wb-border);
+      border-radius: 6px;
+      font-size: 12.5px;
+      line-height: 1.7;
+      color: var(--wb-text-2);
+    }
+
+    &__cursor {
+      display: inline-block;
+      width: 6px;
+      height: 13px;
+      margin-left: 2px;
+      vertical-align: -2px;
+      background: var(--wb-primary);
+      animation: thinking-blink 1s steps(2, start) infinite;
+    }
+
+    &__footer {
+      margin-top: 6px;
+      font-size: 12px;
+      color: var(--wb-text-muted);
+    }
+  }
+
+  @keyframes thinking-blink {
+    0%,
+    100% {
+      opacity: 1;
+    }
+    50% {
+      opacity: 0;
+    }
+  }
+</style>

+ 277 - 0
ai-electron/frontend/src/workbench/components/chat/processTypes.ts

@@ -0,0 +1,277 @@
+import type { ChatMessageStepVO } from '../../api/chat';
+
+/**
+ * 「执行过程」时间线纯函数模块(思考过程 + 分步结论)。
+ *
+ * 与 index.vue 解耦:步骤 reducer / 专家输出镜像 / 历史回放映射 / 摘要计算均为纯函数,便于单测。
+ * 设计依据:docs/design/chat-process-timeline-plan.md §8.2。
+ */
+
+export type ProcessStepKind = 'thinking' | 'route' | 'tool' | 'expert' | 'confirm' | 'integration';
+
+export interface ProcessStep {
+  stepKey: string;
+  seq: number;
+  kind: ProcessStepKind;
+  title: string;
+  status: string;
+  speaker?: 'entry' | 'expert';
+  expertName?: string;
+  refKey?: string;
+  conclusion?: string;
+  durationMs?: number;
+  /** thinking 步:流式累积的推理全文 */
+  thinkingText?: string;
+  /** expert 步:实时镜像的回答文本(完成后由 REST 回填的原文覆盖) */
+  mirrorText?: string;
+  /** 详情(route 随事件下发;其余回放时来自 detailJson) */
+  detail?: Record<string, any>;
+}
+
+const KINDS: ProcessStepKind[] = ['thinking', 'route', 'tool', 'expert', 'confirm', 'integration'];
+
+/**
+ * 数值归一:后端 Jackson 把 Long 序列化为字符串(防雪花 ID 精度丢失),
+ * durationMs / seq 等数值字段到前端可能是 string,统一转 number,避免 += 变字符串拼接。
+ */
+function toNum(value: any): number | undefined {
+  if (value == null || value === '') return undefined;
+  const n = Number(value);
+  return Number.isFinite(n) ? n : undefined;
+}
+
+function kindOfKey(stepKey: string): ProcessStepKind {
+  const prefix = stepKey.split(':')[0];
+  const map: Record<string, ProcessStepKind> = {
+    think: 'thinking',
+    route: 'route',
+    tool: 'tool',
+    expert: 'expert',
+    confirm: 'confirm',
+    integ: 'integration',
+  };
+  return map[prefix] ?? 'tool';
+}
+
+function titleOfKind(kind: ProcessStepKind): string {
+  const map: Record<ProcessStepKind, string> = {
+    thinking: '深度思考',
+    route: '路由决策',
+    tool: '工具调用',
+    expert: '咨询专家',
+    confirm: '人工确认',
+    integration: '汇总整合',
+  };
+  return map[kind] ?? '执行步骤';
+}
+
+/**
+ * 应用一条 step_* 事件(start 追加 / delta 拼接 / end 归一)。
+ *
+ * 按 stepKey upsert:HITL 恢复段续接同一步骤(保留原 seq 与位置);
+ * 乱序 / 重复 end 容错(end 先到时建占位步,start 后到时不重复追加)。
+ */
+export function applyStepEvent(steps: ProcessStep[], event: any): void {
+  const type = event?.type;
+  const key = event?.stepKey;
+  if (!key || (type !== 'step_start' && type !== 'step_delta' && type !== 'step_end')) {
+    return;
+  }
+  const existing = steps.find((s) => s.stepKey === key);
+  if (type === 'step_start') {
+    if (existing) {
+      existing.status = 'running';
+      if (event.title) existing.title = event.title;
+      if (event.speaker) existing.speaker = event.speaker;
+      if (event.expertName) existing.expertName = event.expertName;
+      return;
+    }
+    const kind: ProcessStepKind = KINDS.includes(event.kind) ? event.kind : kindOfKey(key);
+    steps.push({
+      stepKey: key,
+      seq: toNum(event.seq) ?? steps.length + 1,
+      kind,
+      title: event.title || titleOfKind(kind),
+      status: 'running',
+      speaker: event.speaker,
+      expertName: event.expertName,
+      refKey: event.refKey,
+    });
+    return;
+  }
+  if (type === 'step_delta') {
+    if (!existing || existing.kind !== 'thinking') return;
+    existing.thinkingText = (existing.thinkingText ?? '') + (event.delta ?? '');
+    return;
+  }
+  // step_end
+  let step = existing;
+  if (!step) {
+    const kind = kindOfKey(key);
+    step = {
+      stepKey: key,
+      seq: steps.length + 1,
+      kind,
+      title: titleOfKind(kind),
+      status: event.status ?? 'success',
+    };
+    steps.push(step);
+  }
+  if (event.status) step.status = event.status;
+  if (event.conclusion != null) step.conclusion = event.conclusion;
+  const duration = toNum(event.durationMs);
+  if (duration != null) step.durationMs = duration;
+  if (event.detail && typeof event.detail === 'object') {
+    step.detail = { ...(step.detail ?? {}), ...event.detail };
+  }
+}
+
+/**
+ * 专家输出镜像:text_delta 带 speaker=expert 时,把同一片增量追加进对应专家步详情。
+ * 正文追加逻辑在 index.vue 保持不变(零额外流式体积)。
+ */
+export function mirrorExpertDelta(steps: ProcessStep[], event: any): void {
+  if (event?.speaker !== 'expert' || !event?.delta) return;
+  let step = event.stepKey ? steps.find((s) => s.stepKey === event.stepKey) : undefined;
+  if (!step) {
+    // 回退:最后一个运行中的专家步
+    for (let i = steps.length - 1; i >= 0; i--) {
+      if (steps[i].kind === 'expert' && (steps[i].status === 'running' || steps[i].status === 'waiting')) {
+        step = steps[i];
+        break;
+      }
+    }
+  }
+  if (step && step.kind === 'expert') {
+    step.mirrorText = (step.mirrorText ?? '') + event.delta;
+  }
+}
+
+/**
+ * 历史回放:把 steps REST 返回的 VO 映射为 ProcessStep(解析 detailJson)。
+ */
+export function buildStepsFromVo(vos: ChatMessageStepVO[]): ProcessStep[] {
+  const steps: ProcessStep[] = [];
+  for (const vo of vos ?? []) {
+    if (!vo?.stepKey) continue;
+    let detail: Record<string, any> | undefined;
+    if (vo.detailJson) {
+      try {
+        detail = JSON.parse(vo.detailJson);
+      } catch {
+        detail = undefined;
+      }
+    }
+    const kind: ProcessStepKind = KINDS.includes(vo.kind as ProcessStepKind)
+      ? (vo.kind as ProcessStepKind)
+      : kindOfKey(vo.stepKey);
+    const step: ProcessStep = {
+      stepKey: vo.stepKey,
+      seq: toNum(vo.seq) ?? steps.length + 1,
+      kind,
+      title: vo.title || titleOfKind(kind),
+      status: vo.status ?? 'success',
+      speaker: vo.speaker,
+      expertName: vo.expertName,
+      conclusion: vo.conclusion,
+      durationMs: toNum(vo.durationMs),
+      detail,
+    };
+    if (kind === 'thinking' && typeof detail?.text === 'string') {
+      step.thinkingText = detail.text;
+    }
+    if (kind === 'expert' && typeof detail?.rawOutput === 'string') {
+      step.mirrorText = detail.rawOutput;
+    }
+    if (kind === 'tool' && detail?.toolCallId) {
+      step.refKey = String(detail.toolCallId);
+    }
+    steps.push(step);
+  }
+  return steps;
+}
+
+export interface ProcessSummary {
+  count: number;
+  thinkingMs: number;
+  activeTitle?: string;
+  hasThinking: boolean;
+}
+
+/** 摘要行数据:步骤数 / 思考总耗时 / 当前活动步标题 */
+export function summarizeSteps(steps: ProcessStep[]): ProcessSummary {
+  let thinkingMs = 0;
+  let hasThinking = false;
+  let activeTitle: string | undefined;
+  for (const step of steps) {
+    if (step.kind === 'thinking') {
+      hasThinking = true;
+      thinkingMs += toNum(step.durationMs) ?? 0;
+    }
+    if (step.status === 'running') {
+      activeTitle = step.title;
+    }
+  }
+  return { count: steps.length, thinkingMs, activeTitle, hasThinking };
+}
+
+/** tool 步关联的既有 tool part(入参/出参来自 tool_call_* 事件,实时链路的数据源) */
+export function findLinkedPart(parts: any[] | undefined, step: ProcessStep): any | undefined {
+  if (step.kind !== 'tool' || !step.refKey) return undefined;
+  return (parts ?? []).find((p) => p?.kind === 'tool' && p.toolCallId === step.refKey);
+}
+
+/** 状态 → a-tag 颜色 */
+export function stepStatusColor(status: string): string {
+  switch (status) {
+    case 'running':
+      return 'processing';
+    case 'success':
+    case 'approved':
+      return 'success';
+    case 'error':
+    case 'rejected':
+      return 'error';
+    case 'waiting':
+      return 'warning';
+    default:
+      return 'default';
+  }
+}
+
+/** 状态 → 中文标签 */
+export function stepStatusLabel(status: string): string {
+  const map: Record<string, string> = {
+    running: '进行中',
+    success: '成功',
+    error: '失败',
+    skipped: '已跳过',
+    waiting: '等待确认',
+    approved: '已允许',
+    rejected: '已拒绝',
+    expired: '已失效',
+    aborted: '已中止',
+  };
+  return map[status] ?? status;
+}
+
+/** kind → 图标(i-mdi) */
+export function stepIcon(kind: ProcessStepKind): string {
+  const map: Record<ProcessStepKind, string> = {
+    thinking: 'i-mdi:brain',
+    route: 'i-mdi:share-variant-outline',
+    tool: 'i-mdi:tools',
+    expert: 'i-mdi:account-tie-outline',
+    confirm: 'i-mdi:lock-outline',
+    integration: 'i-mdi:playlist-check',
+  };
+  return map[kind] ?? 'i-mdi:checkbox-blank-circle-outline';
+}
+
+/** 耗时格式化:<1s 显示 ms,否则保留一位小数的秒(入参可能是后端 Long→String 的字符串) */
+export function formatDuration(ms?: number | string): string {
+  const n = toNum(ms);
+  if (n == null) return '';
+  if (n < 1000) return `${n} ms`;
+  return `${(n / 1000).toFixed(1)} s`;
+}

+ 80 - 0
ai-electron/frontend/src/workbench/styles/workbench.less

@@ -654,6 +654,61 @@
   border-top: 1px solid #eff2f7;
 }
 
+/* ------------------------------------------------------------------ *
+ * 抽屉 / 侧边栏通用加固:
+ * 1) 关闭按钮扩大命中区域并给明确悬浮反馈,避免「点不到 / 点了没反应」;
+ * 2) 去掉抽屉面板整圈 focus 描边(自动聚焦导致的蓝色边框,观感像坏掉);
+ * 3) 顶栏显式压低层级,确保任何模式下都不会盖住抽屉头部与关闭按钮。
+ * 适用于链路详情 / 编排运行详情 / 首登清单 / 聊天来源 / 批量进度等所有抽屉。
+ * ------------------------------------------------------------------ */
+.app-topbar {
+  position: relative;
+  z-index: 400;
+}
+
+.ant-drawer {
+  z-index: 1000;
+}
+
+.ant-drawer-content:focus,
+.ant-drawer-content:focus-visible,
+.ant-drawer-content-wrapper:focus,
+.ant-drawer-content-wrapper:focus-visible {
+  outline: none;
+}
+
+.ant-drawer-close {
+  display: inline-flex;
+  align-items: center;
+  justify-content: center;
+  width: 32px;
+  height: 32px;
+  margin: 0;
+  padding: 0;
+  border-radius: 8px;
+  color: #64748b;
+  transition: background 0.15s, color 0.15s;
+
+  &:hover {
+    background: #eef2f7;
+    color: #111827;
+  }
+
+  &:focus-visible {
+    outline: 2px solid #2a50ec;
+    outline-offset: 1px;
+  }
+
+  .anticon {
+    font-size: 16px;
+  }
+}
+
+.ant-drawer-header {
+  position: relative;
+  z-index: 1;
+}
+
 // 表格操作列:统一按钮尺寸与图标大小,覆盖页面表格、详情弹框与抽屉内的表格
 .wb-page,
 .wb-ops-modal,
@@ -700,3 +755,28 @@
 .chat-workbench .ant-btn {
   border-radius: 6px !important;
 }
+
+// 执行过程面板(思考过程 + 分步结论)内部滚动条:取色自工作台令牌,不用浏览器默认
+.process-scroll {
+  scrollbar-width: thin;
+  scrollbar-color: var(--wb-border) transparent;
+
+  &::-webkit-scrollbar {
+    width: 6px;
+    height: 6px;
+  }
+
+  &::-webkit-scrollbar-track {
+    background: transparent;
+  }
+
+  &::-webkit-scrollbar-thumb {
+    background: var(--wb-border);
+    border-radius: 3px;
+
+    &:hover {
+      background: var(--wb-text-muted);
+    }
+  }
+}
+

+ 6 - 1
ai-electron/frontend/src/workbench/views/agent/memory/index.vue

@@ -242,7 +242,12 @@
               option-label-prop="label"
               @change="handleScopeChange"
             >
-              <a-select-option v-for="item in agentOptions" :key="item.id" :label="item.agentName" :value="item.id" />
+              <a-select-option
+                v-for="item in agentOptions"
+                :key="item.id"
+                :label="item.agentName || item.agentCode"
+                :value="item.id"
+              >{{ item.agentName || item.agentCode }}</a-select-option>
             </a-select>
             <a-button @click="handleScopeChange"> 刷新文件 </a-button>
             <span v-if="!form.enabled" class="filter-tip">长期记忆当前为关闭状态,以下为已落盘的历史记忆。</span>

+ 1 - 1
ai-electron/frontend/src/workbench/views/agent/pack/index.vue

@@ -259,7 +259,7 @@
             placeholder="请选择包内技能"
             style="width: 100%"
           >
-            <a-select-option v-for="item in skillOptions" :key="item.id" :label="item.name" :value="item.id" />
+            <a-select-option v-for="item in skillOptions" :key="item.id" :label="item.name" :value="item.id">{{ item.name }}</a-select-option>
           </a-select>
         </a-form-item>
         <a-form-item name="status">

+ 346 - 9
ai-electron/frontend/src/workbench/views/chat/index.vue

@@ -135,9 +135,23 @@
               <img class="avatar__logo" :src="logo" alt="数剑" />
             </div>
             <div class="bubble bubble--assistant">
+              <!-- 执行过程(思考过程 + 分步结论):有步骤时统一折叠面板呈现,legacy 工具/专家/路由卡片抑制;
+                   confirm 交互卡与正文仍在下方原位(面板内只读镜像) -->
+              <ProcessPanel
+                v-if="msg.steps && msg.steps.length"
+                :steps="msg.steps"
+                :streaming="msg.streaming"
+                :aborted="msg.status === '3'"
+                :duration-ms="msg.durationMs"
+                :parts="msg.parts"
+                :expanded="isProcessExpanded(msg)"
+                :overflow="msg.processOverflow"
+                :session-id="currentSessionId"
+                @toggle="toggleProcess(msg)"
+              />
               <template v-for="(part, index) in msg.parts" :key="index">
                 <AiMarkdown v-if="part.kind === 'text'" :content="part.text ?? ''" />
-                <div v-else-if="part.kind === 'tool'" class="tool-card">
+                <div v-else-if="part.kind === 'tool' && !msg.steps?.length" class="tool-card">
                   <div
                     class="tool-card__head"
                     role="button"
@@ -173,7 +187,7 @@
                     </div>
                   </div>
                 </div>
-                <div v-else-if="part.kind === 'expert'" class="expert-card">
+                <div v-else-if="part.kind === 'expert' && !msg.steps?.length" class="expert-card">
                   <div
                     class="expert-card__head"
                     role="button"
@@ -205,11 +219,18 @@
                     <pre class="tool-code">{{ part.expertConclusion || '(暂无可展示的结论原文)' }}</pre>
                   </div>
                 </div>
-                <div v-else-if="part.kind === 'route'" class="route-note">
+                <div v-else-if="part.kind === 'route' && !msg.steps?.length" class="route-note">
                   <Icon class="route-note__icon" icon="i-mdi:share-variant-outline" />
                   <span>{{ part.reason }}</span>
                 </div>
-                <div v-else class="confirm-card" :class="`confirm-card--${part.confirmState}`">
+                <PlanApprovalCard
+                  v-else-if="part.kind === 'confirm' && isPlanConfirm(part)"
+                  :part="part"
+                  @approve="handleConfirmTool(part, true, false)"
+                  @reject="handleRejectTool(part)"
+                  @open-doc="openPlanDoc"
+                />
+                <div v-else-if="part.kind === 'confirm'" class="confirm-card" :class="`confirm-card--${part.confirmState}`">
                   <div class="confirm-card__head">
                     <Icon class="confirm-card__icon" icon="i-mdi:lock-outline" />
                     <span class="confirm-card__title">该操作需要你确认后才会执行</span>
@@ -674,8 +695,36 @@
         <a-spin v-if="artifactPreview.loading" class="artifact-preview__loading" />
         <div v-else-if="artifactPreview.error" class="artifact-preview__error">{{ artifactPreview.error }}</div>
         <template v-else-if="artifactPreview.item">
+          <div v-if="artifactPreview.item.kind === 'markdown'" class="artifact-preview__md-bar">
+            <div class="artifact-preview__md-modes">
+              <button
+                type="button"
+                :class="{ 'is-on': artifactPreview.mdMode === 'rendered' }"
+                @click="artifactPreview.mdMode = 'rendered'"
+              >
+                渲染
+              </button>
+              <button
+                type="button"
+                :class="{ 'is-on': artifactPreview.mdMode === 'source' }"
+                @click="artifactPreview.mdMode = 'source'"
+              >
+                源码
+              </button>
+            </div>
+            <button type="button" class="artifact-preview__md-dl" @click="handleDownloadArtifact(artifactPreview.item!)">
+              下载
+            </button>
+          </div>
+          <div
+            v-if="artifactPreview.item.kind === 'markdown' && artifactPreview.mdMode === 'rendered'"
+            class="artifact-preview__md"
+          >
+            <AiMarkdown :content="artifactPreview.content" />
+          </div>
+          <pre v-else-if="artifactPreview.item.kind === 'markdown'" class="artifact-preview__text">{{ artifactPreview.content }}</pre>
           <iframe
-            v-if="artifactPreview.item.kind === 'html'"
+            v-else-if="artifactPreview.item.kind === 'html'"
             class="artifact-preview__html"
             :srcdoc="artifactPreview.content"
           ></iframe>
@@ -785,7 +834,7 @@
 </template>
 
 <script setup name="AiAgentChat" lang="ts">
-  import { computed, h, nextTick, onActivated, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
+  import { computed, h, nextTick, onActivated, onBeforeUnmount, onDeactivated, onMounted, reactive, ref, watch } from 'vue';
   import { useRouter } from 'vue-router';
   import {
     Button as AButton,
@@ -821,6 +870,7 @@
     listChatResources,
     listChatRouteRuns,
     listChatSession,
+    listChatSteps,
     listChatToolCall,
     pinChatSessionExpert,
     removeChatResources,
@@ -835,6 +885,7 @@
   import type {
     AiRouteRunDetailVO,
     ChatAttachmentVO,
+    ChatMessageStepVO,
     ChatMessageVO,
     ChatPendingToolCall,
     ChatPermissionMode,
@@ -872,6 +923,14 @@
   import { Icon } from '@/core/components/Icon';
   import AiMarkdown from '@/workbench/components/AiMarkdown.vue';
   import PromptModal from '@/workbench/components/PromptModal.vue';
+  import ProcessPanel from '@/workbench/components/chat/ProcessPanel.vue';
+  import PlanApprovalCard from '@/workbench/components/chat/PlanApprovalCard.vue';
+  import {
+    applyStepEvent,
+    buildStepsFromVo,
+    mirrorExpertDelta,
+    type ProcessStep,
+  } from '@/workbench/components/chat/processTypes';
 
   type ExpertOptionVO = Record<string, any>;
   type ScenarioPackOptionVO = Record<string, any>;
@@ -958,6 +1017,12 @@
     };
     /** 对话期实时进度文案(后端 phase 事件下发;正文开始流动即清空) */
     phaseText?: string;
+    /** 执行过程时间线(思考过程 + 分步结论;有步骤时抑制 legacy 工具/专家/路由卡片) */
+    steps?: ProcessStep[];
+    /** 用户手动展开/折叠过过程面板(自动展开/折叠行为让位) */
+    processUserToggled?: boolean;
+    /** 步骤数超出上限(摘要显示 200+) */
+    processOverflow?: boolean;
   }
 
   /** 资源标签(REQ-AI-32):+ 后面显示的选中项,悬停左侧出叉号可移除 */
@@ -1148,6 +1213,7 @@
     objectUrl: string;
     csvHeader: string[];
     csvRows: string[][];
+    mdMode: 'rendered' | 'source';
   }>({
     visible: false,
     loading: false,
@@ -1158,6 +1224,7 @@
     objectUrl: '',
     csvHeader: [],
     csvRows: [],
+    mdMode: 'rendered',
   });
 
   /** 展开 / 收起产物面板 */
@@ -1297,6 +1364,7 @@
     artifactPreview.visible = true;
     artifactPreview.item = item;
     artifactPreview.loading = true;
+    artifactPreview.mdMode = 'rendered';
     try {
       if (item.kind === 'image' || item.kind === 'pdf') {
         let blob = await fetchArtifactBlob(sessionId, item.path);
@@ -1412,7 +1480,16 @@
     syncWorkbenchHeight();
   });
 
+  /** 离开聊天页(keep-alive 失活):关闭 SSE,让后端按「运行中→中止 / 已暂停→保留待确认」收尾,
+   *  避免残留运行与回来后的确认/恢复冲突(连接中断)。 */
+  onDeactivated(() => {
+    closeStream();
+    streaming.value = false;
+  });
+
   onBeforeUnmount(() => {
+    closeStream();
+    streaming.value = false;
     workbenchTimers.forEach((timer) => window.clearTimeout(timer));
     workbenchTimers = [];
     if (artifactRefreshTimer) {
@@ -1581,6 +1658,71 @@
       : [...expandedSourceKeys.value, key];
   };
 
+  /** 执行过程面板展开态的键(按消息主键;流式中自动展开、完成后自动折叠,用户手动操作后让位) */
+  const expandedProcessKeys = ref<string[]>([]);
+
+  /** 过程面板是否展开 */
+  const isProcessExpanded = (msg: LocalMessage) => expandedProcessKeys.value.includes(String(msg.id));
+
+  /** 展开 / 收起过程面板(标记用户已手动操作,自动行为让位) */
+  const toggleProcess = (msg: LocalMessage) => {
+    const key = String(msg.id);
+    msg.processUserToggled = true;
+    expandedProcessKeys.value = isProcessExpanded(msg)
+      ? expandedProcessKeys.value.filter((item) => item !== key)
+      : [...expandedProcessKeys.value, key];
+  };
+
+  /** 自动展开过程面板(仅用户未手动操作时) */
+  const autoExpandProcess = (msg: LocalMessage) => {
+    if (msg.processUserToggled) return;
+    const key = String(msg.id);
+    if (!expandedProcessKeys.value.includes(key)) {
+      expandedProcessKeys.value = [...expandedProcessKeys.value, key];
+    }
+  };
+
+  /** 自动折叠过程面板(仅用户未手动操作时) */
+  const autoCollapseProcess = (msg: LocalMessage) => {
+    if (msg.processUserToggled) return;
+    const key = String(msg.id);
+    expandedProcessKeys.value = expandedProcessKeys.value.filter((item) => item !== key);
+  };
+
+  /**
+   * 消息主键归位时迁移过程面板展开键:流式期用占位 id,done/aborted/tool_confirm 会换成真实
+   * messageId,展开键须随之迁移,否则展开态丢失(用户手动展开的面板会被意外折叠)。
+   */
+  const rekeyProcess = (msg: LocalMessage, newId: string | number | undefined) => {
+    if (newId === undefined || newId === null) return;
+    const oldKey = String(msg.id);
+    const newKey = String(newId);
+    if (oldKey === newKey) return;
+    if (expandedProcessKeys.value.includes(oldKey)) {
+      expandedProcessKeys.value = [...expandedProcessKeys.value.filter((item) => item !== oldKey), newKey];
+    }
+  };
+
+  /**
+   * 执行过程权威对齐:done/aborted 后拉 steps REST 覆盖 live 构建的步骤。
+   *
+   * 顺带带回专家完整原文(detail_json.rawOutput)与子工具详情;失败不影响 live 步骤展示。
+   * legacy 消息(无步骤)仍走 syncExpertConclusions 回填专家卡片。
+   */
+  const syncSteps = async (msg: LocalMessage) => {
+    const sessionId = currentSessionId.value;
+    if (!sessionId) return;
+    try {
+      const res = await listChatSteps(sessionId);
+      const mine = (res ?? []).filter((item) => String(item.messageId ?? '') === String(msg.id));
+      if (mine.length) {
+        msg.steps = buildStepsFromVo(mine);
+      }
+    } catch {
+      // 步骤对齐失败不影响回答展示(live 步骤仍在)
+    }
+  };
+
   /** 工具状态标签颜色 */
   const toolStateType = (state?: string): ElTagType => {
     if (state === 'success') {
@@ -2425,12 +2567,16 @@
     }
     // 工具卡片展开态不跨会话保留
     expandedToolKeys.value = [];
+    // 过程面板展开态不跨会话保留
+    expandedProcessKeys.value = [];
     // 资源选择(REQ-AI-32):切会话时载入该会话的服务端资源集与指定专家
     await loadSessionResourceSet(session);
-    const [messageRes, toolRes, routeRes] = await Promise.all([
+    const [messageRes, toolRes, routeRes, stepRes] = await Promise.all([
       listChatMessage(session.id),
       listChatToolCall(session.id),
       listChatRouteRuns(session.id),
+      // 执行步骤(精确回放):失败降级为空数组,旧消息走 legacy 卡片渲染
+      listChatSteps(session.id).catch(() => [] as ChatMessageStepVO[]),
     ]);
     const toolsByMessage = new Map<string, ToolCallLogVO[]>();
     (toolRes ?? []).forEach((tool) => {
@@ -2445,9 +2591,21 @@
         runByMessage.set(String(run.messageId), run);
       }
     });
+    const stepsByMessage = new Map<string, ChatMessageStepVO[]>();
+    (stepRes ?? []).forEach((step) => {
+      const key = String(step.messageId);
+      const list = stepsByMessage.get(key) ?? [];
+      list.push(step);
+      stepsByMessage.set(key, list);
+    });
     messages.value = (messageRes ?? []).map((item) => {
       const local = toLocalMessage(item, toolsByMessage.get(String(item.id)) ?? []);
       appendRouteParts(local, runByMessage.get(String(item.id)));
+      // 有步骤的消息精确还原过程时间线(抑制 legacy 卡片);存量旧消息无步骤走原渲染
+      const stepVos = stepsByMessage.get(String(item.id));
+      if (stepVos?.length) {
+        local.steps = buildStepsFromVo(stepVos);
+      }
       return local;
     });
     // 恢复未决的工具确认卡片(Redis 暂存失效时标记为已过期)
@@ -2685,7 +2843,9 @@
         return;
       }
       // 暂存旧回答:后端若在预检 / 上下文回退阶段拒绝,需要把它放回
-      regenerateBackup = messages.value.slice(userIndex + 1).map((item) => ({ ...item, parts: [...item.parts] }));
+      regenerateBackup = messages.value
+        .slice(userIndex + 1)
+        .map((item) => ({ ...item, parts: [...item.parts], steps: item.steps ? [...item.steps] : undefined }));
       messages.value.splice(userIndex + 1);
       const tempId = `pending-${Date.now()}`;
       messages.value.push({
@@ -2749,6 +2909,13 @@
       clearPhase(msg);
       // 前端随即关闭 SSE,很可能收不到后端随后的 aborted 事件,故本地即时标记「已中止」
       msg.status = '3';
+      // 过程面板:running 步本地标为已中止(与消息状态同口径),并自动折叠
+      msg.steps?.forEach((step) => {
+        if (step.status === 'running') {
+          step.status = 'aborted';
+        }
+      });
+      autoCollapseProcess(msg);
     }
     finishStream();
     // 中止时已落盘的部分产物也要展示
@@ -2756,6 +2923,30 @@
   };
 
   /** 处置待确认的工具调用:写入结果后建立恢复流继续生成 */
+  /** 是否为计划模式的「批准计划」确认(plan_exit):用专用计划卡而非通用 raw-JSON 确认卡 */
+  const isPlanConfirm = (part: MessagePart) =>
+    part.kind === 'confirm' &&
+    (part.toolCalls ?? []).some((c) => c.toolName === 'plan_exit' || /批准计划/.test(c.toolLabel || ''));
+
+  /** 打开计划文档(plans/PLAN.md)渲染预览;尚未生成时给出提示 */
+  const openPlanDoc = async () => {
+    const sessionId = currentSessionId.value;
+    if (!sessionId) return;
+    try {
+      const res = await listArtifacts(sessionId);
+      const doc = (res?.items ?? []).find(
+        (it) => it.name === 'PLAN.md' || it.path.endsWith('plans/PLAN.md'),
+      );
+      if (doc) {
+        await previewArtifact(doc);
+      } else {
+        antMessage.info('计划文档尚未生成(plans/PLAN.md),批准后将随执行落地');
+      }
+    } catch (error) {
+      antMessage.error((error as Error)?.message || '计划文档加载失败');
+    }
+  };
+
   const handleConfirmTool = async (part: MessagePart, confirmed: boolean, remember: boolean, rejectReason?: string) => {
     // 只有待确认卡片可处置:挡住连点与竞态(已被置为 expired 的旧卡片不再重复提交)
     if (part.confirmState !== 'pending') {
@@ -2839,6 +3030,23 @@
           msg.parts.push({ kind: 'text', text: delta });
         }
         msg.content += delta;
+        // 专家输出镜像:speaker=expert 时同一片增量也进过程面板的专家步详情(正文逻辑不变)
+        if (msg.steps?.length) {
+          mirrorExpertDelta(msg.steps, event);
+        }
+        break;
+      }
+      case 'step_start':
+      case 'step_delta':
+      case 'step_end': {
+        // 执行过程时间线(思考过程 + 分步结论):按 stepKey upsert,恢复段续接同一步骤
+        if (!msg.steps) {
+          msg.steps = [];
+        }
+        applyStepEvent(msg.steps, event);
+        if (event.type === 'step_start') {
+          autoExpandProcess(msg);
+        }
         break;
       }
       case 'tool_call_start': {
@@ -2880,9 +3088,12 @@
       }
       case 'tool_confirm': {
         // 工具被配置为「需人工确认」:本轮暂停,等待用户处置后再恢复
+        rekeyProcess(msg, event.messageId);
         msg.id = event.messageId ?? msg.id;
         msg.streaming = false;
         clearPhase(msg);
+        // 暂停期面板保持展开,让用户看到 waiting 的确认步与运行中的工具步
+        autoExpandProcess(msg);
         // 后端待确认按 messageId 唯一暂存:同一助手消息内第二次暂停会覆盖旧槽位,
         // 若旧卡片仍留在前端且 messageId 与新卡片相同,用户点旧卡片时后端处理的却是新一批
         // 工具调用(点 A 却执行了 B)。故先把同消息内已有的 pending 卡片统一置为 expired。
@@ -2962,6 +3173,7 @@
         break;
       }
       case 'done': {
+        rekeyProcess(msg, event.messageId);
         msg.id = event.messageId ?? msg.id;
         msg.streaming = false;
         clearPhase(msg);
@@ -2977,17 +3189,35 @@
         regenerateBackup = null;
         void refreshRegenerateCheck();
         getSessions();
-        // 编排轨迹回填:异步补齐专家原始结论,不阻塞本轮收尾
+        // 执行过程:自动折叠为摘要行 + 拉 steps REST 权威对齐(带回专家原文与子工具详情)
+        if (msg.steps?.length) {
+          msg.processOverflow = (event.stepCount ?? 0) > msg.steps.length;
+          autoCollapseProcess(msg);
+          void syncSteps(msg);
+        }
+        // 编排轨迹回填:异步补齐专家原始结论(legacy 消息;有步骤的消息由 syncSteps 覆盖)
         void syncExpertConclusions(msg);
         break;
       }
       case 'aborted': {
         // 中止也按收尾处理:给用户明确的「已中止」反馈(兜底服务端主动中止等场景)
+        rekeyProcess(msg, event.messageId);
         msg.id = event.messageId ?? msg.id;
         msg.streaming = false;
         clearPhase(msg);
         msg.durationMs = event.durationMs ?? msg.durationMs;
         msg.status = '3';
+        // 执行过程:running 步标为已中止并折叠(后端 abortRunning 可能已下发,此处兜底)
+        if (msg.steps?.length) {
+          msg.steps.forEach((step) => {
+            if (step.status === 'running') {
+              step.status = 'aborted';
+            }
+          });
+          msg.processOverflow = (event.stepCount ?? 0) > msg.steps.length;
+          autoCollapseProcess(msg);
+          void syncSteps(msg);
+        }
         finishStream();
         scheduleArtifactRefresh();
         regenerateBackup = null;
@@ -3005,6 +3235,12 @@
         clearPhase(msg);
         msg.status = '1';
         msg.errorMsg = event.message || '对话失败';
+        // 执行过程:保留已走步骤供排障,running 步标为已中止
+        msg.steps?.forEach((step) => {
+          if (step.status === 'running') {
+            step.status = 'aborted';
+          }
+        });
         antMessage.error(msg.errorMsg);
         finishStream();
         scheduleArtifactRefresh();
@@ -5320,6 +5556,49 @@
     text-align: center;
   }
 
+  /* 全屏放大时让预览内容填充满弹框:ModalWrapper 全屏给 spin 容器固定高度,
+     这里把预览区改为弹性列并解除 60vh/65vh 上限,内容随弹框高度伸展 */
+  .fullscreen-modal .artifact-preview {
+    display: flex;
+    flex-direction: column;
+    height: 100%;
+    min-height: 0;
+  }
+
+  .fullscreen-modal .artifact-preview__md-bar {
+    flex: none;
+  }
+
+  .fullscreen-modal .artifact-preview__html,
+  .fullscreen-modal .artifact-preview__pdf {
+    flex: 1;
+    min-height: 0;
+    height: auto;
+  }
+
+  .fullscreen-modal .artifact-preview__md,
+  .fullscreen-modal .artifact-preview__text,
+  .fullscreen-modal .artifact-preview__table-wrap {
+    flex: 1;
+    min-height: 0;
+    max-height: none;
+    height: auto;
+  }
+
+  .fullscreen-modal .artifact-preview__image {
+    flex: 1;
+    min-height: 0;
+    max-height: none;
+    width: 100%;
+    height: 100%;
+    object-fit: contain;
+  }
+
+  .fullscreen-modal .artifact-preview__loading,
+  .fullscreen-modal .artifact-preview__error {
+    flex: 1;
+  }
+
   .artifact-preview__html {
     width: 100%;
     height: 60vh;
@@ -5385,6 +5664,64 @@
     border-radius: 8px;
   }
 
+  .artifact-preview__md-bar {
+    display: flex;
+    align-items: center;
+    gap: 10px;
+    margin-bottom: 10px;
+  }
+
+  .artifact-preview__md-modes {
+    display: inline-flex;
+    padding: 2px;
+    background: #f1f5f9;
+    border: 1px solid var(--wb-border, #e7ebf3);
+    border-radius: 8px;
+
+    button {
+      padding: 4px 14px;
+      font-size: 12.5px;
+      color: var(--wb-text-2, #667085);
+      background: transparent;
+      border: 0;
+      border-radius: 6px;
+      cursor: pointer;
+      transition: 0.15s;
+
+      &.is-on {
+        color: var(--wb-primary, #2a50ec);
+        background: #fff;
+        font-weight: 600;
+        box-shadow: 0 1px 3px rgba(15, 23, 42, 0.1);
+      }
+    }
+  }
+
+  .artifact-preview__md-dl {
+    margin-left: auto;
+    padding: 4px 12px;
+    font-size: 12.5px;
+    color: var(--wb-text-2, #667085);
+    background: #fff;
+    border: 1px solid var(--wb-border, #e7ebf3);
+    border-radius: 6px;
+    cursor: pointer;
+
+    &:hover {
+      color: var(--wb-primary, #2a50ec);
+      border-color: var(--wb-primary, #2a50ec);
+    }
+  }
+
+  .artifact-preview__md {
+    max-height: 60vh;
+    overflow: auto;
+    padding: 18px 22px;
+    background: #fff;
+    border: 1px solid var(--wb-border, #e7ebf3);
+    border-radius: 8px;
+  }
+
   .artifact-preview__hint {
     margin-top: 8px;
     color: var(--wb-text-2, #667085);

+ 29 - 0
ai-electron/frontend/src/workbench/views/model/config/index.vue

@@ -156,6 +156,19 @@
             <a-radio value="0">否</a-radio>
           </a-radio-group>
         </a-form-item>
+        <a-form-item
+          v-if="isChatForm"
+          label="思考模式"
+          extra="开启后模型输出推理过程,聊天「执行过程」面板展示深度思考步;留空跟随模型/供应商默认"
+        >
+          <a-select
+            v-model:value="form.enableThinking"
+            allow-clear
+            placeholder="跟随模型默认"
+            style="width: 200px"
+            :options="thinkingOptions"
+          />
+        </a-form-item>
         <template v-if="isLocalForm">
           <a-divider orientation="left">本地模型</a-divider>
           <a-form-item>
@@ -237,6 +250,15 @@
           <a-descriptions-item label="支持视觉">{{
             detail.record.modelType !== 'chat' ? '-' : detail.record.supportsVision === '0' ? '否' : '是'
           }}</a-descriptions-item>
+          <a-descriptions-item label="思考模式">{{
+            detail.record.modelType !== 'chat'
+              ? '-'
+              : detail.record.enableThinking === true
+                ? '强制开启'
+                : detail.record.enableThinking === false
+                  ? '强制关闭'
+                  : '跟随默认'
+          }}</a-descriptions-item>
           <a-descriptions-item label="密钥">{{
             isLocalProvider(detail.record.provider) ? '无需密钥(本地推理)' : detail.record.apiKeyMask || '未配置'
           }}</a-descriptions-item>
@@ -340,6 +362,7 @@
     modelType: 'chat',
     modelCode: undefined,
     supportsVision: '1',
+    enableThinking: undefined,
     baseUrl: PROVIDER_OPTIONS[1].baseUrl,
     apiKey: undefined,
     dimension: undefined,
@@ -351,6 +374,12 @@
     remark: undefined,
   };
 
+  /** 思考模式选项:boolean 值(antd 类型仅声明 string|number,此处放宽;后端 BO 为 Boolean) */
+  const thinkingOptions: any[] = [
+    { value: true, label: '强制开启' },
+    { value: false, label: '强制关闭' },
+  ];
+
   /** 是否本地 ONNX 模型提供商(兼容历史别名:含 onnx / 本地 / 内置;排除 Ollama 等本地 HTTP 服务) */
   function isLocalProvider(value?: string) {
     const normalized = String(value ?? '')

+ 29 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/config/AiProperties.java

@@ -280,6 +280,35 @@ public class AiProperties {
          */
         private long streamTimeoutMs = 0L;
 
+        /**
+         * 「执行过程」时间线总开关(思考过程 + 分步结论)。
+         *
+         * <p>false 时不装配时间线、不下发 step_* 事件、不落步骤明细,全链路回到现状
+         * (docs/design/chat-process-timeline-plan.md §3.6)。</p>
+         */
+        private boolean processStepsEnabled = true;
+
+        /**
+         * 思考全文落库上限(字符;内存上限恒为 16000)
+         */
+        private int thinkingDetailMaxChars = 8000;
+
+        /**
+         * 一行结论截断长度(字符)
+         */
+        private int stepConclusionChars = 80;
+
+        /**
+         * 单消息步骤上限(超出只计数不落详情,摘要显示「200+ 个步骤」)
+         */
+        private int maxStepsPerMessage = 200;
+
+        /**
+         * 可选:LLM 一句话结论精炼(默认关)。开启后收尾异步用对话模型把确定性结论
+         * 精炼为更自然的一句话(关闭思考、限 80 token、20 秒超时),失败回退确定性结论。
+         */
+        private boolean stepLlmConclusionEnabled = false;
+
         /**
          * 单次专家调用的同步等待上限(秒),{@code <=0} 时回退为兜底值 180 秒(REQ-AI-30)。
          *

+ 14 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/controller/AiChatController.java

@@ -22,6 +22,7 @@ import com.zsjz.ai.module.ai.domain.vo.AiRouteRunDetailVo;
 import com.zsjz.ai.module.ai.domain.vo.AiSessionResourceVo;
 import com.zsjz.ai.module.ai.domain.vo.AiSessionVo;
 import com.zsjz.ai.module.ai.domain.vo.AiToolCallLogVo;
+import com.zsjz.ai.module.ai.domain.vo.AiMessageStepVo;
 import com.zsjz.ai.module.ai.service.IAiChatAttachmentService;
 import com.zsjz.ai.module.ai.service.IAiRouteService;
 import com.zsjz.ai.module.ai.service.IAiSessionResourceService;
@@ -243,6 +244,19 @@ public class AiChatController extends BaseController {
         return R.ok(aiSessionService.queryOwnedToolCalls(sessionId));
     }
 
+    /**
+     * 查询会话的消息执行步骤(供对话页精确回放「执行过程」时间线;仅新数据,存量旧消息无行)。
+     *
+     * @param sessionId 会话主键
+     */
+    @SaCheckPermission("ai:chat:query")
+    @GetMapping("/session/{sessionId}/steps")
+    public R<List<AiMessageStepVo>> listSteps(@NotNull(message = "会话不能为空")
+                                              @PathVariable("sessionId") Long sessionId) {
+        aiSessionService.assertSessionInCurrentCase(sessionId);
+        return R.ok(aiSessionService.queryOwnedSteps(sessionId));
+    }
+
     /**
      * 查询会话的编排轨迹(REQ-AI-30)
      *

+ 2 - 1
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AgentAssembler.java

@@ -287,7 +287,8 @@ public class AgentAssembler {
                             McpClientAssembly mcpAssembly, boolean expertMode, boolean planEnabled,
                             String workspaceCode, Long caseId, Long workspaceAgentId) {
         AiModelConfig modelConfig = modelFactory.resolveChatModel(definition.getModelId());
-        Model model = modelFactory.buildChatModel(modelConfig);
+        // 模型级思考模式覆盖(enable_thinking 列,null 跟随模型/供应商默认;过程面板思考步的数据来源)
+        Model model = modelFactory.buildChatModel(modelConfig, modelConfig.getEnableThinking());
         Toolkit toolkit = new Toolkit();
         List<String> registeredCodes = new ArrayList<>(
             registerTools(toolkit, enabledTools, kbIds, expertMode));

+ 12 - 11
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AgentModelFactory.java

@@ -120,6 +120,16 @@ public class AgentModelFactory {
         String baseUrl = resolveBaseUrl(config.getBaseUrl());
         String apiKey = modelConfigService.decryptApiKey(config.getId());
         GenerateOptions generateOptions = buildGenerateOptions(config);
+        // 思考模式覆盖并入 GenerateOptions:提供商扩展 SPI 路径与 OpenAI 兼容回退路径同时生效
+        // (模型级 enable_thinking 配置列,null 保持现状;docs/design/chat-process-timeline-plan.md §12 R1)
+        if (enableThinkingOverride != null) {
+            GenerateOptions.Builder ob = GenerateOptions.builder();
+            if (generateOptions != null && generateOptions.getExecutionConfig() != null) {
+                ob.executionConfig(generateOptions.getExecutionConfig());
+            }
+            ob.additionalBodyParam("enable_thinking", enableThinkingOverride);
+            generateOptions = ob.build();
+        }
         String provider = StringUtils.trim(config.getProvider());
         if (StringUtils.isNotBlank(provider) && StringUtils.isNotBlank(apiKey)) {
             String modelId = provider + ":" + StringUtils.trim(config.getModelCode());
@@ -142,17 +152,8 @@ public class AgentModelFactory {
             .modelName(config.getModelCode())
             .baseUrl(baseUrl)
             .stream(true);
-        GenerateOptions options = generateOptions;
-        if (enableThinkingOverride != null) {
-            GenerateOptions.Builder ob = GenerateOptions.builder();
-            if (options != null && options.getExecutionConfig() != null) {
-                ob.executionConfig(options.getExecutionConfig());
-            }
-            ob.additionalBodyParam("enable_thinking", enableThinkingOverride);
-            options = ob.build();
-        }
-        if (options != null) {
-            builder.generateOptions(options);
+        if (generateOptions != null) {
+            builder.generateOptions(generateOptions);
         }
         return builder.build();
     }

+ 92 - 17
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiChatFacade.java

@@ -28,6 +28,7 @@ import com.zsjz.ai.module.ai.domain.vo.AiMessageVo;
 import com.zsjz.ai.module.ai.domain.vo.AiRegenerateCheckVo;
 import com.zsjz.ai.module.ai.mapper.AiMessageMapper;
 import com.zsjz.ai.module.ai.service.IAiAgentService;
+import com.zsjz.ai.module.ai.service.IAiMessageStepService;
 import com.zsjz.ai.module.ai.service.IAiPermissionDecisionService;
 import com.zsjz.ai.module.ai.service.IAiQuotaService;
 import com.zsjz.ai.module.ai.service.IAiSafetyEventService;
@@ -253,6 +254,11 @@ public class AiChatFacade {
      */
     private final AiTurnFinisher turnFinisher;
 
+    /**
+     * 执行步骤持久化(HITL 恢复段取 maxSeq 续接序号)
+     */
+    private final IAiMessageStepService stepService;
+
     /**
      * 整合轮与指定专家兜底的编排驱动(R4 拆出)
      */
@@ -425,15 +431,38 @@ public class AiChatFacade {
             // 编排器需要把专家侧的待确认信息**上浮**写入入口轮状态,故此处回挂引用
             route.entryState = state;
         }
+        // 执行过程时间线(思考过程 + 分步结论):开关启用时装配,入口/专家/整合段共享同一实例
+        if (aiProperties.getChat().isProcessStepsEnabled()) {
+            AiProcessTimeline timeline = new AiProcessTimeline(emitter, sessionId, 0,
+                aiProperties.getChat().getMaxStepsPerMessage());
+            state.process = timeline;
+            if (route != null) {
+                route.timeline = timeline;
+            }
+        }
         AtomicBoolean finished = new AtomicBoolean(false);
         try {
             AiSseSupport.send(emitter, AiSseSupport.envelope(EVENT_START));
             // SSE 断连 / 超时:取消该会话**当前全部**后端执行(与对话页「停止」同一路径)。
             // 统一在此登记一次——SseEmitter 的回调是单槽覆盖,分支内再注册会顶掉这里;
-            // 故入口轮、短路轮、指定专家兜底、整合轮与恢复段共用这一套(原先只有入口轮分支注册过)
-            emitter.onCompletion(() -> runRegistry.cancel(sessionId));
-            emitter.onTimeout(() -> runRegistry.cancel(sessionId));
-            emitter.onError(ignored -> runRegistry.cancel(sessionId));
+            // 故入口轮、短路轮、指定专家兜底、整合轮与恢复段共用这一套(原先只有入口轮分支注册过)。
+            // 例外:本轮已暂停等待人工确认(pendingConfirm)时**不取消**——切页/断连不应摧毁
+            // 框架的 ASKING 暂停态与 Redis 待确认暂存,否则用户回来点确认会因会话状态被取消而恢复失败。
+            emitter.onCompletion(() -> {
+                if (!state.pendingConfirm) {
+                    runRegistry.cancel(sessionId);
+                }
+            });
+            emitter.onTimeout(() -> {
+                if (!state.pendingConfirm) {
+                    runRegistry.cancel(sessionId);
+                }
+            });
+            emitter.onError(ignored -> {
+                if (!state.pendingConfirm) {
+                    runRegistry.cancel(sessionId);
+                }
+            });
             // 单次执行句柄(AgentScope 2.0.4):登记后可由「停止」/ SSE 断连取消本段后端执行
             AgentRun<AgentEvent> run = agent.prepareRun(
                 List.of(attachmentAssembler.buildUserMsg(userContent, attachmentBlocks)), ctx);
@@ -451,18 +480,33 @@ public class AiChatFacade {
                     // 否则前端收到 done/error 后立刻调用「重新生成」会被误判 CONVERSATION_BUSY
                     runRegistry.unregister(sessionId, cancelable);
                     long durationMs = (System.nanoTime() - startNanos) / 1_000_000;
-                    // 用户停止 / SSE 断连触发的取消:按「已中止」收尾,不当作失败
+                    // 用户停止 / SSE 断连触发的取消:按「已中止」收尾,不当作失败。
+                    // 但若本轮其实已暂停等待确认(pendingConfirm),按「待确认」收尾保留暂停态,
+                    // 使用户切页回来后仍可正常确认并恢复(避免恢复时连接中断)。
                     if (run.status() == AgentRun.Status.CANCELLED) {
-                        turnFinisher.finishCancelled(emitter, sessionId, state, durationMs, null, route);
+                        if (state.pendingConfirm) {
+                            Long pausedId = turnFinisher.finishPending(emitter, sessionId, state, durationMs, route);
+                            turnFinisher.finishRoute(route, pausedId, AiRouteRun.STATUS_PENDING, "等待人工确认", durationMs);
+                        } else {
+                            turnFinisher.finishCancelled(emitter, sessionId, state, durationMs, null, route);
+                        }
                         return;
                     }
                     log.error("对话流式执行失败,sessionId={}", sessionId, error);
                     String message = AiSseSupport.rootCauseMessage(error);
+                    // 执行过程:running 步标为已中止(保留已走步骤供排障)
+                    if (state.process != null) {
+                        state.process.abortRunning(message);
+                    }
                     traceService.appendTransition(state.traceId, "error", message);
                     traceService.accumulate(state.traceId, AiTrace.STATUS_FAILED, durationMs, null,
                         null, null, null, message);
                     try {
-                        sessionService.persistAssistantFailure(sessionId, message, durationMs);
+                        AiMessage failed = sessionService.persistAssistantFailure(sessionId, message, durationMs);
+                        // 执行过程:失败消息也落步骤(保留已走步骤供排障与回放)
+                        if (failed != null) {
+                            turnFinisher.persistProcessSteps(state, sessionId, failed.getId());
+                        }
                     } catch (Exception e) {
                         log.error("落库失败消息异常,sessionId={}", sessionId, e);
                     }
@@ -701,6 +745,13 @@ public class AiChatFacade {
         } else {
             traceService.appendTransition(state.traceId, "resume", "人工确认后恢复执行");
         }
+        // 执行过程:恢复段新建时间线续接(落库按 step_key upsert,seq 保留原值);
+        // 先把暂停段的确认步回填为终态(已允许/已拒绝),前端按同键覆盖
+        if (aiProperties.getChat().isProcessStepsEnabled()) {
+            state.process = new AiProcessTimeline(emitter, sessionId, stepService.maxSeq(messageId),
+                aiProperties.getChat().getMaxStepsPerMessage());
+            AiProcessTimeline.resolveConfirmStep(state.process, pending.replyId(), pending.decisions());
+        }
         AtomicBoolean finished = new AtomicBoolean(false);
         try {
             AiSseSupport.send(emitter, AiSseSupport.envelope(EVENT_START));
@@ -708,10 +759,23 @@ public class AiChatFacade {
             AiPhaseSupport.emit(emitter, state, AiPhaseSupport.PHASE_RESUMING,
                 "数剑正在继续执行你已确认的操作…", null);
             // SSE 断连 / 超时:取消该会话**当前全部**后端执行(与对话页「停止」同一路径)。
-            // 恢复段是**另一条 SSE 请求**,故此处同样要登记(与 streamChat 同款;SseEmitter 回调单槽覆盖)
-            emitter.onCompletion(() -> runRegistry.cancel(sessionId));
-            emitter.onTimeout(() -> runRegistry.cancel(sessionId));
-            emitter.onError(ignored -> runRegistry.cancel(sessionId));
+            // 恢复段是**另一条 SSE 请求**,故此处同样要登记(与 streamChat 同款;SseEmitter 回调单槽覆盖)。
+            // 已暂停等待确认(pendingConfirm)时不取消,保留暂停态供用户回来继续确认。
+            emitter.onCompletion(() -> {
+                if (!state.pendingConfirm) {
+                    runRegistry.cancel(sessionId);
+                }
+            });
+            emitter.onTimeout(() -> {
+                if (!state.pendingConfirm) {
+                    runRegistry.cancel(sessionId);
+                }
+            });
+            emitter.onError(ignored -> {
+                if (!state.pendingConfirm) {
+                    runRegistry.cancel(sessionId);
+                }
+            });
             AgentRun<AgentEvent> run = agent.prepareRun(AiResumeMessageFactory.build(pending), ctx);
             AiRunRegistry.Cancelable cancelable = run::cancel;
             runRegistry.register(sessionId, cancelable);
@@ -726,17 +790,27 @@ public class AiChatFacade {
                     // 执行已结束:先释放互斥再下发收尾事件(与 streamChat 同口径)
                     runRegistry.unregister(sessionId, cancelable);
                     long durationMs = (System.nanoTime() - startNanos) / 1_000_000;
-                    // 用户停止 / SSE 断连触发的取消:按「已中止」收尾,不当作失败
+                    // 用户停止 / SSE 断连触发的取消:按「已中止」收尾,不当作失败。
+                    // 若恢复段内又暂停等待确认(pendingConfirm),保留暂停态与暂存,供用户继续确认。
                     if (run.status() == AgentRun.Status.CANCELLED) {
-                        pendingStore.remove(sessionId, messageId);
-                        turnFinisher.finishCancelled(emitter, sessionId, state, durationMs, messageId, null);
-                        // 恢复段没有新的编排上下文:按暂停时回填的 message_id 收尾同一条编排
-                        turnFinisher.finishRouteByMessage(messageId, AiRouteRun.STATUS_ABORTED,
-                            CANCELLED_TEXT, durationMs);
+                        if (state.pendingConfirm) {
+                            turnFinisher.finishPendingResume(emitter, sessionId, state, durationMs, messageId, null);
+                            turnFinisher.finishRouteByMessage(messageId, AiRouteRun.STATUS_PENDING,
+                                "等待人工确认", durationMs);
+                        } else {
+                            pendingStore.remove(sessionId, messageId);
+                            turnFinisher.finishCancelled(emitter, sessionId, state, durationMs, messageId, null);
+                            // 恢复段没有新的编排上下文:按暂停时回填的 message_id 收尾同一条编排
+                            turnFinisher.finishRouteByMessage(messageId, AiRouteRun.STATUS_ABORTED,
+                                CANCELLED_TEXT, durationMs);
+                        }
                         return;
                     }
                     log.error("HITL 恢复执行失败,sessionId={}, messageId={}", sessionId, messageId, error);
                     String message = AiSseSupport.rootCauseMessage(error);
+                    if (state.process != null) {
+                        state.process.abortRunning(message);
+                    }
                     traceService.appendTransition(state.traceId, "error", "恢复失败:" + message);
                     traceService.accumulate(state.traceId, AiTrace.STATUS_ABORTED, durationMs, null,
                         null, null, null, message);
@@ -745,6 +819,7 @@ public class AiChatFacade {
                             AiMessage.STATUS_ABORTED, durationMs, null, state.toTokenUsage(), state.sources);
                         usageStatService.accumulate(state.userId, state.agentId, state.modelId,
                             state.toTokenUsage(), 0, 0);
+                        turnFinisher.persistProcessSteps(state, sessionId, messageId);
                     } catch (Exception e) {
                         log.error("落库恢复失败消息异常,messageId={}", messageId, e);
                     }

+ 36 - 2
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiExpertResumeDriver.java

@@ -11,7 +11,9 @@ import com.zsjz.ai.module.ai.domain.AiRouteRun;
 import com.zsjz.ai.module.ai.domain.AiSession;
 import com.zsjz.ai.module.ai.domain.AiTrace;
 import com.zsjz.ai.module.ai.domain.dto.AiSessionResourceSet;
+import com.zsjz.ai.module.ai.config.AiProperties;
 import com.zsjz.ai.module.ai.service.IAiAgentService;
+import com.zsjz.ai.module.ai.service.IAiMessageStepService;
 import com.zsjz.ai.module.ai.service.IAiSessionResourceService;
 import com.zsjz.ai.module.ai.service.IAiSessionService;
 import com.zsjz.ai.module.ai.service.IAiTraceService;
@@ -118,6 +120,16 @@ public class AiExpertResumeDriver {
      */
     private final AiRouteSupport routeSupport;
 
+    /**
+     * 配置(执行过程开关与步骤上限)
+     */
+    private final AiProperties aiProperties;
+
+    /**
+     * 执行步骤持久化(恢复段取 maxSeq 续接序号)
+     */
+    private final IAiMessageStepService stepService;
+
     /**
      * 「记住该工具」用户级信任的落位(入口链路与专家链路)
      */
@@ -180,6 +192,14 @@ public class AiExpertResumeDriver {
         state.modelId = definition.getModelId();
         state.traceId = traceId;
         route.entryState = state;
+        // 执行过程:恢复段新建时间线续接(专家步同键 upsert);先回填确认步终态
+        if (aiProperties.getChat().isProcessStepsEnabled()) {
+            AiProcessTimeline timeline = new AiProcessTimeline(emitter, sessionId, stepService.maxSeq(messageId),
+                aiProperties.getChat().getMaxStepsPerMessage());
+            state.process = timeline;
+            route.timeline = timeline;
+            AiProcessTimeline.resolveConfirmStep(timeline, pending.replyId(), pending.decisions());
+        }
         RuntimeContext.Builder resumeContext = RuntimeContext.builder()
             .userId(String.valueOf(userId))
             .sessionId(String.valueOf(sessionId))
@@ -209,6 +229,10 @@ public class AiExpertResumeDriver {
         // 专家续跑是阻塞式编排调用:登记「dispose 该 Mono」为取消句柄(中断 boundedElastic 线程)
         AtomicReference<Disposable> holder = new AtomicReference<>();
         AiRunRegistry.Cancelable cancelable = () -> {
+            // 已暂停等待人工确认时不取消,保留暂停态供用户回来继续确认
+            if (state.pendingConfirm || route.pendingResume != null) {
+                return false;
+            }
             Disposable current = holder.get();
             if (current == null || current.isDisposed()) {
                 return false;
@@ -233,8 +257,14 @@ public class AiExpertResumeDriver {
                     runRegistry.unregister(sessionId, cancelable);
                     long durationMs = (System.nanoTime() - startNanos) / 1_000_000;
                     traceService.appendTransition(traceId, "cancelled", "用户停止专家续跑");
-                    turnFinisher.finishRoute(route, null, AiRouteRun.STATUS_ABORTED, CANCELLED_TEXT, durationMs);
-                    pendingStore.release(sessionId, messageId);
+                    if (state.pendingConfirm) {
+                        // 续跑段内又暂停等待确认:保留暂停态与暂存,供用户继续确认
+                        turnFinisher.finishPendingResume(emitter, sessionId, state, durationMs, messageId, route);
+                        turnFinisher.finishRoute(route, messageId, AiRouteRun.STATUS_PENDING, "等待人工确认", durationMs);
+                    } else {
+                        turnFinisher.finishRoute(route, null, AiRouteRun.STATUS_ABORTED, CANCELLED_TEXT, durationMs);
+                        pendingStore.release(sessionId, messageId);
+                    }
                 })
                 .doFinally(signal -> runRegistry.unregister(sessionId, cancelable))
                 .subscribe(outcome -> {
@@ -284,6 +314,10 @@ public class AiExpertResumeDriver {
                     long durationMs = (System.nanoTime() - startNanos) / 1_000_000;
                     String message = AiSseSupport.rootCauseMessage(error);
                     log.error("编排恢复失败,sessionId={}, messageId={}", sessionId, messageId, error);
+                    if (state.process != null) {
+                        state.process.abortRunning(message);
+                    }
+                    turnFinisher.persistProcessSteps(state, sessionId, messageId);
                     traceService.appendTransition(traceId, "error", "恢复失败:" + message);
                     pendingStore.release(sessionId, messageId);
                     turnFinisher.failStream(emitter, message, error);

+ 55 - 5
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiIntegrationDriver.java

@@ -117,6 +117,12 @@ public class AiIntegrationDriver {
         state.answer.setLength(0);
         // 对话期进度:整合轮是一次完整的模型调用(可能数秒),播报「在汇总」避免正文重开前的静默
         AiPhaseSupport.emit(emitter, state, AiPhaseSupport.PHASE_INTEGRATING, "数剑正在汇总专家结论…", null);
+        // 执行过程:整合步(收尾时终态;失败/中止由 abortRunning 统一处置)
+        String integrationStepKey = "integ:" + route.routeRunId;
+        if (state.process != null) {
+            state.process.startStep(AiProcessTimeline.KIND_INTEGRATION, integrationStepKey, "汇总整合",
+                "entry", null, state.agentId, null);
+        }
         String userMessage = intro + report;
         AtomicBoolean finished = new AtomicBoolean(false);
         AgentRun<AgentEvent> run = agent.prepareRun(List.of(new UserMessage(userMessage)), ctx);
@@ -133,8 +139,17 @@ public class AiIntegrationDriver {
                 // 执行已结束:先释放互斥再下发收尾事件,避免紧随其后的「重新生成」被判忙
                 runRegistry.unregister(sessionId, cancelable);
                 long durationMs = (System.nanoTime() - startNanos) / 1_000_000;
-                // 用户停止 / SSE 断连触发的取消:按「已中止」收尾,不当作失败
+                // 用户停止 / SSE 断连触发的取消:按「已中止」收尾,不当作失败。
+                // 若整合轮内暂停等待确认(pendingConfirm),保留暂停态供用户回来继续确认。
                 if (run.status() == AgentRun.Status.CANCELLED) {
+                    if (state.pendingConfirm) {
+                        if (messageId != null) {
+                            turnFinisher.finishPendingResume(emitter, sessionId, state, durationMs, messageId, route);
+                        } else {
+                            turnFinisher.finishPending(emitter, sessionId, state, durationMs, route);
+                        }
+                        return;
+                    }
                     if (messageId != null) {
                         pendingStore.release(sessionId, messageId);
                     }
@@ -143,6 +158,12 @@ public class AiIntegrationDriver {
                 }
                 String message = AiSseSupport.rootCauseMessage(error);
                 log.error("编排整合轮失败,sessionId={}, messageId={}", sessionId, messageId, error);
+                if (state.process != null) {
+                    state.process.abortRunning(message);
+                }
+                if (messageId != null) {
+                    turnFinisher.persistProcessSteps(state, sessionId, messageId);
+                }
                 traceService.appendTransition(state.traceId, "error", "整合失败:" + message);
                 if (messageId != null) {
                     pendingStore.release(sessionId, messageId);
@@ -157,6 +178,14 @@ public class AiIntegrationDriver {
                 // 执行已结束:先释放互斥再下发 done
                 runRegistry.unregister(sessionId, cancelable);
                 long durationMs = (System.nanoTime() - startNanos) / 1_000_000;
+                // 执行过程:整合步终态(结论+整合正文摘要)
+                if (state.process != null) {
+                    int expertCalls = route.expertCallCount.get();
+                    String conclusion = expertCalls > 0 ? "已汇总 " + expertCalls + " 次专家调用结论" : "已整理最终回答";
+                    java.util.Map<String, Object> detail = new java.util.LinkedHashMap<>();
+                    detail.put("text", AiSseSupport.abbreviate(state.answer.toString(), 2000));
+                    state.process.endStep(integrationStepKey, AiProcessTimeline.STATUS_SUCCESS, conclusion, null, detail);
+                }
                 AiMessage assistant = turnFinisher.finish(emitter, sessionId, state, durationMs, messageId, route);
                 turnFinisher.finishRoute(route, assistant == null ? null : assistant.getId(),
                     route.degraded ? AiRouteRun.STATUS_DEGRADED : AiRouteRun.STATUS_SUCCESS, null, durationMs);
@@ -167,9 +196,22 @@ public class AiIntegrationDriver {
                 }
             });
         // SSE 断连 / 超时:取消后端执行(与对话页「停止」同一路径)
-        emitter.onCompletion(run::cancel);
-        emitter.onTimeout(run::cancel);
-        emitter.onError(ignored -> run.cancel());
+        // SSE 断连 / 超时:取消后端执行;已暂停等待确认时不取消,保留暂停态
+        emitter.onCompletion(() -> {
+            if (!state.pendingConfirm) {
+                run.cancel();
+            }
+        });
+        emitter.onTimeout(() -> {
+            if (!state.pendingConfirm) {
+                run.cancel();
+            }
+        });
+        emitter.onError(ignored -> {
+            if (!state.pendingConfirm) {
+                run.cancel();
+            }
+        });
     }
 
     /**
@@ -204,6 +246,10 @@ public class AiIntegrationDriver {
         // 兜底编排同为阻塞式调用:登记「dispose 该 Mono」为取消句柄
         AtomicReference<Disposable> holder = new AtomicReference<>();
         AiRunRegistry.Cancelable cancelable = () -> {
+            // 已暂停等待人工确认时不取消,保留暂停态供用户回来继续确认
+            if (state.pendingConfirm || route.pendingResume != null) {
+                return false;
+            }
             Disposable current = holder.get();
             if (current == null || current.isDisposed()) {
                 return false;
@@ -225,7 +271,11 @@ public class AiIntegrationDriver {
                 // 执行已结束:先释放互斥再下发 aborted
                 runRegistry.unregister(sessionId, cancelable);
                 long durationMs = (System.nanoTime() - startNanos) / 1_000_000;
-                turnFinisher.finishCancelled(emitter, sessionId, state, durationMs, null, route);
+                if (state.pendingConfirm) {
+                    turnFinisher.finishPending(emitter, sessionId, state, durationMs, route);
+                } else {
+                    turnFinisher.finishCancelled(emitter, sessionId, state, durationMs, null, route);
+                }
             })
             .doFinally(signal -> runRegistry.unregister(sessionId, cancelable))
             .subscribe(report -> {

+ 582 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiProcessTimeline.java

@@ -0,0 +1,582 @@
+package com.zsjz.ai.module.ai.core.agent;
+
+import lombok.extern.slf4j.Slf4j;
+import com.zsjz.ai.common.compat.JsonUtils;
+import com.zsjz.ai.common.compat.StringUtils;
+import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * 一轮对话的「执行过程」权威时间线(思考过程 + 分步结论,docs/design/chat-process-timeline-plan.md)。
+ *
+ * <p>按事件到达顺序把本轮经历归一为步骤(thinking / route / tool / expert / confirm / integration),
+ * 实时下发 {@code step_start / step_delta / step_end} 三种 SSE 事件,收尾时由 {@link AiTurnFinisher}
+ * 批量落库 {@code ai_message_step} 供历史精确回放。每步带一行**确定性结论**(零 LLM 成本)。</p>
+ *
+ * <p><b>跨段共享</b>:入口轮 / 专家轮 / 整合轮共用同一实例(经 {@link AiStreamState#process} 与
+ * {@link AiRouteContext#timeline} 传递);HITL 恢复段新建实例并以 {@code seqStart = maxSeq(messageId)}
+ * 续接,落库按 {@code (message_id, step_key)} upsert(confirm 步 waiting→终态、expert 步同键续跑)。</p>
+ *
+ * <p><b>线程约束</b>:入口订阅线程与专家 boundedElastic 线程先后访问本对象(事实串行但无
+ * happens-before 保证),故全部公开方法 {@code synchronized};不引入 subscribeOn/publishOn,
+ * 钩子全部在既有回调线程内同步调用。{@code emitter} 为 null(无人值守链路)时只累积不下发。</p>
+ *
+ * @author BizBuddy
+ */
+@Slf4j
+final class AiProcessTimeline {
+
+    /** 事件类型:步骤开始 */
+    static final String EVENT_STEP_START = "step_start";
+
+    /** 事件类型:步骤增量(仅 thinking 步) */
+    static final String EVENT_STEP_DELTA = "step_delta";
+
+    /** 事件类型:步骤终态(可对同一 stepKey 重发以更新结论) */
+    static final String EVENT_STEP_END = "step_end";
+
+    /** 步骤类型:模型思考 */
+    static final String KIND_THINKING = "thinking";
+
+    /** 步骤类型:路由决策 */
+    static final String KIND_ROUTE = "route";
+
+    /** 步骤类型:工具调用 */
+    static final String KIND_TOOL = "tool";
+
+    /** 步骤类型:专家咨询 */
+    static final String KIND_EXPERT = "expert";
+
+    /** 步骤类型:人工确认 */
+    static final String KIND_CONFIRM = "confirm";
+
+    /** 步骤类型:汇总整合 */
+    static final String KIND_INTEGRATION = "integration";
+
+    /** 状态:进行中 */
+    static final String STATUS_RUNNING = "running";
+
+    /** 状态:成功 */
+    static final String STATUS_SUCCESS = "success";
+
+    /** 状态:失败 */
+    static final String STATUS_ERROR = "error";
+
+    /** 状态:跳过(思考内容未过安全审核) */
+    static final String STATUS_SKIPPED = "skipped";
+
+    /** 状态:等待人工确认 */
+    static final String STATUS_WAITING = "waiting";
+
+    /** 状态:已允许执行 */
+    static final String STATUS_APPROVED = "approved";
+
+    /** 状态:已拒绝 */
+    static final String STATUS_REJECTED = "rejected";
+
+    /** 状态:确认已失效 */
+    static final String STATUS_EXPIRED = "expired";
+
+    /** 状态:已中止 */
+    static final String STATUS_ABORTED = "aborted";
+
+    /** 思考全文内存上限(超出停止追加但继续计时) */
+    private static final int THINKING_MEMORY_CAP = 16000;
+
+    /** 思考全文落库上限 */
+    private static final int THINKING_PERSIST_CAP = 8000;
+
+    /** 一行结论截断长度 */
+    private static final int CONCLUSION_CHARS = 80;
+
+    /** SSE 发射器(可空:无人值守链路只累积不下发) */
+    private final SseEmitter emitter;
+
+    /** 会话主键 */
+    private final Long sessionId;
+
+    /** 轮内步骤序号(恢复段从 maxSeq 续接) */
+    private final AtomicInteger seq;
+
+    /** 步骤累积(stepKey → 累积项,插入序即时间线顺序) */
+    private final Map<String, AiStepAcc> steps = new LinkedHashMap<>();
+
+    /** 单消息步骤上限(超出只计数不落详情) */
+    private final int maxSteps;
+
+    /** 是否已超出步骤上限(摘要显示「200+ 个步骤」) */
+    private boolean overflow;
+
+    AiProcessTimeline(SseEmitter emitter, Long sessionId, int seqStart, int maxSteps) {
+        this.emitter = emitter;
+        this.sessionId = sessionId;
+        this.seq = new AtomicInteger(seqStart);
+        this.maxSteps = maxSteps > 0 ? maxSteps : 200;
+    }
+
+    /**
+     * 开始一个步骤(同键已存在时不重复开步,与 expert_start 恢复段抑制口径一致)。
+     *
+     * @param kind       步骤类型
+     * @param stepKey    步骤键(轮内唯一)
+     * @param title      标题(后端拼好,前端只渲染)
+     * @param speaker    说话人 entry / expert
+     * @param expertName 专家名(speaker=expert 时非空)
+     * @param agentId    关联智能体主键(可空)
+     * @param refKey     关联键(tool→toolCallId;expert→agentId#attempt;可空)
+     */
+    synchronized void startStep(String kind, String stepKey, String title, String speaker,
+                                String expertName, Long agentId, String refKey) {
+        if (StringUtils.isBlank(stepKey) || steps.containsKey(stepKey)) {
+            return;
+        }
+        if (steps.size() >= maxSteps) {
+            overflow = true;
+        }
+        AiStepAcc acc = new AiStepAcc();
+        acc.stepKey = stepKey;
+        acc.seq = seq.incrementAndGet();
+        acc.kind = kind;
+        acc.title = title;
+        acc.speaker = StringUtils.isBlank(speaker) ? "entry" : speaker;
+        acc.expertName = expertName;
+        acc.agentId = agentId;
+        acc.refKey = refKey;
+        acc.status = STATUS_RUNNING;
+        acc.startNanos = System.nanoTime();
+        steps.put(stepKey, acc);
+        Map<String, Object> payload = AiSseSupport.envelope(EVENT_STEP_START);
+        payload.put("stepKey", stepKey);
+        payload.put("seq", acc.seq);
+        payload.put("kind", kind);
+        payload.put("title", title);
+        payload.put("status", STATUS_RUNNING);
+        payload.put("speaker", acc.speaker);
+        if (StringUtils.isNotBlank(expertName)) {
+            payload.put("expertName", expertName);
+        }
+        if (StringUtils.isNotBlank(refKey)) {
+            payload.put("refKey", refKey);
+        }
+        AiSseSupport.send(emitter, payload);
+    }
+
+    /**
+     * 思考增量:累积已过安全守卫的文本并下发(内存上限截断,超出停止追加但继续计时)。
+     *
+     * @param stepKey  思考步键
+     * @param safeText 已过安全守卫的增量文本
+     */
+    synchronized void appendThinking(String stepKey, String safeText) {
+        AiStepAcc acc = steps.get(stepKey);
+        if (acc == null || STATUS_SKIPPED.equals(acc.status) || StringUtils.isBlank(safeText)) {
+            return;
+        }
+        if (acc.thinking.length() < THINKING_MEMORY_CAP) {
+            int room = THINKING_MEMORY_CAP - acc.thinking.length();
+            acc.thinking.append(safeText.length() <= room ? safeText : safeText.substring(0, room));
+            if (safeText.length() > room) {
+                acc.thinkingTruncated = true;
+            }
+        } else {
+            acc.thinkingTruncated = true;
+        }
+        Map<String, Object> payload = AiSseSupport.envelope(EVENT_STEP_DELTA);
+        payload.put("stepKey", stepKey);
+        payload.put("delta", safeText);
+        AiSseSupport.send(emitter, payload);
+    }
+
+    /**
+     * 取思考步的安全尾部缓冲(供事件桥做跨片防切断,复用 text_delta 同款机制)。
+     *
+     * @param stepKey 思考步键
+     * @return 缓冲;步不存在时返回 null
+     */
+    synchronized StringBuilder thinkingPendingOf(String stepKey) {
+        AiStepAcc acc = steps.get(stepKey);
+        return acc == null ? null : acc.safetyPending;
+    }
+
+    /**
+     * 思考步是否已被安全跳过(BLOCK 后后续增量一律丢弃)。
+     *
+     * @param stepKey 思考步键
+     * @return 是否已跳过
+     */
+    synchronized boolean isThinkingSkipped(String stepKey) {
+        AiStepAcc acc = steps.get(stepKey);
+        return acc != null && STATUS_SKIPPED.equals(acc.status);
+    }
+
+    /**
+     * 思考内容命中安全阻断:整步跳过(不影响正文)。
+     *
+     * @param stepKey 思考步键
+     */
+    synchronized void skipThinking(String stepKey) {
+        AiStepAcc acc = steps.get(stepKey);
+        if (acc == null || !STATUS_RUNNING.equals(acc.status)) {
+            return;
+        }
+        acc.safetyPending.setLength(0);
+        acc.thinking.setLength(0);
+        endStepInternal(acc, STATUS_SKIPPED, "思考内容未通过安全审核", null, null);
+    }
+
+    /**
+     * 结束思考步:冲刷尾部后由事件桥调用,生成结论与详情。
+     *
+     * @param stepKey 思考步键
+     */
+    synchronized void endThinking(String stepKey) {
+        AiStepAcc acc = steps.get(stepKey);
+        if (acc == null || !STATUS_RUNNING.equals(acc.status)) {
+            return;
+        }
+        String text = acc.thinking.toString();
+        long durationMs = elapsedMs(acc);
+        String conclusion = thinkingConclusion(text, durationMs);
+        Map<String, Object> detail = new LinkedHashMap<>();
+        detail.put("text", AiSseSupport.abbreviate(text, THINKING_PERSIST_CAP));
+        detail.put("truncated", acc.thinkingTruncated || text.length() > THINKING_PERSIST_CAP);
+        endStepInternal(acc, STATUS_SUCCESS, conclusion, durationMs, detail);
+    }
+
+    /**
+     * 结束一个步骤(终态)。同键不存在时按「恢复段续接」处理:仅下发 step_end,
+     * 前端按 stepKey upsert 既有步骤;落库走 update 路径(seq 保留原值)。
+     *
+     * @param stepKey    步骤键
+     * @param status     终态
+     * @param conclusion 一行结论(后端拼好)
+     * @param durationMs 耗时(可空:有累积项时按起点计算)
+     * @param detail     详情(可空;仅 route 步随 SSE 下发,其余走既有事件/REST/落库)
+     */
+    synchronized void endStep(String stepKey, String status, String conclusion, Long durationMs,
+                              Map<String, Object> detail) {
+        if (StringUtils.isBlank(stepKey)) {
+            return;
+        }
+        AiStepAcc acc = steps.get(stepKey);
+        if (acc == null) {
+            // 恢复段续接:本实例没有该步(暂停段已落库),构造续接项只发 step_end
+            acc = new AiStepAcc();
+            acc.stepKey = stepKey;
+            acc.seq = seq.incrementAndGet();
+            acc.kind = kindOfKey(stepKey);
+            acc.title = null;
+            acc.speaker = "entry";
+            acc.status = STATUS_RUNNING;
+            acc.startNanos = System.nanoTime();
+            steps.put(stepKey, acc);
+        }
+        endStepInternal(acc, status, conclusion, durationMs, detail);
+    }
+
+    /**
+     * 更新已结束步骤的结论(如 route_fallback 降级说明),重发 step_end(前端按键覆盖结论)。
+     *
+     * @param stepKey    步骤键
+     * @param conclusion 新结论
+     * @param detail     新详情(可空,保留原详情)
+     */
+    synchronized void updateConclusion(String stepKey, String conclusion, Map<String, Object> detail) {
+        AiStepAcc acc = steps.get(stepKey);
+        if (acc == null) {
+            return;
+        }
+        acc.conclusion = conclusion;
+        if (detail != null) {
+            acc.detail = detail;
+        }
+        Map<String, Object> payload = AiSseSupport.envelope(EVENT_STEP_END);
+        payload.put("stepKey", stepKey);
+        payload.put("status", acc.status);
+        payload.put("conclusion", conclusion);
+        if (acc.durationMs != null) {
+            payload.put("durationMs", acc.durationMs);
+        }
+        if (KIND_ROUTE.equals(acc.kind) && acc.detail != null) {
+            payload.put("detail", acc.detail);
+        }
+        AiSseSupport.send(emitter, payload);
+    }
+
+    /**
+     * 把 running 步全部标为已中止(用户停止 / SSE 断连 / 流中错误)。waiting 步不动。
+     *
+     * @param reason 中止原因
+     */
+    synchronized void abortRunning(String reason) {
+        for (AiStepAcc acc : steps.values()) {
+            if (STATUS_RUNNING.equals(acc.status)) {
+                endStepInternal(acc, STATUS_ABORTED, reason, null, null);
+            }
+        }
+    }
+
+    /**
+     * 恢复段开始时回填确认步终态(同键 upsert:暂停段 waiting → approved/rejected)。
+     *
+     * @param process        时间线(可空)
+     * @param pendingReplyId 暂停时的 replyId(确认步键后缀)
+     * @param decisions      用户处置结果
+     */
+    static void resolveConfirmStep(AiProcessTimeline process, String pendingReplyId,
+                                   List<AiConfirmPendingStore.PendingDecision> decisions) {
+        if (process == null || StringUtils.isBlank(pendingReplyId)) {
+            return;
+        }
+        boolean allApproved = decisions != null && !decisions.isEmpty()
+            && decisions.stream().allMatch(AiConfirmPendingStore.PendingDecision::confirmed);
+        String rejectReason = null;
+        if (decisions != null) {
+            for (AiConfirmPendingStore.PendingDecision decision : decisions) {
+                if (!decision.confirmed() && StringUtils.isNotBlank(decision.reason())) {
+                    rejectReason = decision.reason();
+                    break;
+                }
+            }
+        }
+        String status = allApproved ? STATUS_APPROVED : STATUS_REJECTED;
+        String conclusion = allApproved ? "已允许执行"
+            : "已拒绝" + (StringUtils.isNotBlank(rejectReason) ? ":" + rejectReason : "");
+        Map<String, Object> detail = new LinkedHashMap<>();
+        List<Map<String, Object>> items = new ArrayList<>();
+        if (decisions != null) {
+            for (AiConfirmPendingStore.PendingDecision decision : decisions) {
+                Map<String, Object> item = new LinkedHashMap<>();
+                item.put("toolCallId", decision.toolCallId());
+                item.put("confirmed", decision.confirmed());
+                item.put("remember", decision.remember());
+                item.put("reason", decision.reason());
+                items.add(item);
+            }
+        }
+        detail.put("decisions", items);
+        process.endStep("confirm:" + pendingReplyId, status, conclusion, null, detail);
+    }
+
+    /**
+     * 本轮是否有步骤(无步骤时前端不渲染过程面板,与现状一致)。
+     *
+     * @return 是否有步骤
+     */
+    synchronized boolean hasSteps() {
+        return !steps.isEmpty();
+    }
+
+    /**
+     * 步骤总数(含超出上限只计数的部分)。
+     *
+     * @return 步骤数
+     */
+    synchronized int stepCount() {
+        return steps.size();
+    }
+
+    /**
+     * 各 thinking 步耗时之和(毫秒),供 done/aborted 载荷与摘要行。
+     *
+     * @return 思考总耗时
+     */
+    synchronized long thinkingDurationMs() {
+        long total = 0;
+        for (AiStepAcc acc : steps.values()) {
+            if (KIND_THINKING.equals(acc.kind) && acc.durationMs != null) {
+                total += acc.durationMs;
+            }
+        }
+        return total;
+    }
+
+    /**
+     * 导出步骤快照供收尾落库(超出上限只落前 maxSteps 步;thinking 文本字段由落库方再脱敏)。
+     *
+     * @return 按 seq 排序的步骤快照
+     */
+    synchronized List<StepView> toStepViews() {
+        List<StepView> views = new ArrayList<>();
+        int count = 0;
+        for (AiStepAcc acc : steps.values()) {
+            if (count++ >= maxSteps) {
+                break;
+            }
+            Map<String, Object> detail = acc.detail;
+            if (KIND_THINKING.equals(acc.kind)) {
+                detail = new LinkedHashMap<>();
+                String text = acc.thinking.toString();
+                detail.put("text", AiSseSupport.abbreviate(text, THINKING_PERSIST_CAP));
+                detail.put("truncated", acc.thinkingTruncated || text.length() > THINKING_PERSIST_CAP);
+            }
+            views.add(new StepView(acc.stepKey, acc.seq, acc.kind, acc.title, acc.speaker, acc.expertName,
+                acc.agentId, acc.status, acc.conclusion, detail, acc.durationMs));
+        }
+        return views;
+    }
+
+    /**
+     * 步骤快照(落库映射用,不依赖实体类)。
+     */
+    record StepView(String stepKey, int seq, String kind, String title, String speaker, String expertName,
+                    Long agentId, String status, String conclusion, Map<String, Object> detail, Long durationMs) {
+    }
+
+    // ------------------------------------------------------------------
+    // 确定性结论生成(零 LLM 成本,静态方法便于单测)
+    // ------------------------------------------------------------------
+
+    /**
+     * 思考步结论:首个非空行截 80 字;无文本→「思考了 X 秒」。
+     */
+    static String thinkingConclusion(String text, long durationMs) {
+        String line = firstMeaningfulLine(text);
+        if (StringUtils.isNotBlank(line)) {
+            return AiSseSupport.abbreviate(line, CONCLUSION_CHARS);
+        }
+        return "思考了 " + Math.max(1, Math.round(durationMs / 1000.0)) + " 秒";
+    }
+
+    /**
+     * 工具步结论:成功取输出首个有意义行(跳过空行 / Exit code: 0),空→「执行完成」;
+     * 失败→「执行失败:{state}」;拒绝→「已拒绝执行」。
+     */
+    static String toolConclusion(String output, String state) {
+        if ("DENIED".equals(state)) {
+            return "已拒绝执行";
+        }
+        if (state != null && !"SUCCESS".equals(state)) {
+            return "执行失败:" + state;
+        }
+        String line = firstMeaningfulLine(output);
+        if (StringUtils.isBlank(line)) {
+            return "执行完成";
+        }
+        return AiSseSupport.abbreviate(line, CONCLUSION_CHARS);
+    }
+
+    /**
+     * 专家步结论:成功取原文首行截 80 字,空→「专家「X」已回答」;失败→原因;暂停→等待确认。
+     */
+    static String expertConclusion(String rawOutput, String expertName, String error) {
+        if (StringUtils.isNotBlank(error)) {
+            return AiSseSupport.abbreviate(error, CONCLUSION_CHARS);
+        }
+        String line = firstMeaningfulLine(rawOutput);
+        if (StringUtils.isNotBlank(line)) {
+            return AiSseSupport.abbreviate(line, CONCLUSION_CHARS);
+        }
+        return "专家「" + (StringUtils.isBlank(expertName) ? "领域专家" : expertName) + "」已回答";
+    }
+
+    /**
+     * 路由步结论:route→「数剑判定:需咨询专家「X」」+理由;self→自答;pinned→已指定。
+     */
+    static String routeConclusion(String action, String expertName, String reason) {
+        String base;
+        if ("self".equals(action)) {
+            base = "数剑判定:本轮由自己回答";
+        } else if ("pinned".equals(action)) {
+            base = "已指定专家:" + (StringUtils.isBlank(expertName) ? "领域专家" : expertName);
+        } else {
+            base = "数剑判定:需咨询专家「" + (StringUtils.isBlank(expertName) ? "领域专家" : expertName) + "」";
+        }
+        if (StringUtils.isNotBlank(reason)) {
+            base = base + ":" + AiSseSupport.abbreviate(reason, 60);
+        }
+        return AiSseSupport.abbreviate(base, CONCLUSION_CHARS + 40);
+    }
+
+    /**
+     * 取首个有意义行(跳过空行与命令退出码行),用于结论摘要。
+     */
+    static String firstMeaningfulLine(String text) {
+        if (StringUtils.isBlank(text)) {
+            return null;
+        }
+        for (String line : text.split("\\r?\\n")) {
+            String trimmed = line.trim();
+            if (trimmed.isEmpty()) {
+                continue;
+            }
+            if (trimmed.startsWith("Exit code:")) {
+                continue;
+            }
+            // 去掉行首 markdown 标记,结论更干净
+            return trimmed.replaceAll("^[#*>\\-\\s]+", "");
+        }
+        return null;
+    }
+
+    // ------------------------------------------------------------------
+    // 内部
+    // ------------------------------------------------------------------
+
+    private void endStepInternal(AiStepAcc acc, String status, String conclusion, Long durationMs,
+                                 Map<String, Object> detail) {
+        acc.status = status;
+        acc.conclusion = conclusion;
+        acc.durationMs = durationMs != null ? durationMs : elapsedMs(acc);
+        if (detail != null) {
+            acc.detail = detail;
+        }
+        Map<String, Object> payload = AiSseSupport.envelope(EVENT_STEP_END);
+        payload.put("stepKey", acc.stepKey);
+        payload.put("status", status);
+        if (StringUtils.isNotBlank(conclusion)) {
+            payload.put("conclusion", conclusion);
+        }
+        payload.put("durationMs", acc.durationMs);
+        // 仅 route 步随事件下发详情(action/reason/confidence);tool 走既有事件、expert 走 REST/落库
+        if (KIND_ROUTE.equals(acc.kind) && acc.detail != null) {
+            payload.put("detail", acc.detail);
+        }
+        AiSseSupport.send(emitter, payload);
+    }
+
+    private static long elapsedMs(AiStepAcc acc) {
+        return acc.startNanos == 0L ? 0L : (System.nanoTime() - acc.startNanos) / 1_000_000;
+    }
+
+    private static String kindOfKey(String stepKey) {
+        int colon = stepKey.indexOf(':');
+        String prefix = colon > 0 ? stepKey.substring(0, colon) : stepKey;
+        return switch (prefix) {
+            case "think" -> KIND_THINKING;
+            case "route" -> KIND_ROUTE;
+            case "tool" -> KIND_TOOL;
+            case "expert" -> KIND_EXPERT;
+            case "confirm" -> KIND_CONFIRM;
+            case "integ" -> KIND_INTEGRATION;
+            default -> KIND_TOOL;
+        };
+    }
+
+    /**
+     * 单步累积项(字段包级可见,理由同 {@link AiToolCallAcc})。
+     */
+    private static final class AiStepAcc {
+        String stepKey;
+        int seq;
+        String kind;
+        String title;
+        String speaker;
+        String expertName;
+        Long agentId;
+        String refKey;
+        String status;
+        final StringBuilder thinking = new StringBuilder();
+        final StringBuilder safetyPending = new StringBuilder();
+        boolean thinkingTruncated;
+        String conclusion;
+        Map<String, Object> detail;
+        long startNanos;
+        Long durationMs;
+    }
+}

+ 6 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiRouteContext.java

@@ -210,6 +210,12 @@ import java.util.concurrent.atomic.AtomicLong;
      */
     volatile AiConfirmPendingStore.ExpertResume pendingResume;
 
+    /**
+     * 本轮「执行过程」时间线(可空):入口轮装配后回挂,专家轮 / 整合轮 / 恢复段共享同一实例,
+     * 使路由 / 专家 / 工具 / 思考步骤归一到同一条时间线(docs/design/chat-process-timeline-plan.md)。
+     */
+    volatile AiProcessTimeline timeline;
+
     /**
      * HITL 恢复段的待确认工具调用(仅专家续跑使用)。
      *

+ 139 - 2
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiRouteOrchestrator.java

@@ -12,6 +12,8 @@ import io.agentscope.core.skill.SkillFilter;
 import io.agentscope.harness.agent.HarnessAgent;
 import lombok.extern.slf4j.Slf4j;
 import com.zsjz.ai.module.ai.config.AiProperties;
+import com.zsjz.ai.module.ai.core.safety.AiSafetyGuard;
+import com.zsjz.ai.module.ai.core.safety.SafetyScene;
 import com.zsjz.ai.module.ai.domain.AiExpertAgent;
 import com.zsjz.ai.module.ai.domain.AiRouteExpertCall;
 import com.zsjz.ai.module.ai.domain.AiRouteRun;
@@ -22,10 +24,13 @@ import com.zsjz.ai.module.ai.service.IAiAgentService;
 import com.zsjz.ai.module.ai.service.IAiSkillService;
 import com.zsjz.ai.module.ai.service.IAiTraceService;
 import com.zsjz.ai.common.compat.StringUtils;
+import com.zsjz.ai.common.compat.JsonUtils;
+import com.fasterxml.jackson.databind.JsonNode;
 import org.springframework.context.annotation.Lazy;
 import org.springframework.stereotype.Component;
 
 import java.util.ArrayList;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -132,6 +137,11 @@ public class AiRouteOrchestrator {
      */
     private final AiRunRegistry runRegistry;
 
+    /**
+     * 安全合规守卫:专家步详情里的原文落库前整段脱敏(与工具明细同口径)
+     */
+    private final AiSafetyGuard safetyGuard;
+
     /**
      * @param agentRegistry    智能体装配注册表(专家走独立装配)
      * @param expertDirectory  专家名录(取专家定义)
@@ -151,7 +161,8 @@ public class AiRouteOrchestrator {
                                AiProperties aiProperties,
                                IAiSkillService skillService,
                                IAiAgentService agentService,
-                               AiRunRegistry runRegistry) {
+                               AiRunRegistry runRegistry,
+                               AiSafetyGuard safetyGuard) {
         this.agentRegistry = agentRegistry;
         this.expertDirectory = expertDirectory;
         this.recorder = recorder;
@@ -161,6 +172,7 @@ public class AiRouteOrchestrator {
         this.skillService = skillService;
         this.agentService = agentService;
         this.runRegistry = runRegistry;
+        this.safetyGuard = safetyGuard;
     }
 
     /**
@@ -196,6 +208,7 @@ public class AiRouteOrchestrator {
             route.degradeReason = "指定专家不存在或已被删除";
             log.warn("指定专家不可用,直接降级自答:pinnedExpertId={}", route.pinnedExpertId);
             emit(route, EVENT_ROUTE_FALLBACK, Map.of("reason", route.degradeReason));
+            updateRouteFallback(route, route.degradeReason);
             return degradeReport(route, null, null);
         }
         return executeInternal(route, candidate);
@@ -210,17 +223,21 @@ public class AiRouteOrchestrator {
      */
     private String executeInternal(AiRouteContext route, AiExpertCandidate first) {
         AiExpertCandidate chosen = first;
+        String action = StringUtils.isBlank(route.action) ? AiRouteRun.ACTION_ROUTE : route.action;
         emit(route, EVENT_ROUTE_DECISION, Map.of(
-            "action", StringUtils.isBlank(route.action) ? AiRouteRun.ACTION_ROUTE : route.action,
+            "action", action,
             "expertKey", chosen.agentKey(),
             "expertAgentId", chosen.agentId(),
             "expertName", chosen.agentName()));
+        // 执行过程:路由决策步(判定即终态,结论含决策理由;详情随事件下发供面板展示)
+        recordRouteStep(route, action, chosen.agentName());
         // 专家直答修订(2026-10-03):阶梯恒为单一专家、**只调用一次**——不判契约、不重试、不换专家;
         // 调不通或没有产出即降级为数剑兜底自答
         if (route.budgetExceeded) {
             route.degraded = true;
             route.degradeReason = budgetDegradeReason(route);
             emit(route, EVENT_ROUTE_FALLBACK, Map.of("reason", route.degradeReason));
+            updateRouteFallback(route, route.degradeReason);
             return degradeReport(route, chosen, null);
         }
         ExpertAttempt result = runOnce(route, chosen, 1, AiRouteExpertCall.KIND_FIRST);
@@ -239,9 +256,66 @@ public class AiRouteOrchestrator {
         route.degraded = true;
         route.degradeReason = "专家结论不可用:" + result.error();
         emit(route, EVENT_ROUTE_FALLBACK, Map.of("reason", route.degradeReason));
+        updateRouteFallback(route, route.degradeReason);
         return degradeReport(route, chosen, result.error());
     }
 
+    /**
+     * 执行过程:建路由决策步并即终态(结论=判定+理由截断)。
+     *
+     * @param route      编排运行状态
+     * @param action     决策动作 route / pinned
+     * @param expertName 专家名
+     */
+    private void recordRouteStep(AiRouteContext route, String action, String expertName) {
+        AiProcessTimeline timeline = route.timeline;
+        if (timeline == null) {
+            return;
+        }
+        String reason = decisionField(route.decisionJson, "reason");
+        Map<String, Object> detail = new LinkedHashMap<>();
+        detail.put("action", action);
+        detail.put("reason", reason);
+        detail.put("confidence", decisionField(route.decisionJson, "confidence"));
+        detail.put("taskContext", AiSseSupport.abbreviate(route.taskContext, 2000));
+        String key = "route:" + route.routeRunId;
+        timeline.startStep(AiProcessTimeline.KIND_ROUTE, key, "路由决策", "entry", null, route.entryAgentId, null);
+        timeline.endStep(key, AiProcessTimeline.STATUS_SUCCESS,
+            AiProcessTimeline.routeConclusion(action, expertName, reason), null, detail);
+    }
+
+    /**
+     * 执行过程:降级时更新路由步结论(重发 step_end,前端按键覆盖)。
+     *
+     * @param route  编排运行状态
+     * @param reason 降级原因
+     */
+    private void updateRouteFallback(AiRouteContext route, String reason) {
+        AiProcessTimeline timeline = route.timeline;
+        if (timeline != null) {
+            timeline.updateConclusion("route:" + route.routeRunId,
+                AiSseSupport.abbreviate("降级:" + reason, 120), null);
+        }
+    }
+
+    /**
+     * 从决策原文 JSON 取字段(reason / confidence),解析失败返回 null。
+     */
+    private static String decisionField(String decisionJson, String field) {
+        if (StringUtils.isBlank(decisionJson)) {
+            return null;
+        }
+        try {
+            JsonNode node = JsonUtils.readTree(decisionJson);
+            if (node == null || !node.hasNonNull(field)) {
+                return null;
+            }
+            return node.get(field).asText();
+        } catch (Exception e) {
+            return null;
+        }
+    }
+
     /**
      * 人工确认后的专家续跑(REQ-AI-30 Phase 2 HITL 贯通)。
      *
@@ -263,6 +337,7 @@ public class AiRouteOrchestrator {
             route.degraded = true;
             route.degradeReason = "专家不存在或已被删除,无法续跑";
             emit(route, EVENT_ROUTE_FALLBACK, Map.of("reason", route.degradeReason));
+            updateRouteFallback(route, route.degradeReason);
             return new ResumeOutcome(false, degradeReport(route, null, null));
         }
         int attempt = resume.attemptNo() == null ? 1 : resume.attemptNo();
@@ -282,6 +357,7 @@ public class AiRouteOrchestrator {
         route.degraded = true;
         route.degradeReason = "恢复后专家结论不可用:" + resumed.error();
         emit(route, EVENT_ROUTE_FALLBACK, Map.of("reason", route.degradeReason));
+        updateRouteFallback(route, route.degradeReason);
         return new ResumeOutcome(false, degradeReport(route, candidate, resumed.error()));
     }
 
@@ -479,6 +555,9 @@ public class AiRouteOrchestrator {
                 .map(AiConfirmPendingStore.PendingToolCall::toolName).toList());
         // 此处**刻意不下发 expert_result**:下发了会把卡片标成终态,于是恢复段真正的 expert_result
         // 就找不到可回填的卡片了。卡片保持「调用中」,由确认卡片说明当前状态。
+        // 执行过程:专家步标为 waiting(非终态),恢复段续跑后同键 upsert 为终态
+        endExpertStep(route, "expert:" + candidate.agentId() + "#" + attempt, AiProcessTimeline.STATUS_WAITING,
+            "等待你确认后继续", state, raw, PAUSE_VALIDATION_ERROR, durationMs);
     }
 
     /**
@@ -541,6 +620,8 @@ public class AiRouteOrchestrator {
             return ExpertAttempt.unrepairable("专家不存在或已被删除");
         }
         String expertSessionId = route.routeRunId + "#" + candidate.agentId();
+        // 执行过程:专家步键(恢复段续跑同键,前端按 stepKey upsert,不重复开卡)
+        String expertStepKey = "expert:" + candidate.agentId() + "#" + attempt;
         if (!resume) {
             emit(route, EVENT_EXPERT_START, Map.of(
                 "expertKey", candidate.agentKey(),
@@ -551,6 +632,13 @@ public class AiRouteOrchestrator {
             // 对话期进度:专家执行可能长达数十秒,先播报「在咨询谁」,其内部动作由专家状态的 phase 接续
             AiPhaseSupport.emit(route.emitter, route.entryState, AiPhaseSupport.PHASE_EXPERT,
                 "正在咨询领域专家「" + candidate.agentName() + "」…", null);
+            // 执行过程:建专家步(标题含重试次数)
+            AiProcessTimeline timeline = route.timeline;
+            if (timeline != null) {
+                String title = "咨询专家「" + candidate.agentName() + "」" + (attempt > 1 ? "(第 " + attempt + " 次)" : "");
+                timeline.startStep(AiProcessTimeline.KIND_EXPERT, expertStepKey, title, "expert",
+                    candidate.agentName(), candidate.agentId(), candidate.agentId() + "#" + attempt);
+            }
         }
         // 专家直答(REQ-AI-30 直答修订,2026-10-03):先清掉数剑已流出的正文并进入接管态,
         // 随后专家的正文以 text_delta 直传用户(内部工具卡片不下发,只累积留证)
@@ -566,6 +654,9 @@ public class AiRouteOrchestrator {
         state.traceId = childTraceId;
         // 对话期进度:专家的思考 / 工具动作按专家身份播报(「专家「X」正在调用…」)
         state.speakerExpertName = candidate.agentName();
+        // 执行过程:专家轮共享入口轮装配的时间线;正文增量附带专家步键供前端镜像专家输出
+        state.process = route.timeline;
+        state.processExpertStepKey = expertStepKey;
         if (resume) {
             // 恢复段:回填被 HITL 暂停的专家工具入参;结果事件里不会再有 ToolCallDelta
             state.seedPendingToolCalls(route.resumePendingToolCalls);
@@ -672,6 +763,9 @@ public class AiRouteOrchestrator {
             recordCall(route, candidate, expertSessionId, attempt, kind, null, false, CANCELLED_TEXT,
                 false, true, cancelledUsage, durationMs);
             route.cancelled = true;
+            // 执行过程:专家步标为已中止(其余 running 步由收尾 abortRunning 统一处置)
+            endExpertStep(route, expertStepKey, AiProcessTimeline.STATUS_ABORTED, CANCELLED_TEXT,
+                state, null, CANCELLED_TEXT, durationMs);
             try {
                 accumulateTrace(state, childTraceId, false, CANCELLED_TEXT, false, cancelledUsage, durationMs);
             } catch (Exception e) {
@@ -716,9 +810,52 @@ public class AiRouteOrchestrator {
             "expertName", candidate.agentName(),
             "attemptNo", attempt,
             "status", ok ? AiRouteExpertCall.STATUS_SUCCESS : AiRouteExpertCall.STATUS_INVALID));
+        // 执行过程:专家步终态(结论取原文首行;详情含脱敏原文与子工具列表,供面板展开与历史回放)
+        endExpertStep(route, expertStepKey, ok ? AiProcessTimeline.STATUS_SUCCESS : AiProcessTimeline.STATUS_ERROR,
+            AiProcessTimeline.expertConclusion(rawOutput, candidate.agentName(), ok ? null : reason),
+            state, rawOutput, ok ? null : reason, durationMs);
         return new ExpertAttempt(ok, !ok, rawOutput, reason, false);
     }
 
+    /**
+     * 执行过程:结束专家步(含详情:脱敏原文 + 子工具列表,子工具仅 name/state/duration,零入参出参泄漏)。
+     *
+     * @param route        编排运行状态
+     * @param expertStepKey 专家步键
+     * @param status       终态
+     * @param conclusion   一行结论
+     * @param state        专家本轮累积状态(取子工具列表与已流出正文)
+     * @param rawOutput    专家完整原文(可空:取消/暂停时取已流出部分)
+     * @param error        不可用原因(成功时为空)
+     * @param durationMs   耗时
+     */
+    private void endExpertStep(AiRouteContext route, String expertStepKey, String status, String conclusion,
+                               AiStreamState state, String rawOutput, String error, long durationMs) {
+        AiProcessTimeline timeline = route.timeline;
+        if (timeline == null) {
+            return;
+        }
+        String raw = rawOutput != null ? rawOutput : state.answer.toString();
+        Map<String, Object> detail = new LinkedHashMap<>();
+        detail.put("rawOutput", AiSseSupport.abbreviate(safetyGuard.mask(raw, SafetyScene.OUTPUT), 8000));
+        if (StringUtils.isNotBlank(error)) {
+            detail.put("validationError", error);
+        }
+        List<Map<String, Object>> tools = new ArrayList<>();
+        for (AiToolCallAcc acc : state.tools.values()) {
+            if (StringUtils.isBlank(acc.toolName)) {
+                continue;
+            }
+            Map<String, Object> tool = new LinkedHashMap<>();
+            tool.put("toolName", acc.toolName);
+            tool.put("state", acc.state == null ? null : acc.state.name());
+            tool.put("durationMs", acc.durationMs);
+            tools.add(tool);
+        }
+        detail.put("tools", tools);
+        timeline.endStep(expertStepKey, status, conclusion, durationMs, detail);
+    }
+
     /**
      * 进入「专家直答」接管态(REQ-AI-30 直答修订)。
      *

+ 87 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiStepConclusionRefiner.java

@@ -0,0 +1,87 @@
+package com.zsjz.ai.module.ai.core.agent;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import com.zsjz.ai.module.ai.config.AiProperties;
+import com.zsjz.ai.module.ai.domain.AiMessageStep;
+import com.zsjz.ai.module.ai.service.IAiMessageStepService;
+import com.zsjz.ai.module.llm.LlmRequest;
+import com.zsjz.ai.module.llm.LlmService;
+import com.zsjz.ai.common.compat.StringUtils;
+import org.springframework.stereotype.Component;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+/**
+ * 可选的步骤结论 LLM 精炼(P3,默认关,docs/design/chat-process-timeline-plan.md §5.7)。
+ *
+ * <p>开启后在步骤落库之后**异步**用对话模型把确定性结论精炼为更自然的一句话:
+ * 关闭思考(enableThinking=false)、限 80 token、20 秒超时;单步失败回退确定性结论,
+ * 绝不影响回答与已落库步骤。精炼结果只回写 DB(回放可见),不重开已关闭的 SSE。</p>
+ *
+ * @author BizBuddy
+ */
+@Slf4j
+@Component
+@RequiredArgsConstructor
+public class AiStepConclusionRefiner {
+
+    private static final String SYSTEM_PROMPT =
+        "你是执行过程摘要器。把给定的步骤结论改写为一句不超过 40 字的中文摘要,"
+            + "保留关键事实(数量/对象/结果),不要添加原文没有的信息,不要输出引号或前缀,只输出摘要本身。";
+
+    /** 单线程守护执行器:精炼是低优先级旁路,不占对话线程,进程退出不阻塞 */
+    private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor(runnable -> {
+        Thread thread = new Thread(runnable, "step-conclusion-refiner");
+        thread.setDaemon(true);
+        return thread;
+    });
+
+    private final LlmService llmService;
+
+    private final IAiMessageStepService stepService;
+
+    private final AiProperties aiProperties;
+
+    /**
+     * 异步精炼一批步骤的结论(开关关闭时直接返回)。
+     *
+     * @param sessionId 会话主键
+     * @param messageId 助手消息主键
+     * @param modelId   对话模型主键(可空:用默认对话模型)
+     * @param rows      已落库的步骤实体
+     */
+    void refineAsync(Long sessionId, Long messageId, Long modelId, List<AiMessageStep> rows) {
+        if (!aiProperties.getChat().isStepLlmConclusionEnabled() || rows == null || rows.isEmpty()) {
+            return;
+        }
+        EXECUTOR.submit(() -> {
+            for (AiMessageStep row : rows) {
+                if (StringUtils.isBlank(row.getConclusion()) || "confirm".equals(row.getKind())) {
+                    continue;
+                }
+                try {
+                    String refined = llmService.chat(LlmRequest.builder()
+                        .modelId(modelId)
+                        .system(SYSTEM_PROMPT)
+                        .user("步骤:" + row.getTitle() + "\n原始结论:" + row.getConclusion())
+                        .enableThinking(false)
+                        .maxTokens(80)
+                        .timeout(Duration.ofSeconds(20))
+                        .build());
+                    if (StringUtils.isNotBlank(refined)) {
+                        String trimmed = refined.trim().replaceAll("^[\"'“”]+|[\"'“”]+$", "");
+                        stepService.updateConclusion(messageId, row.getStepKey(),
+                            AiSseSupport.abbreviate(trimmed, 80));
+                    }
+                } catch (Exception e) {
+                    log.debug("步骤结论精炼失败(回退确定性结论):messageId={}, stepKey={}, err={}",
+                        messageId, row.getStepKey(), e.getMessage());
+                }
+            }
+        });
+    }
+}

+ 172 - 1
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiStreamEventBridge.java

@@ -5,6 +5,9 @@ import io.agentscope.core.event.ModelCallEndEvent;
 import io.agentscope.core.event.ModelCallStartEvent;
 import io.agentscope.core.event.RequireUserConfirmEvent;
 import io.agentscope.core.event.TextBlockDeltaEvent;
+import io.agentscope.core.event.ThinkingBlockDeltaEvent;
+import io.agentscope.core.event.ThinkingBlockEndEvent;
+import io.agentscope.core.event.ThinkingBlockStartEvent;
 import io.agentscope.core.event.ToolCallDeltaEvent;
 import io.agentscope.core.event.ToolCallStartEvent;
 import io.agentscope.core.event.ToolResultEndEvent;
@@ -27,6 +30,7 @@ import org.springframework.stereotype.Component;
 import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
 
 import java.util.ArrayList;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
@@ -115,6 +119,12 @@ public class AiStreamEventBridge {
      */
     private static final Set<String> COMMAND_TOOL_NAMES = Set.of("execute", "run_command", "bash", "shell");
 
+    /**
+     * 编排协议工具(不建普通工具步:route_decision 的语义由专用 route 步表达,
+     * submit_expert_result 为历史协议工具;与前端 ROUTE_PROTOCOL_TOOLS 同口径)
+     */
+    private static final Set<String> ROUTE_PROTOCOL_TOOLS = Set.of(RouteDecisionTool.TOOL_NAME, "submit_expert_result");
+
     /**
      * 命令结果首行退出码(框架输出形如 {@code Exit code: 1},可能被包成 JSON 字符串带引号)
      */
@@ -178,9 +188,123 @@ public class AiStreamEventBridge {
             onToolResultEnd(emitter, state, resultEnd, forwardToolEvents);
             return;
         }
+        if (event instanceof ThinkingBlockStartEvent thinkingStart) {
+            onThinkingStart(state, thinkingStart);
+            return;
+        }
+        if (event instanceof ThinkingBlockDeltaEvent thinkingDelta) {
+            onThinkingDelta(state, thinkingDelta);
+            return;
+        }
+        if (event instanceof ThinkingBlockEndEvent thinkingEnd) {
+            onThinkingEnd(state, thinkingEnd);
+            return;
+        }
         log.debug("忽略的 AgentScope 事件:{}", event == null ? null : event.getClass().getSimpleName());
     }
 
+    /**
+     * 模型思考开始:建 thinking 步(每个 ThinkingBlock 一步,ReAct 多次模型调用不合并)。
+     *
+     * <p>专家侧思考同样建步(speaker=expert),标题为「专家「X」思考」;入口侧为「深度思考」。
+     * 思考步不受 {@code forwardToolEvents} 门控——它不是工具卡片,专家直答链路同样展示。</p>
+     *
+     * @param state 流式累积状态
+     * @param event 思考开始事件
+     */
+    private void onThinkingStart(AiStreamState state, ThinkingBlockStartEvent event) {
+        AiProcessTimeline process = state.process;
+        if (process == null) {
+            return;
+        }
+        captureReplyId(state, event.getReplyId());
+        boolean expert = StringUtils.isNotBlank(state.speakerExpertName);
+        String title = expert ? "专家「" + state.speakerExpertName + "」思考" : "深度思考";
+        process.startStep(AiProcessTimeline.KIND_THINKING, thinkingKey(state, event.getReplyId(), event.getBlockId()),
+            title, expert ? "expert" : "entry", state.speakerExpertName, state.agentId, null);
+    }
+
+    /**
+     * 模型思考增量:复用 text_delta 的安全尾部缓冲 + 切点对齐机制(防跨片切断 PII),
+     * 仅把「安全头部」累积进思考步并下发 step_delta;命中 BLOCK 时整步跳过(不影响正文)。
+     *
+     * @param state 流式累积状态
+     * @param event 思考增量事件
+     */
+    private void onThinkingDelta(AiStreamState state, ThinkingBlockDeltaEvent event) {
+        AiProcessTimeline process = state.process;
+        if (process == null || StringUtils.isBlank(event.getDelta())) {
+            return;
+        }
+        String stepKey = thinkingKey(state, event.getReplyId(), event.getBlockId());
+        if (process.isThinkingSkipped(stepKey)) {
+            return;
+        }
+        StringBuilder pending = process.thinkingPendingOf(stepKey);
+        if (pending == null) {
+            return;
+        }
+        if (!safetyGuard.anyActive()) {
+            process.appendThinking(stepKey, event.getDelta());
+            return;
+        }
+        pending.append(event.getDelta());
+        int holdBack = Math.max(safetyGuard.holdBackChars(), 0);
+        if (pending.length() <= holdBack) {
+            return;
+        }
+        int cut = alignCutToSafeBoundary(pending, pending.length() - holdBack);
+        if (cut <= 0) {
+            return;
+        }
+        String head = pending.substring(0, cut);
+        pending.delete(0, cut);
+        SafetyDecision decision = safetyGuard.guard(head, SafetyScene.OUTPUT);
+        if (decision.blocked()) {
+            process.skipThinking(stepKey);
+            return;
+        }
+        process.appendThinking(stepKey, decision.text());
+    }
+
+    /**
+     * 模型思考结束:冲刷安全尾部缓冲后结束思考步(结论取首个非空行,详情为全文)。
+     *
+     * @param state 流式累积状态
+     * @param event 思考结束事件
+     */
+    private void onThinkingEnd(AiStreamState state, ThinkingBlockEndEvent event) {
+        AiProcessTimeline process = state.process;
+        if (process == null) {
+            return;
+        }
+        String stepKey = thinkingKey(state, event.getReplyId(), event.getBlockId());
+        if (process.isThinkingSkipped(stepKey)) {
+            return;
+        }
+        StringBuilder pending = process.thinkingPendingOf(stepKey);
+        if (pending != null && pending.length() > 0 && safetyGuard.anyActive()) {
+            String tail = pending.toString();
+            pending.setLength(0);
+            SafetyDecision decision = safetyGuard.guard(tail, SafetyScene.OUTPUT);
+            if (decision.blocked()) {
+                process.skipThinking(stepKey);
+                return;
+            }
+            process.appendThinking(stepKey, decision.text());
+        }
+        process.endThinking(stepKey);
+    }
+
+    /**
+     * 思考步键:{@code think:{replyId}#{blockId}}(replyId 缺失时回退本轮已捕获值)。
+     */
+    private static String thinkingKey(AiStreamState state, String replyId, String blockId) {
+        String rid = StringUtils.isNotBlank(replyId) ? replyId
+            : StringUtils.isNotBlank(state.replyId) ? state.replyId : "unknown";
+        return "think:" + rid + "#" + (StringUtils.isBlank(blockId) ? "b" : blockId);
+    }
+
     /**
      * 工具被配置为「需人工确认」:AgentScope 暂停执行,等待前端确认后恢复。
      *
@@ -283,7 +407,7 @@ public class AiStreamEventBridge {
      * @param cut     原始切点
      * @return 对齐后的切点;为 0 表示本次不下发
      */
-    private static int alignCutToSafeBoundary(CharSequence pending, int cut) {
+    static int alignCutToSafeBoundary(CharSequence pending, int cut) {
         if (cut <= 0 || cut >= pending.length()) {
             return cut;
         }
@@ -346,9 +470,29 @@ public class AiStreamEventBridge {
         payload.put("replyId", textDelta.getReplyId());
         payload.put("blockId", textDelta.getBlockId());
         payload.put("delta", text);
+        putSpeaker(payload, state);
         AiSseSupport.send(emitter, payload);
     }
 
+    /**
+     * 正文增量附带说话人(专家直答镜像用,旧前端忽略可选字段)。
+     *
+     * <p>专家正文直传用户时附带 {@code speaker=expert / expertName / stepKey},前端据此把同一片增量
+     * **镜像**进过程面板的专家步详情(零额外流式体积,不重复发 delta);入口正文不带这些字段。</p>
+     *
+     * @param payload 事件负载
+     * @param state   流式累积状态
+     */
+    private void putSpeaker(Map<String, Object> payload, AiStreamState state) {
+        if (StringUtils.isNotBlank(state.speakerExpertName)) {
+            payload.put("speaker", "expert");
+            payload.put("expertName", state.speakerExpertName);
+            if (StringUtils.isNotBlank(state.processExpertStepKey)) {
+                payload.put("stepKey", state.processExpertStepKey);
+            }
+        }
+    }
+
     /**
      * 输出命中阻断:清空已展示正文并下发拒答文案,后续正文一律丢弃。
      *
@@ -394,6 +538,7 @@ public class AiStreamEventBridge {
             Map<String, Object> payload = AiSseSupport.envelope(EVENT_TEXT_DELTA);
             payload.put("replyId", state.replyId);
             payload.put("delta", decision.text());
+            putSpeaker(payload, state);
             AiSseSupport.send(emitter, payload);
         }
     }
@@ -420,6 +565,15 @@ public class AiStreamEventBridge {
         if (!forwardToolEvents) {
             return;
         }
+        // 执行过程:入口侧工具建 tool 步(专家内部工具不建独立步,经专家步详情的子工具列表透出,
+        // 维持零入参/出参泄漏口径);编排协议工具不建普通工具步
+        AiProcessTimeline process = state.process;
+        if (process != null && !ROUTE_PROTOCOL_TOOLS.contains(start.getToolCallName())) {
+            boolean expert = StringUtils.isNotBlank(state.speakerExpertName);
+            process.startStep(AiProcessTimeline.KIND_TOOL, "tool:" + start.getToolCallId(),
+                "调用「" + toolLabelResolver.labelOf(start.getToolCallName()) + "」",
+                expert ? "expert" : "entry", state.speakerExpertName, state.agentId, start.getToolCallId());
+        }
         Map<String, Object> payload = AiSseSupport.envelope(EVENT_TOOL_CALL_START);
         payload.put("replyId", start.getReplyId());
         payload.put("toolCallId", start.getToolCallId());
@@ -559,6 +713,23 @@ public class AiStreamEventBridge {
             safetyEventService.record(SafetyScene.TOOL_RESULT, decision, safetyGuard.engineName(),
                 state.sessionId, null, state.agentId, state.userId, acc.toolName + "|" + output);
         }
+        // 执行过程:结束 tool 步(结论取输出首个有意义行;详情含入参/出参,出参已过守卫)
+        AiProcessTimeline process = state.process;
+        if (process != null && !ROUTE_PROTOCOL_TOOLS.contains(acc.toolName)) {
+            String stateName = acc.state == null ? null : acc.state.name();
+            String outputText = decision.blocked() ? AiSafetyGuard.REFUSAL_TEXT : decision.text();
+            Map<String, Object> detail = new LinkedHashMap<>();
+            detail.put("toolCallId", resultEnd.getToolCallId());
+            detail.put("toolName", acc.toolName);
+            detail.put("input", AiSseSupport.abbreviate(acc.input.toString(), 2000));
+            detail.put("output", outputText);
+            detail.put("state", stateName);
+            putSource(detail, acc.source);
+            String stepStatus = "SUCCESS".equals(stateName) ? AiProcessTimeline.STATUS_SUCCESS
+                : "DENIED".equals(stateName) ? AiProcessTimeline.STATUS_REJECTED : AiProcessTimeline.STATUS_ERROR;
+            process.endStep("tool:" + resultEnd.getToolCallId(), stepStatus,
+                AiProcessTimeline.toolConclusion(outputText, stateName), acc.durationMs, detail);
+        }
         Map<String, Object> payload = AiSseSupport.envelope(EVENT_TOOL_RESULT);
         payload.put("toolCallId", resultEnd.getToolCallId());
         payload.put("toolName", acc.toolName);

+ 16 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiStreamState.java

@@ -116,6 +116,22 @@ final class AiStreamState {
     /** 暂停时的 AgentScope replyId */
     volatile String pendingReplyId;
 
+    /**
+     * 本轮「执行过程」时间线(思考过程 + 分步结论,可空)。
+     *
+     * <p>由 {@link AiChatFacade} 在开关启用时装配;入口轮 / 专家轮 / 整合轮共享同一实例
+     * (专家侧经 {@link AiRouteContext#timeline} 回挂)。为 null 时全链路保持现状(零行为变化)。</p>
+     */
+    volatile AiProcessTimeline process;
+
+    /**
+     * 当前专家步的步骤键({@code expert:{agentId}#{attemptNo}},可空)。
+     *
+     * <p>由 {@link AiRouteOrchestrator#runExpert} 写入,供事件桥在 {@code text_delta} 载荷里
+     * 附带 speaker/stepKey,前端据此把专家正文**镜像**进过程面板的专家步详情(零额外流式体积)。</p>
+     */
+    volatile String processExpertStepKey;
+
     /** 待确认的工具调用 */
     List<AiConfirmPendingStore.PendingToolCall> pendingToolCalls = List.of();
 

+ 113 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/AiTurnFinisher.java

@@ -8,11 +8,13 @@ import com.zsjz.ai.module.ai.core.safety.AiSafetyGuard;
 import com.zsjz.ai.module.ai.core.safety.SafetyDecision;
 import com.zsjz.ai.module.ai.core.safety.SafetyScene;
 import com.zsjz.ai.module.ai.domain.AiMessage;
+import com.zsjz.ai.module.ai.domain.AiMessageStep;
 import com.zsjz.ai.module.ai.domain.AiRouteRun;
 import com.zsjz.ai.module.ai.domain.AiToolCallLog;
 import com.zsjz.ai.module.ai.domain.AiTrace;
 import com.zsjz.ai.module.ai.domain.dto.ChatTokenUsage;
 import com.zsjz.ai.module.ai.service.IAiPermissionDecisionService;
+import com.zsjz.ai.module.ai.service.IAiMessageStepService;
 import com.zsjz.ai.module.ai.service.IAiSafetyEventService;
 import com.zsjz.ai.module.ai.service.IAiSessionService;
 import com.zsjz.ai.module.ai.service.IAiTraceService;
@@ -117,6 +119,16 @@ public class AiTurnFinisher {
      */
     private final IAiSafetyEventService safetyEventService;
 
+    /**
+     * 执行步骤落库(思考过程 + 分步结论):收尾/暂停时批量 upsert,失败只告警不影响回答
+     */
+    private final IAiMessageStepService stepService;
+
+    /**
+     * 可选的步骤结论 LLM 精炼(默认关;落库后异步旁路,失败回退确定性结论)
+     */
+    private final AiStepConclusionRefiner stepConclusionRefiner;
+
     /**
      * 编排运行收尾(REQ-AI-30):把决策动作、专家调用次数与最终状态写回 {@code ai_route_run}。
      *
@@ -173,6 +185,10 @@ public class AiTurnFinisher {
      */
     void finishCancelled(SseEmitter emitter, Long sessionId, AiStreamState state, long durationMs,
                          Long resumeMessageId, AiRouteContext route) {
+        // 执行过程:running 步统一标为已中止(waiting 步不动;用户主动停止不是失败)
+        if (state.process != null) {
+            state.process.abortRunning(CANCELLED_TEXT);
+        }
         streamBridge.flushSafety(emitter, state);
         traceService.appendTransition(state.traceId, "cancelled", CANCELLED_TEXT);
         traceService.accumulate(state.traceId, AiTrace.STATUS_ABORTED, durationMs, null,
@@ -205,12 +221,15 @@ public class AiTurnFinisher {
         } catch (Exception e) {
             log.error("落库已停止消息异常,sessionId={}, messageId={}", sessionId, resumeMessageId, e);
         }
+        // 执行过程:已中止的步骤同样落库(保留已走步骤供排障与回放)
+        persistProcessSteps(state, sessionId, messageId);
         // 与 done / pending 同口径:写本轮实际落库的助手消息 id(首段中止时 resumeMessageId 为空)
         finishRoute(route, messageId, AiRouteRun.STATUS_ABORTED, CANCELLED_TEXT, durationMs);
         // 载荷与 done 同款字段:前端据 messageId 归位、据 durationMs 渲染耗时(取整轮累计值)
         Map<String, Object> payload = AiSseSupport.envelope(EVENT_ABORTED);
         payload.put("messageId", messageId);
         payload.put("durationMs", totalDuration);
+        putProcessSummary(payload, state);
         AiSseSupport.send(emitter, payload);
         AiSseSupport.complete(emitter);
     }
@@ -268,6 +287,8 @@ public class AiTurnFinisher {
         }
         // 重新生成:新回答已落库,此时才删除被替换的旧回答(中途失败时保留,避免「报错 + 丢答案」)
         deleteReplacedAnswers(sessionId, state);
+        // 执行过程:步骤批量落库(失败只告警,绝不影响已完成的回答)
+        persistProcessSteps(state, sessionId, assistant.getId());
         recordAllowDecisions(state, assistant.getId(), resumeMessageId);
         // 专家调用的工具同样补「实际执行」的决策留痕(REQ-AI-30 Phase 2):按专家维度记账,
         // 被拒绝(DENIED,多为「需确认」档)的不记,避免出现与实际结果相反的「允许」行
@@ -302,6 +323,7 @@ public class AiTurnFinisher {
             // 参考来源:与 references 事件同一 VO 序列化,前端刷新前也可据此回填
             payload.put("references", state.sources);
         }
+        putProcessSummary(payload, state);
         AiSseSupport.send(emitter, payload);
         AiSseSupport.complete(emitter);
         // 平台托管记忆:轮末异步抽取 + 合并;异常只记日志,绝不影响已完成的回答
@@ -441,6 +463,36 @@ public class AiTurnFinisher {
             pendingAgentId, state.userId, state.pendingReplyId, state.pendingToolCalls, null,
             LocalDateTime.now().toString(), expertResume));
 
+        // 执行过程:确认步(waiting 非终态;恢复段按同键 upsert 为 approved/rejected)。
+        // 交互按钮仍在正文流原位的 confirm 卡片,面板内只读镜像。
+        AiProcessTimeline process = state.process;
+        if (process != null && StringUtils.isNotBlank(state.pendingReplyId)) {
+            String confirmKey = "confirm:" + state.pendingReplyId;
+            boolean expertPause = state.pendingAgentId != null;
+            StringBuilder labels = new StringBuilder();
+            List<Map<String, Object>> callItems = new ArrayList<>();
+            for (AiConfirmPendingStore.PendingToolCall call : state.pendingToolCalls) {
+                String label = toolLabelResolver.labelOf(call.toolName());
+                if (labels.length() > 0) {
+                    labels.append("、");
+                }
+                labels.append(label);
+                Map<String, Object> item = new LinkedHashMap<>();
+                item.put("toolCallId", call.toolCallId());
+                item.put("toolName", call.toolName());
+                item.put("toolLabel", label);
+                callItems.add(item);
+            }
+            Map<String, Object> detail = new LinkedHashMap<>();
+            detail.put("toolCalls", callItems);
+            process.startStep(AiProcessTimeline.KIND_CONFIRM, confirmKey, "人工确认",
+                expertPause ? "expert" : "entry", null, pendingAgentId, null);
+            process.endStep(confirmKey, AiProcessTimeline.STATUS_WAITING,
+                "等待你确认:「" + labels + "」", null, detail);
+        }
+        // 执行过程:暂停段步骤落库(confirm 步 waiting;恢复段按同键 upsert 为终态)
+        persistProcessSteps(state, state.sessionId, assistant.getId());
+
         Map<String, Object> payload = new LinkedHashMap<>();
         payload.put("type", EVENT_TOOL_CONFIRM);
         payload.put("messageId", assistant.getId());
@@ -593,6 +645,67 @@ public class AiTurnFinisher {
             .toList();
     }
 
+    /**
+     * 执行过程:把时间线快照映射为步骤实体并批量 upsert 落库。
+     *
+     * <p>与 memoryPipeline 同口径:try/catch 只告警,**绝不影响回答落库**。thinking 全文落库前
+     * 整段再脱敏一次(流式已逐片脱敏,此处为兜底);恢复段续接步(标题为空)走 update 路径保留原值。</p>
+     *
+     * @param state     流式累积状态
+     * @param sessionId 会话主键
+     * @param messageId 助手消息主键(可空:无消息则不落)
+     */
+    void persistProcessSteps(AiStreamState state, Long sessionId, Long messageId) {
+        AiProcessTimeline process = state.process;
+        if (process == null || messageId == null || !process.hasSteps()) {
+            return;
+        }
+        try {
+            List<AiMessageStep> rows = new ArrayList<>();
+            for (AiProcessTimeline.StepView view : process.toStepViews()) {
+                AiMessageStep row = new AiMessageStep();
+                row.setSeq(view.seq());
+                row.setStepKey(view.stepKey());
+                row.setKind(view.kind());
+                row.setTitle(view.title());
+                row.setSpeaker(view.speaker());
+                row.setExpertName(view.expertName());
+                row.setAgentId(view.agentId());
+                row.setStatus(view.status());
+                row.setConclusion(view.conclusion());
+                row.setDurationMs(view.durationMs());
+                Map<String, Object> detail = view.detail();
+                if (detail != null && !detail.isEmpty()) {
+                    if (AiProcessTimeline.KIND_THINKING.equals(view.kind()) && detail.get("text") instanceof String text) {
+                        detail = new LinkedHashMap<>(detail);
+                        detail.put("text", safetyGuard.mask(text, SafetyScene.OUTPUT));
+                    }
+                    row.setDetailJson(JsonUtils.toJsonString(detail));
+                }
+                rows.add(row);
+            }
+            stepService.saveSteps(sessionId, messageId, rows, state.userId);
+            // 可选 LLM 精炼(默认关):异步旁路,不影响回答与已落库步骤
+            stepConclusionRefiner.refineAsync(sessionId, messageId, state.modelId, rows);
+        } catch (Exception e) {
+            log.warn("执行步骤落库失败(不影响回答),sessionId={}, messageId={}", sessionId, messageId, e);
+        }
+    }
+
+    /**
+     * done / aborted 载荷追加执行过程摘要(可选字段,旧前端忽略)。
+     *
+     * @param payload 事件载荷
+     * @param state   流式累积状态
+     */
+    private void putProcessSummary(Map<String, Object> payload, AiStreamState state) {
+        AiProcessTimeline process = state.process;
+        if (process != null && process.hasSteps()) {
+            payload.put("stepCount", process.stepCount());
+            payload.put("thinkingDurationMs", process.thinkingDurationMs());
+        }
+    }
+
     /**
      * 下发失败事件并终止 SSE 流(错误信封的唯一构造点)。
      *

+ 14 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/RouteDecisionTool.java

@@ -120,6 +120,20 @@ class RouteDecisionTool extends ToolBase {
         route.action = action;
         route.decisionJson = JsonUtils.toJsonString(input);
         if (AiRouteRun.ACTION_SELF.equals(action)) {
+            // 执行过程:自答同样建路由决策步(解释「为什么本轮没有专家」)
+            AiProcessTimeline timeline = route.timeline;
+            if (timeline != null) {
+                String reason = text(input.get("reason"));
+                Map<String, Object> detail = new LinkedHashMap<>();
+                detail.put("action", AiRouteRun.ACTION_SELF);
+                detail.put("reason", reason);
+                detail.put("confidence", input.get("confidence"));
+                String key = "route:" + route.routeRunId;
+                timeline.startStep(AiProcessTimeline.KIND_ROUTE, key, "路由决策", "entry", null,
+                    route.entryAgentId, null);
+                timeline.endStep(key, AiProcessTimeline.STATUS_SUCCESS,
+                    AiProcessTimeline.routeConclusion(AiRouteRun.ACTION_SELF, null, reason), null, detail);
+            }
             return Mono.just(ToolResultBlock
                 .text("已记录你的决定:本轮由你自己回答。请直接给出回答,不要再调用本工具。")
                 .withIdAndName(id, name));

+ 1 - 1
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/ToolLabelResolver.java

@@ -75,7 +75,7 @@ public class ToolLabelResolver {
         Map.entry("grep_files", "按文本内容搜索工作区文件"),
         Map.entry("glob_files", "按文件名模式查找工作区文件"),
         Map.entry("list_files", "列出工作区目录内容"),
-        Map.entry("execute", "在宿主机执行命令(无沙箱隔离)"),
+        Map.entry("execute", "在工作区执行命令行操作"),
         Map.entry("web_fetch", "抓取指定网页内容"),
         Map.entry("web_search", "联网搜索(需要 TAVILY_API_KEY)"));
 

+ 103 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiMessageStep.java

@@ -0,0 +1,103 @@
+package com.zsjz.ai.module.ai.domain;
+
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+import com.zsjz.ai.common.compat.BaseEntity;
+
+import java.io.Serial;
+
+/**
+ * AI 助手消息执行步骤对象 ai_message_step(思考过程 + 分步结论)。
+ *
+ * <p>追加型明细,物理删除,不设 del_flag;按 {@code (message_id, step_key)} 幂等更新
+ * (HITL 恢复段续接同一步骤)。仅承接开关启用后新产生的对话,存量历史会话不回填。</p>
+ *
+ * @author BizBuddy
+ */
+@Data
+@EqualsAndHashCode(callSuper = true)
+@TableName("ai_message_step")
+public class AiMessageStep extends BaseEntity {
+
+    @Serial
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 主键
+     */
+    @TableId(value = "id")
+    private Long id;
+
+    /**
+     * 所属会话(ai_session.id)
+     */
+    private Long sessionId;
+
+    /**
+     * 所属助手消息(ai_message.id)
+     */
+    private Long messageId;
+
+    /**
+     * 轮内步骤序号(恢复段续接 maxSeq+n)
+     */
+    private Integer seq;
+
+    /**
+     * 步骤键(轮内唯一,HITL 恢复段 upsert 依据)
+     */
+    private String stepKey;
+
+    /**
+     * 步骤类型 thinking/route/tool/expert/confirm/integration
+     */
+    private String kind;
+
+    /**
+     * 说话人 entry/expert
+     */
+    private String speaker;
+
+    /**
+     * 专家名(speaker=expert 时)
+     */
+    private String expertName;
+
+    /**
+     * 关联智能体主键(专家步/确认步)
+     */
+    private Long agentId;
+
+    /**
+     * 步骤标题(后端拼好)
+     */
+    private String title;
+
+    /**
+     * 状态 running/success/error/skipped/waiting/approved/rejected/expired/aborted
+     */
+    private String status;
+
+    /**
+     * 一行结论(≤80 字)
+     */
+    private String conclusion;
+
+    /**
+     * 详情 JSON(思考全文/工具入参出参/专家原文+子工具/路由理由/确认处置,已脱敏)
+     */
+    private String detailJson;
+
+    /**
+     * 步骤耗时(毫秒)
+     */
+    private Long durationMs;
+
+    /**
+     * 备注
+     */
+    private String remark;
+
+}

+ 8 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiModelConfig.java

@@ -99,6 +99,14 @@ public class AiModelConfig extends BaseEntity {
      */
     private String supportsVision;
 
+    /**
+     * 思考模式覆盖(仅对话模型有意义):true 强制开启 / false 强制关闭 / null 跟随模型与供应商默认。
+     *
+     * <p>开启后模型输出 reasoning_content,框架解析为 ThinkingBlock 事件,
+     * 聊天「执行过程」面板据此流式展示深度思考步(docs/design/chat-process-timeline-plan.md)。</p>
+     */
+    private Boolean enableThinking;
+
     /**
      * 服务地址(OpenAI 兼容根地址);本地模型({@code provider=local})时为模型目录
      */

+ 5 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/bo/AiModelConfigBo.java

@@ -59,6 +59,11 @@ public class AiModelConfigBo implements Serializable {
      */
     private String supportsVision;
 
+    /**
+     * 思考模式覆盖(仅对话模型):true 开启 / false 关闭 / null 跟随默认
+     */
+    private Boolean enableThinking;
+
     /**
      * 服务地址(OpenAI 兼容根地址);本地模型(provider=local)时为模型目录。
      *

+ 98 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiMessageStepVo.java

@@ -0,0 +1,98 @@
+package com.zsjz.ai.module.ai.domain.vo;
+
+import io.github.linpeilie.annotations.AutoMapper;
+import lombok.Data;
+import com.zsjz.ai.module.ai.domain.AiMessageStep;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.time.LocalDateTime;
+
+/**
+ * AI 助手消息执行步骤视图对象 ai_message_step(供对话页精确回放过程时间线)。
+ *
+ * @author BizBuddy
+ */
+@Data
+@AutoMapper(target = AiMessageStep.class)
+public class AiMessageStepVo implements Serializable {
+
+    @Serial
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 主键
+     */
+    private Long id;
+
+    /**
+     * 所属会话(ai_session.id)
+     */
+    private Long sessionId;
+
+    /**
+     * 所属助手消息(ai_message.id)
+     */
+    private Long messageId;
+
+    /**
+     * 轮内步骤序号
+     */
+    private Integer seq;
+
+    /**
+     * 步骤键
+     */
+    private String stepKey;
+
+    /**
+     * 步骤类型 thinking/route/tool/expert/confirm/integration
+     */
+    private String kind;
+
+    /**
+     * 说话人 entry/expert
+     */
+    private String speaker;
+
+    /**
+     * 专家名
+     */
+    private String expertName;
+
+    /**
+     * 关联智能体主键
+     */
+    private Long agentId;
+
+    /**
+     * 步骤标题
+     */
+    private String title;
+
+    /**
+     * 状态
+     */
+    private String status;
+
+    /**
+     * 一行结论
+     */
+    private String conclusion;
+
+    /**
+     * 详情 JSON
+     */
+    private String detailJson;
+
+    /**
+     * 步骤耗时(毫秒)
+     */
+    private Long durationMs;
+
+    /**
+     * 创建时间
+     */
+    private LocalDateTime createTime;
+
+}

+ 5 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiModelConfigVo.java

@@ -52,6 +52,11 @@ public class AiModelConfigVo implements Serializable {
      */
     private String supportsVision;
 
+    /**
+     * 思考模式覆盖(仅对话模型):true 开启 / false 关闭 / null 跟随默认
+     */
+    private Boolean enableThinking;
+
     /**
      * 服务地址
      */

+ 18 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/mapper/AiAuditRetentionMapper.java

@@ -113,4 +113,22 @@ public interface AiAuditRetentionMapper {
     @Delete("delete from ai_route_expert_call where create_time < #{cutoff}")
     int purgeRouteExpertCall(@Param("cutoff") LocalDateTime cutoff);
 
+    /**
+     * 统计超期的消息执行步骤行数
+     *
+     * @param cutoff 保留截止时间
+     * @return 行数
+     */
+    @Select("select count(*) from ai_message_step where create_time < #{cutoff}")
+    long countMessageStep(@Param("cutoff") LocalDateTime cutoff);
+
+    /**
+     * 物理删除超期的消息执行步骤(思考过程 + 分步结论明细)
+     *
+     * @param cutoff 保留截止时间
+     * @return 删除行数
+     */
+    @Delete("delete from ai_message_step where create_time < #{cutoff}")
+    int purgeMessageStep(@Param("cutoff") LocalDateTime cutoff);
+
 }

+ 17 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/mapper/AiMessageStepMapper.java

@@ -0,0 +1,17 @@
+package com.zsjz.ai.module.ai.mapper;
+
+import org.apache.ibatis.annotations.Mapper;
+
+import com.zsjz.ai.module.ai.domain.AiMessageStep;
+import com.zsjz.ai.module.ai.domain.vo.AiMessageStepVo;
+import com.zsjz.ai.common.compat.BaseMapperPlus;
+
+/**
+ * AI 助手消息执行步骤 Mapper 接口
+ *
+ * @author BizBuddy
+ */
+@Mapper
+public interface AiMessageStepMapper extends BaseMapperPlus<AiMessageStep, AiMessageStepVo> {
+
+}

+ 58 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/service/IAiMessageStepService.java

@@ -0,0 +1,58 @@
+package com.zsjz.ai.module.ai.service;
+
+import com.zsjz.ai.module.ai.domain.AiMessageStep;
+import com.zsjz.ai.module.ai.domain.vo.AiMessageStepVo;
+
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * AI 助手消息执行步骤 Service 接口(思考过程 + 分步结论的持久化与回放)。
+ *
+ * @author BizBuddy
+ */
+public interface IAiMessageStepService {
+
+    /**
+     * 批量保存步骤(按 {@code (message_id, step_key)} upsert):
+     * 命中既有键则更新状态/结论/详情/耗时(seq 保留原值),未命中则插入。
+     *
+     * @param sessionId 会话主键
+     * @param messageId 助手消息主键
+     * @param steps     步骤实体(由收尾逻辑从时间线快照映射)
+     * @param userId    触发用户(审计列)
+     */
+    void saveSteps(Long sessionId, Long messageId, List<AiMessageStep> steps, Long userId);
+
+    /**
+     * 查询会话全部步骤(按 message_id, seq 排序,供历史精确回放)。
+     *
+     * @param sessionId 会话主键
+     * @return 步骤视图列表
+     */
+    List<AiMessageStepVo> listBySession(Long sessionId);
+
+    /**
+     * 按助手消息主键批量物理删除(重新生成 / 删除轮次级联)。
+     *
+     * @param messageIds 助手消息主键集合
+     */
+    void deleteByMessageIds(Collection<Long> messageIds);
+
+    /**
+     * 取某消息当前最大步骤序号(HITL 恢复段续接 seqStart;无行返回 0)。
+     *
+     * @param messageId 助手消息主键
+     * @return 最大序号
+     */
+    int maxSeq(Long messageId);
+
+    /**
+     * 按步键更新结论(可选 LLM 精炼回写;无行时静默忽略)。
+     *
+     * @param messageId  助手消息主键
+     * @param stepKey    步骤键
+     * @param conclusion 新结论
+     */
+    void updateConclusion(Long messageId, String stepKey, String conclusion);
+}

+ 9 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/service/IAiSessionService.java

@@ -12,6 +12,7 @@ import com.zsjz.ai.module.ai.domain.vo.AiSessionExportVo;
 import com.zsjz.ai.module.ai.domain.vo.AiSessionVo;
 import com.zsjz.ai.module.ai.domain.vo.AiSourceVo;
 import com.zsjz.ai.module.ai.domain.vo.AiToolCallLogVo;
+import com.zsjz.ai.module.ai.domain.vo.AiMessageStepVo;
 import com.zsjz.ai.common.compat.PageResult;
 import com.zsjz.ai.common.compat.PageQuery;
 
@@ -355,6 +356,14 @@ public interface IAiSessionService {
      */
     List<AiToolCallLogVo> queryOwnedToolCalls(Long sessionId);
 
+    /**
+     * 查询归属当前用户的会话的消息执行步骤(供对话页精确回放过程时间线;存量旧消息无行)。
+     *
+     * @param sessionId 会话主键
+     * @return 步骤明细(按 message_id, seq 升序)
+     */
+    List<AiMessageStepVo> queryOwnedSteps(Long sessionId);
+
     /**
      * 终止会话(会话管理页,不限定归属用户)。
      *

+ 3 - 1
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiAuditRetentionServiceImpl.java

@@ -139,7 +139,9 @@ public class AiAuditRetentionServiceImpl implements IAiAuditRetentionService {
                 retentionMapper::purgePermissionDecisionLog),
             new TableOps("ai_route_run", retentionMapper::countRouteRun, retentionMapper::purgeRouteRun),
             new TableOps("ai_route_expert_call", retentionMapper::countRouteExpertCall,
-                retentionMapper::purgeRouteExpertCall));
+                retentionMapper::purgeRouteExpertCall),
+            new TableOps("ai_message_step", retentionMapper::countMessageStep,
+                retentionMapper::purgeMessageStep));
     }
 
     /**

+ 116 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiMessageStepServiceImpl.java

@@ -0,0 +1,116 @@
+package com.zsjz.ai.module.ai.service.impl;
+
+import com.baomidou.mybatisplus.core.toolkit.Wrappers;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import com.zsjz.ai.module.ai.domain.AiMessageStep;
+import com.zsjz.ai.module.ai.domain.vo.AiMessageStepVo;
+import com.zsjz.ai.module.ai.mapper.AiMessageStepMapper;
+import com.zsjz.ai.module.ai.service.IAiMessageStepService;
+import com.zsjz.ai.common.compat.StringUtils;
+import org.springframework.stereotype.Service;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * AI 助手消息执行步骤 Service 业务层处理(思考过程 + 分步结论)。
+ *
+ * <p>upsert 口径:HITL 暂停段已落 waiting 步,恢复段按 {@code (message_id, step_key)} 命中后
+ * 只更新状态/结论/详情/耗时(seq 与标题保留原值),未命中则插入(seq 由恢复段 maxSeq+n 续接)。</p>
+ *
+ * @author BizBuddy
+ */
+@Slf4j
+@RequiredArgsConstructor
+@Service
+public class AiMessageStepServiceImpl implements IAiMessageStepService {
+
+    private final AiMessageStepMapper baseMapper;
+
+    @Override
+    public void saveSteps(Long sessionId, Long messageId, List<AiMessageStep> steps, Long userId) {
+        if (sessionId == null || messageId == null || steps == null || steps.isEmpty()) {
+            return;
+        }
+        List<AiMessageStep> existing = baseMapper.selectList(Wrappers.<AiMessageStep>lambdaQuery()
+            .eq(AiMessageStep::getMessageId, messageId));
+        Map<String, AiMessageStep> byKey = new HashMap<>();
+        for (AiMessageStep row : existing) {
+            byKey.put(row.getStepKey(), row);
+        }
+        for (AiMessageStep step : steps) {
+            if (StringUtils.isBlank(step.getStepKey())) {
+                continue;
+            }
+            AiMessageStep hit = byKey.get(step.getStepKey());
+            if (hit != null) {
+                // 续接:保留原 seq / 标题 / 类型,仅更新终态与结论详情
+                hit.setStatus(step.getStatus());
+                if (StringUtils.isNotBlank(step.getConclusion())) {
+                    hit.setConclusion(step.getConclusion());
+                }
+                if (StringUtils.isNotBlank(step.getDetailJson())) {
+                    hit.setDetailJson(step.getDetailJson());
+                }
+                if (step.getDurationMs() != null) {
+                    hit.setDurationMs(step.getDurationMs());
+                }
+                hit.setUpdateBy(userId);
+                baseMapper.updateById(hit);
+            } else {
+                step.setSessionId(sessionId);
+                step.setMessageId(messageId);
+                step.setCreateBy(userId);
+                step.setUpdateBy(userId);
+                baseMapper.insert(step);
+            }
+        }
+    }
+
+    @Override
+    public List<AiMessageStepVo> listBySession(Long sessionId) {
+        return baseMapper.selectVoList(Wrappers.<AiMessageStep>lambdaQuery()
+            .eq(AiMessageStep::getSessionId, sessionId)
+            .orderByAsc(AiMessageStep::getMessageId)
+            .orderByAsc(AiMessageStep::getSeq));
+    }
+
+    @Override
+    public void deleteByMessageIds(Collection<Long> messageIds) {
+        if (messageIds == null || messageIds.isEmpty()) {
+            return;
+        }
+        baseMapper.delete(Wrappers.<AiMessageStep>lambdaQuery()
+            .in(AiMessageStep::getMessageId, messageIds));
+    }
+
+    @Override
+    public int maxSeq(Long messageId) {
+        if (messageId == null) {
+            return 0;
+        }
+        AiMessageStep top = baseMapper.selectOne(Wrappers.<AiMessageStep>lambdaQuery()
+            .eq(AiMessageStep::getMessageId, messageId)
+            .orderByDesc(AiMessageStep::getSeq)
+            .last("limit 1"));
+        return top == null || top.getSeq() == null ? 0 : top.getSeq();
+    }
+
+    @Override
+    public void updateConclusion(Long messageId, String stepKey, String conclusion) {
+        if (messageId == null || StringUtils.isBlank(stepKey) || StringUtils.isBlank(conclusion)) {
+            return;
+        }
+        AiMessageStep row = baseMapper.selectOne(Wrappers.<AiMessageStep>lambdaQuery()
+            .eq(AiMessageStep::getMessageId, messageId)
+            .eq(AiMessageStep::getStepKey, stepKey)
+            .last("limit 1"));
+        if (row != null) {
+            row.setConclusion(conclusion);
+            baseMapper.updateById(row);
+        }
+    }
+}

+ 1 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiModelConfigServiceImpl.java

@@ -189,6 +189,7 @@ public class AiModelConfigServiceImpl implements IAiModelConfigService {
         copy.setModelType(source.getModelType());
         copy.setModelCode(source.getModelCode());
         copy.setSupportsVision(source.getSupportsVision());
+        copy.setEnableThinking(source.getEnableThinking());
         copy.setBaseUrl(source.getBaseUrl());
         // 密钥密文原样搬运:不解密、不重加密(明文不进内存与日志,副本与源共享同一密钥)
         copy.setApiKey(source.getApiKey());

+ 18 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiSessionServiceImpl.java

@@ -27,6 +27,7 @@ import com.zsjz.ai.module.ai.domain.vo.AiSessionExportVo;
 import com.zsjz.ai.module.ai.domain.vo.AiSessionVo;
 import com.zsjz.ai.module.ai.domain.vo.AiSourceVo;
 import com.zsjz.ai.module.ai.domain.vo.AiToolCallLogVo;
+import com.zsjz.ai.module.ai.domain.vo.AiMessageStepVo;
 import com.zsjz.ai.module.ai.mapper.AiMessageMapper;
 import com.zsjz.ai.module.ai.mapper.AiScenarioPackMapper;
 import com.zsjz.ai.module.ai.mapper.AiSessionMapper;
@@ -34,6 +35,7 @@ import com.zsjz.ai.module.ai.mapper.AiToolCallLogMapper;
 import com.zsjz.ai.module.ai.mapper.AiToolMapper;
 import com.zsjz.ai.module.ai.service.IAiAgentService;
 import com.zsjz.ai.module.ai.service.IAiChatAttachmentService;
+import com.zsjz.ai.module.ai.service.IAiMessageStepService;
 import com.zsjz.ai.module.ai.service.IAiScenarioPackService;
 import com.zsjz.ai.module.ai.service.IAiSessionService;
 import com.zsjz.ai.common.context.CaseContextHolder;
@@ -150,6 +152,11 @@ public class AiSessionServiceImpl implements IAiSessionService {
 
     private final AiToolCallLogMapper toolCallLogMapper;
 
+    /**
+     * 执行步骤持久化与回放(思考过程 + 分步结论;删除回答/轮次时级联清理)
+     */
+    private final IAiMessageStepService messageStepService;
+
     /**
      * 工具注册表:重新生成预检按 {@code tool_code} 取 {@code tool_type} 判定写操作
      */
@@ -395,6 +402,8 @@ public class AiSessionServiceImpl implements IAiSessionService {
         boolean flag = messageMapper.deleteByIds(doomed) > 0;
         if (flag) {
             decrementMessageCount(sessionId, doomed.size());
+            // 执行步骤随轮次级联物理删除
+            messageStepService.deleteByMessageIds(doomed);
         }
         return flag;
     }
@@ -461,6 +470,8 @@ public class AiSessionServiceImpl implements IAiSessionService {
         int deleted = messageMapper.deleteByIds(ids);
         if (deleted > 0) {
             decrementMessageCount(sessionId, deleted);
+            // 执行步骤随回答级联物理删除(重新生成无残留)
+            messageStepService.deleteByMessageIds(ids);
         }
     }
 
@@ -1030,6 +1041,13 @@ public class AiSessionServiceImpl implements IAiSessionService {
         return queryToolCalls(sessionId);
     }
 
+    @Override
+    public List<AiMessageStepVo> queryOwnedSteps(Long sessionId) {
+        // 与 queryOwnedToolCalls 同口径:只校验归属;对话页由控制器统一做案件校验
+        getOwnedSession(sessionId);
+        return messageStepService.listBySession(sessionId);
+    }
+
     @Override
     public Boolean closeWithValidByIds(Collection<Long> ids) {
         if (ids == null || ids.isEmpty()) {

+ 891 - 0
docs/design/chat-process-timeline-plan.md

@@ -0,0 +1,891 @@
+# AI 聊天「思考过程 + 分步结论」设计方案
+
+| 项 | 内容 |
+|---|---|
+| 文档状态 | 草案 v1.0(待评审,评审通过后按 §11 分阶段实施) |
+| 日期 | 2026-11-18 |
+| 影响范围 | 后端 `ai-server` module/ai(org.dromara.ai 迁移后包 `com.zsjz.ai.module.ai`);前端 `ai-electron/frontend` workbench 聊天页 |
+| 变更性质 | **增量式**:新增事件/表/组件,不重写编排业务逻辑,不新增权限码,存量历史数据不回填 |
+| 关联文档 | `docs/design/pale-reef-swan.md`(权限融合)、`docs/design/tool-call-detail-plan.md`(工具明细) |
+
+## 决策记录(已与需求方确认)
+
+| # | 决策 | 说明 |
+|---|---|---|
+| D1 | 界面形态:**统一折叠过程面板** | 助手气泡顶部「执行过程」容器;流式自动展开为步骤时间线,完成后自动折叠为一行摘要;每步含一行结论、可展开详情 |
+| D2 | 内容范围:**模型思考 + 执行步骤** | 流式展示模型原始推理(reasoning),同时展示路由/工具/专家/确认等执行步骤;模型不吐思考时自动降级为纯执行步骤 |
+| D3 | **过程持久化 + 精确回放**;**存量历史会话不回填、不迁移** | 新对话步骤落库,刷新/切会话后精确还原;数据库中已有旧消息无步骤行,按现有卡片渲染,不写 backfill 脚本 |
+| D4 | **编排专家的输出必须展示** | 专家运行期间回答文本实时镜像进步骤详情;完成后步骤给结论行、可展开完整原文;原文随步骤持久化,回放可见 |
+
+---
+
+## 1. 背景与目标
+
+### 1.1 现状痛点
+
+当前聊天页(`ai-electron/frontend/src/workbench/views/chat/index.vue`,约 5400 行单体 SFC)对"AI 在干什么"的透出非常有限:
+
+1. **没有思考过程**:模型原始推理(reasoning_content)完全没有透出。框架其实已经解析了它(见 §2.6),但桥接层直接忽略。
+2. **只有一行瞬态状态**:`phase` 事件驱动的 `phaseText` 状态条(`index.vue:252-255`)在长等待时播报"数剑在干什么",但**正文一开始流出就消失**,用户无法回看本轮经历了哪些阶段。
+3. **没有"每步结论"**:工具卡只给入参/结果摘要原文,专家卡只在 `done` 后回填原文,路由只有一行判定文案;缺少"这一步做完了什么"的一句话结论。
+4. **历史顺序是近似**:步骤顺序不持久化,历史重建时工具卡在前、正文在后、route/expert 插到首个 text 前(`index.vue:1931-1966,1871-1928`),与实时所见不一致。
+
+### 1.2 目标
+
+- 对标大厂 AI 聊天体验,让用户**实时看到**本轮的完整执行过程(思考 → 路由 → 工具 → 专家 → 确认 → 整合),**每一步都有一行结论**,可展开看详情。
+- 过程**持久化**,刷新/切会话后**精确回放**(顺带修复历史顺序近似问题)。
+- **零侵入**:不改既有编排语义、不动权限模型、旧前端/旧消息/无思考模型全部自动降级;总开关可一键回退到现状。
+
+### 1.3 大厂体验对标拆解
+
+| 产品 | 代表体验 | 本方案取舍 |
+|---|---|---|
+| DeepSeek | 可折叠「深度思考」块,推理文本流式渲染,结束显示"已深度思考(用时 X 秒)",默认折叠 | **采纳**:thinking 步流式渲染 + 耗时摘要 + 自动折叠(D2) |
+| ChatGPT o 系列 | "Thought for X seconds" 一行摘要,展开看思考摘要;工具/检索步骤折叠为活动行 | **采纳**:完成后折叠为一行摘要(D1);不采纳其 LLM 摘要(成本/时延),用确定性结论,LLM 摘要列为 P3 可选 |
+| Manus | 任务步骤时间线,每步状态图标 + 标题 + 结果摘要,过程与最终回答分离 | **采纳**:纵向步骤时间线 + 每步一行结论 + 过程/正文分离(D1/D4);不采纳右侧双栏(现有右侧已是工件面板,窄屏成本高) |
+| Coze / Dify | 工作流节点卡片,节点输入/输出可展开 | **采纳**:步骤详情可展开(入参/出参/原文);不采纳节点画布(聊天场景线性时间线足够) |
+
+### 1.4 非目标(明确不做)
+
+- 不回填/迁移存量历史会话的过程数据(D3)。
+- 不重写编排逻辑(RouteDecisionTool / AiRouteOrchestrator / 专家直答接管语义保持不变)。
+- 不新增权限码(steps 端点复用 `ai:chat:query`)。
+- 不全局强制开启模型 thinking(避免 reasoning 吃光 maxTokens,`module/llm/LlmService.java:345` 已有教训)。
+- 不做 SSE Last-Event-ID 断点续传(维持现状)。
+
+---
+
+## 2. 现状分析(均已读源码/jar 核实)
+
+> 后端基路径 `B = ai-server/src/main/java/com/zsjz/ai/module/ai`;前端基路径 `F = ai-electron/frontend/src`。
+
+### 2.1 前端链路
+
+- 聊天页单体 SFC:`F/workbench/views/chat/index.vue`(name `AiAgentChat`)。消息列表模板 66–361,parts 循环 138–246,输入区 364–578,右侧工件面板 582–659。
+- UI 库 **Ant Design Vue**(非 Element Plus);图标 `Icon`(`@/core/components/Icon`,`i-mdi:*`);Markdown 渲染 `F/workbench/components/AiMarkdown.vue`(markdown-it + highlight.js)。
+- 消息模型(局部 ref,无 Pinia):
+  - `MessagePart`(887–930):`kind: 'text'|'tool'|'confirm'|'expert'|'route'` + 各 kind 字段;
+  - `LocalMessage`(933–961):`id, role, content, parts[], streaming, status, createTime, errorMsg, durationMs, toolCallCount, totalTokens, attachments, sources, retryPayload, phaseText`。
+- SSE 客户端:`F/workbench/api/chatSse.ts` — **fetch + ReadableStream**(GET,`x-token` 头;EventSource 无法带自定义头故不用),URL 36–43:`/ai/chat/stream?sessionId&messageId`、`/ai/chat/resume`、`/ai/chat/session/{sid}/message/{mid}/regenerate`(base = apiUrl + `/js` + `/a`)。帧为**无名 SSE**,按 `payload.type` 分发(119–127)→ **未注册的类型自动忽略**。
+- 事件处理:`handleStreamEvent`(`index.vue:2817-3016`),逐事件映射见 §2.3。
+- 历史加载:`handleSelectSession`(2412–2478)并行 `GET /messages + /toolCalls + /routeRuns`(`F/workbench/api/chat.ts:230-240`),`toLocalMessage`(1931–1966)+ `appendRouteParts`(1871–1928)重建卡片,`/pending` 恢复确认卡。
+- 可复用资产:tool-card/expert-card 折叠模式(模板 140–207,样式 3985/4907)、`msg-sources` 折叠(258–300)、展开键数组 `expandedToolKeys/expertExpertKeys/expandedSourceKeys`(1482–1582)、`a-timeline`(`F/workbench/views/audit/trace/index.vue:237` 已用)、工具中文名 `TOOL_LABELS/toolLabel`(`F/core/http/aiConstants.ts`)、设计令牌 `F/workbench/styles/workbench.less`(`--wb-*`,见 §8.10)。
+
+### 2.2 后端链路
+
+- 两步发送:`POST /ai/chat/session/{sid}/message` 先落库用户消息(`B/controller/AiChatController.java:272`),再 `GET /stream?sessionId&messageId` 开 SSE(Controller:413;resume:435;regenerate:476)。
+- 发射:`AiSseSupport.send`(`B/core/agent/AiSseSupport.java:43-52`)— 无名帧 + JSON 信封 `LinkedHashMap`,必含 `type`(envelope():31)。**无 DTO 类**。
+- 编排:`AiChatFacade.streamChat`(`B/core/agent/AiChatFacade.java:301-503`)经 `AgentAssembler`(:316)构建 AgentScope `HarnessAgent`,`agent.prepareRun(...).stream().subscribe(dispatchEntryEvent)`(438–445)→ `AiStreamEventBridge.handle`(130–182)把 `io.agentscope.core.event.AgentEvent` 桥接为 SSE。
+- 路由:入口智能体「数剑」经自定义工具 `RouteDecisionTool`(`route_decision`)调 `AiRouteOrchestrator.execute`;专家作为**第二个 HarnessAgent** 运行(`runExpert`,Orchestrator:535–719),拥有独立 `AiStreamState`(设 `speakerExpertName`,:561–568)。
+- 进度播报:`AiPhaseSupport.emit`(`B/core/agent/AiPhaseSupport.java:80-98`),7 阶段 `routing/thinking/tool/expert/resuming/integrating/finalizing`,带 `speaker(entry/expert)`,按 `phase|text` 去重。
+- 收尾:`AiTurnFinisher`(`B/core/agent/AiTurnFinisher.java`)四路径 — `finish`(:229,正常落库+done)、`finishPending`(:346,HITL 暂停)、`finishPendingResume`(:385,恢复段收尾)、`finishCancelled`(:174,中止)。工具明细仅在收尾/暂停时由 `buildToolLogs`(:551/:568)从内存 `AiStreamState.tools` 落库,专家明细经 `route.expertToolLogs` 合并。
+
+### 2.3 现有 SSE 事件全清单
+
+| type | 载荷关键字段 | 后端来源 | 前端效果(index.vue) |
+|---|---|---|---|
+| `start` | — | Facade:70,430;ExpertResumeDriver:45 | 无操作(2824) |
+| `phase` | `phase, text, speaker, expertName?` | AiPhaseSupport:80-98 | `msg.phaseText` 状态条,首个 text_delta 清除(2826) |
+| `text_delta` | `replyId, blockId, delta` | Bridge:344-350 | 追加 text part + content(2831) |
+| `tool_call_start` | `replyId, toolCallId, toolName, source?` | Bridge:423-428 | push tool part(running);跳过 `ROUTE_PROTOCOL_TOOLS=['route_decision','submit_expert_result']`(1862)(2844) |
+| `tool_call_delta` | `toolCallId, delta` | Bridge:473-476 | 拼接 part.input JSON(2858) |
+| `tool_result` | `toolCallId, toolName, state, output, durationMs, source?` | Bridge:562-569 | 终态+输出+耗时,触发工件刷新(2865) |
+| `references` | `replyId, items[], toolCallId` | Bridge:570-577 | 合并 KB 来源(去重 docId+chunkIndex)(2959) |
+| `answer_reset` | `{}` | Bridge:86;Orchestrator:87,735 | 清空 text parts(安全拦截/专家接管)(2952) |
+| `route_decision` | `action(route/pinned/self), expertKey, expertAgentId, expertName` | Orchestrator:213-217 | push route note(2903) |
+| `expert_start` | `expertKey, expertAgentId, expertName, attemptNo, callKind` | Orchestrator:545-550 | push expert 卡(running)(2917) |
+| `expert_result` | 同上 + `status(success/invalid)` | Orchestrator:713-718 | expert 卡终态(2930) |
+| `expert_invalid` | `expertKey, error` | Orchestrator(校验失败分支) | invalid + expertError(2937) |
+| `route_fallback` | `reason` | Orchestrator:198 等 | route note「已由数剑自行回答」(2945) |
+| `tool_confirm` | `messageId, replyId, expiresInSec, toolCalls[{toolCallId,toolName,toolLabel,toolDesc,input,content}]` | Finisher:444-451 | 暂停流,push confirm 交互卡(2881) |
+| `done` | `messageId, replyId, durationMs, toolCallCount, totalTokens?, references?` | Finisher:291-303 |  finalize + `syncExpertConclusions()`(1526)回填专家原文(2964) |
+| `aborted` | `messageId, durationMs` | Finisher:211-214 | status='3' 已中止(2984) |
+| `error` | `message, reasonCode?` | Finisher:603-608;Facade:588-591 | status='1' + errorMsg(2997) |
+
+### 2.4 专家直答与回填机制(D4 的关键背景)
+
+- 专家链路 `forwardToolEvents=false`(Bridge:140-143):专家内部工具卡**不下发**(避免噪声),但 `phase` 照播"专家「X」正在调用「Y」工具…"——只透出用了哪个工具,入参/结果不下发。
+- **专家正文直传为最终回答**(direct-answer handoff,Facade:607-613):专家 `text_delta` 转发给用户,入口正文经 `answer_reset` 丢弃。
+- 专家完整原文存 `ai_route_expert_call.rawOutput`(8000 字上限)/`parsedOutput`;前端在 `done` 后经 `GET /session/{sid}/routeRuns`(Controller:256,`AiRouteRunDetailVo.expertCalls[].rawOutput`)回填到 expert 卡(`syncExpertConclusions`,index.vue:1526-1551)。
+- **text_delta 载荷目前没有 speaker 字段**,但桥接层持有 `state.speakerExpertName`,可零成本区分入口/专家(本方案据此做镜像,见 §5.4)。
+
+### 2.5 持久化现状
+
+| 表 | 内容 | 写入时机 | 缺口 |
+|---|---|---|---|
+| `ai_message` | `content`=最终纯文本;replyId/streaming/status(0/2 待确认/3 中止)/errorMsg/toolCallCount/tokens/durationMs/sources(JSON) | 收尾/暂停 | 无步骤、无思考、无顺序 |
+| `ai_tool_call_log` | sessionId/messageId/userId/agentId/toolCallId/toolName/toolInput(全量)/toolOutput(截断)/state/durationMs | 仅收尾/暂停(buildToolLogs) | 无步骤序号,与正文顺序无关 |
+| `ai_trace` | 每轮一行,parentTraceId(专家子 trace)、model 快照、contextJson、`transitionsJson`({state,detail} 节点:tool_call/tool_error/resume/error,有上限) | 流中追加 | 粗粒度审计节点,非展示时间线 |
+| `ai_route_run` | action/decisionJson(reason/confidence)/taskContext/expertCallCount/status/degradeReason/durationMs | 编排收尾 | — |
+| `ai_route_expert_call` | attemptNo/callKind/contractJson/rawOutput(≤8000)/parsedOutput/validationError/status/tokens/durationMs | 专家调用收尾 | 专家原文已有,但未进步骤时间线 |
+
+删除回答仅删 `ai_message` 行(`AiSessionServiceImpl.deleteAnswerMessages:447-465`、`deleteChatRound`),明细靠 messageId 关联查询天然过滤;审计保留任务按 `create_time` 物理清理 6 张明细表(`AiAuditRetentionMapper/Task`)。
+
+### 2.6 框架能力(已核实 jar)
+
+- pom `agentscope.version=2.0.5`(`ai-server/pom.xml:27`),harness/core/model-openai/rag-simple/redis/skill-postgresql 均 2.0.5;本地仓库 `D:\soft\repository\io\agentscope\*\2.0.5` 齐全(**含 sources jar**)。
+- `agentscope-core-2.0.5.jar` 含 `io.agentscope.core.event.ThinkingBlockStartEvent / ThinkingBlockDeltaEvent / ThinkingBlockEndEvent`、`message.ThinkingBlock`、`agent.accumulator.ThinkingAccumulator`。
+- `agentscope-extensions-model-openai-2.0.5-sources.jar` 含 **17 处 `reasoning_content`** 引用(`OpenAIResponseParser`/`OpenAIMessageConverter`/`dto.OpenAIMessage`)→ **框架已把模型 reasoning_content 解析成 ThinkingBlock 事件**。
+- 但 `AiStreamEventBridge.handle` 对 Thinking 事件走兜底 `log.debug("忽略的 AgentScope 事件:{}")`(**Bridge:181**)——能力在边界上唾手可得,只差三个分支。
+- 聊天模型经 `AgentModelFactory.buildChatModel(config)`(:112)构造,**无 thinking 覆盖**;重载 `buildChatModel(config, Boolean enableThinkingOverride)`(:119)已存在,非空时 `ob.additionalBodyParam("enable_thinking", ...)`(:146-151),目前仅 LlmService 辅助调用使用。`AgentAssembler:290` 调的是无覆盖版本 → **是否吐 reasoning 取决于模型/供应商配置**(见 §12 R1 验证步骤)。
+
+### 2.7 缺口小结
+
+| 缺口 | 落点 |
+|---|---|
+| 思考流未透出 | Bridge 加 Thinking 三分支(§4/§10) |
+| 无步骤时间线/每步结论 | 新增 AiProcessTimeline + step_* 事件(§3/§5) |
+| 专家输出只在 done 后回填、无实时过程感 | text_delta 加 speaker 字段 + 前端镜像(§5.4) |
+| 步骤不持久化、历史顺序近似 | 新表 ai_message_step + steps REST + 前端精确回放(§6/§7/§8.8) |
+
+---
+
+## 3. 总体设计
+
+### 3.1 架构
+
+```mermaid
+flowchart LR
+    M["模型 API<br/>(reasoning_content + content)"] --> FW["AgentScope 2.0.5<br/>ThinkingBlock* / ToolCall* / TextBlock* 事件"]
+    FW --> BR["AiStreamEventBridge<br/>(既有桥接 + 新增 thinking/tool 钩子)"]
+    BR --> TL["AiProcessTimeline (新增)<br/>内存步骤累积 + seq + 结论生成"]
+    TL -->|"step_start / step_delta / step_end"| SSE["SSE 无名帧 JSON 信封"]
+    BR -->|"text_delta(+speaker) / tool_* / phase / done..."| SSE
+    SSE --> FE["前端 ProcessPanel (新增)<br/>步骤时间线 + 专家输出镜像"]
+    TL -->|"收尾/暂停批量落库 (try/catch 只告警)"| DB[("ai_message_step (新表)")]
+    DB --> REST["GET /ai/chat/session/{sid}/steps (新增)"]
+    REST -->|"刷新/切会话精确回放"| FE
+```
+
+### 3.2 后端权威时间线(为什么不是前端聚合)
+
+新增 `AiProcessTimeline`(`B/core/agent/AiProcessTimeline.java`,与 `AiStreamState` 同包同生命周期模型):
+
+- 每轮一个实例,按事件到达顺序生成步骤(seq 单调递增),实时下发 step 事件,收尾批量落库。
+- **不选前端聚合**:① 专家内部工具事件 `forwardToolEvents=false` 不下发,前端拿不到;② HITL 跨请求分段,前端拼不出权威顺序;③ `answer_reset` 语义复杂;④ 「刷新后所见 == 流式所见」必须靠落库。
+- **不选 Hook/Middleware**:Thinking 事件已到达 `Bridge.handle`,只需加 `instanceof` 分支;`AgentAssembler.buildMiddlewares`(:625-641)完全不动(硬约束:编排逻辑不变)。
+
+### 3.3 生命周期与跨段共享
+
+- 装配:`Facade.streamChat` 建好 `state` 后 `new AiProcessTimeline(emitter, sessionId, 0)`,挂到 **`AiStreamState.process`**(新字段,可空)与 **`AiRouteContext.timeline`**(新字段)。
+- 专家段:`Orchestrator.runExpert` 把专家 state 的 `process` 指向 `route.timeline`(**共享同一实例**),speaker 用已有 `speakerExpertName`。
+- 整合段:`AiIntegrationDriver` 同样挂 `route.timeline`。
+- HITL 恢复段:`Facade.streamResume` / `AiExpertResumeDriver` 新建 timeline,`seqStart = stepService.maxSeq(messageId)`;步骤键与暂停段一致 → 落库按 `(message_id, step_key)` **upsert**(confirm 步 waiting→终态、expert 步同键续跑,seq 保留原值),恢复段新步 seq=maxSeq+n。
+- 线程约束:timeline 方法 `synchronized` + seq `AtomicInteger`(入口订阅线程与专家 boundedElastic 线程先后访问,事实串行但无 happens-before 保证);遵守 `AiStreamState` 注释的「不引入 subscribeOn/publishOn」约束,钩子全部在既有回调线程内同步调用。
+- emitter 为 null(无人值守链路)时只累积不下发,与 AiSseSupport 同口径。
+
+### 3.4 存量数据边界(D3)
+
+- **不回填、不迁移**:数据库中已有历史会话/消息不写任何 backfill 脚本,不重建过程。
+- 旧消息 steps REST 无行 → 前端走现有 `toLocalMessage/appendRouteParts` 卡片渲染(现状原样)。
+- 新表只承接开关启用后新产生的对话;审计保留任务统一清理(含新表),无额外保留策略。
+- 实施时**严禁**顺手做存量迁移;验收含「存量旧会话打开仍为现有卡片渲染」一项(§13)。
+
+### 3.5 兼容与降级策略
+
+| 场景 | 行为 |
+|---|---|
+| 旧前端 | step_* 事件未注册即忽略;text_delta/done/aborted 新增字段为可选,旧前端不读 → 零影响 |
+| 无 reasoning 模型 | 无 Thinking 事件 → 无 thinking 步,面板仅执行步 |
+| 纯自答零步骤轮 | 面板不渲染,与现状完全一致 |
+| 存量旧消息 | steps 无行 → legacy 卡片渲染(D3) |
+| 总开关关闭 | `processStepsEnabled=false` → timeline 不建,全链路回到现状(逐帧一致,仅多可选字段) |
+| 步骤落库失败 | try/catch 只告警,回答落库不受影响(与 memoryPipeline 同口径) |
+
+### 3.6 配置项(`B/config/AiProperties.java` Chat 内新增)
+
+| 配置 | 默认 | 说明 |
+|---|---|---|
+| `processStepsEnabled` | `true` | 总开关;false 时 timeline 不建、不落库、不发 step 事件 |
+| `thinkingDetailMaxChars` | `8000` | 思考全文落库上限(内存上限 16000) |
+| `stepConclusionChars` | `80` | 一行结论截断长度 |
+| `maxStepsPerMessage` | `200` | 单消息步骤上限,超出只计数 |
+
+---
+
+## 4. SSE 事件协议
+
+### 4.1 信封与分发
+
+沿用无名帧 + JSON 信封(`AiSseSupport.send`),新增事件对旧前端零影响(`chatSse.ts:119-127` 按 type 分发,未注册即忽略)。
+
+### 4.2 stepKey 规则(轮内唯一,恢复段靠它 upsert 同一步骤)
+
+| kind | stepKey | 粒度说明 |
+|---|---|---|
+| thinking | `think:{replyId}#{blockId}` | 每个 ThinkingBlock 一步(ReAct 每次模型调用前各一步,**不合并**) |
+| route | `route:{routeRunId}` | 一次编排一步;self/pinned 同样建步 |
+| tool | `tool:{toolCallId}` | 与既有工具事件同键关联 |
+| expert | `expert:{expertAgentId}#{attemptNo}` | 恢复段续跑同一步骤(不重复开卡,与现有 expert_start 抑制口径一致) |
+| confirm | `confirm:{pendingReplyId}` | 每次暂停一步;键含 pendingReplyId 区分二次暂停批次 |
+| integration | `integ:{routeRunId}` | 整合轮一步 |
+
+### 4.3 新增事件 schema
+
+```jsonc
+// step_start —— 步骤开始
+{ "type": "step_start", "stepKey": "think:r1#b0", "seq": 1,
+  "kind": "thinking", "title": "深度思考", "status": "running",
+  "speaker": "entry",            // entry | expert
+  "expertName": null,             // speaker=expert 时非空
+  "refKey": null }                // tool→toolCallId;expert→agentId#attempt
+
+// step_delta —— 步骤增量(仅 thinking 步;已过安全守卫,口径与 text_delta 相同)
+{ "type": "step_delta", "stepKey": "think:r1#b0", "delta": "用户想要查询…" }
+
+// step_end —— 步骤终态(可对同一 stepKey 重发以更新结论,如 route_fallback)
+{ "type": "step_end", "stepKey": "tool:call_9", "status": "success",
+  "conclusion": "查询到 12 条车辆登记记录",   // ≤80 字,后端拼好,前端只渲染
+  "durationMs": 842,
+  "detail": { } }               // 可选;仅 route 步随事件下发 {action,reason,confidence}
+```
+
+- tool 详情**不随 step 事件重复下发**(走既有 `tool_call_*` 事件,前端 `findLinkedPart` 关联)。
+- expert 完整原文**不随 SSE 下发**(live 走镜像 + 既有回填,回放走 steps REST 的 detailJson)。
+- status 枚举:`running / success / error / skipped / waiting / approved / rejected / expired / aborted`。
+
+### 4.4 既有事件追加可选字段(旧前端忽略)
+
+```jsonc
+// text_delta 追加 speaker/expertName/stepKey —— 供前端镜像专家输出(零额外流式体积,不重复发 delta)
+{ "type": "text_delta", "replyId": "r2", "blockId": "b0", "delta": "根据查询结果…",
+  "speaker": "expert", "expertName": "车辆分析专家", "stepKey": "expert:1024#1" }
+
+// done / aborted 追加 stepCount / thinkingDurationMs(各 thinking 步耗时之和)
+{ "type": "done", "messageId": 9001, "durationMs": 12345, "toolCallCount": 3,
+  "stepCount": 7, "thinkingDurationMs": 4200 }
+```
+
+`phase` 事件**原样保留**(无步骤时的兜底播报 + 旧前端兼容)。
+
+### 4.5 时序图
+
+普通轮(思考 + 工具):
+
+```mermaid
+sequenceDiagram
+    participant U as 前端
+    participant B as Bridge/Timeline
+    participant M as 模型/工具
+    M->>B: ThinkingBlockStart/Delta/End
+    B->>U: step_start(thinking) / step_delta×N / step_end(结论+耗时)
+    M->>B: ToolCallStart/Delta/ResultEnd
+    B->>U: step_start(tool) + 既有 tool_call_start/delta/result
+    B->>U: step_end(tool, 结论)
+    M->>B: TextBlockDelta (最终回答)
+    B->>U: text_delta(speaker=entry)×N
+    B->>U: done(+stepCount/thinkingDurationMs)
+    Note over B: 收尾批量落库 ai_message_step
+```
+
+专家轮(输出镜像 + 回填):
+
+```mermaid
+sequenceDiagram
+    participant U as 前端
+    participant O as Orchestrator/Timeline
+    participant E as 专家 Agent
+    O->>U: step_start(route) + route_decision
+    O->>U: step_end(route, 判定理由)
+    O->>U: step_start(expert) + expert_start
+    E->>O: ThinkingBlock* (专家思考)
+    O->>U: step_start/step_delta/step_end(thinking, speaker=expert)
+    E->>O: TextBlockDelta (专家回答)
+    O->>U: text_delta(speaker=expert, stepKey)×N
+    Note over U: 正文追加(现状不变) + 镜像进 expert 步详情
+    E->>O: 专家完成
+    O->>U: step_end(expert, 结论) + expert_result
+    O->>U: done
+    U->>O: GET routeRuns / steps (回填专家原文)
+    Note over O: 收尾落库 (expert detail_json 含 rawOutput)
+```
+
+HITL 暂停-恢复(upsert 续接):
+
+```mermaid
+sequenceDiagram
+    participant U as 前端
+    participant F as Facade/Timeline
+    participant R as Redis Pending
+    F->>U: step_start(confirm, waiting) + tool_confirm
+    Note over F: finishPending 落库 (confirm 步 waiting)
+    U->>F: POST /confirm (允许/记住/拒绝)
+    F->>R: 写 decisions
+    U->>F: GET /resume
+    Note over F: 新 timeline, seqStart=maxSeq(messageId)
+    F->>U: step_end(confirm:{pendingReplyId}, approved/rejected)
+    F->>U: step_start/... (续跑, 同键 expert 步续接)
+    F->>U: done
+    Note over F: saveSteps 按 (message_id,step_key) upsert
+```
+
+中止:
+
+```mermaid
+sequenceDiagram
+    participant U as 前端
+    participant F as Facade/Timeline
+    U->>F: 停止 / SSE 断连
+    Note over F: timeline.abortRunning("用户停止生成")
+    F->>U: step_end(running 步, aborted) (可能收不到, 前端本地兜底)
+    Note over F: finishCancelled 落库 (aborted 步)
+    F->>U: aborted(+stepCount)
+```
+
+---
+
+## 5. 步骤模型与结论生成
+
+### 5.1 内部累积模型(AiProcessTimeline 内,包级可见,照 AiToolCallAcc 风格)
+
+```java
+final class AiStepAcc {
+    String stepKey; int seq; String kind; String title;
+    String speaker; String expertName; Long agentId; String refKey;
+    String status;                 // running → 终态
+    StringBuilder thinking;        // 仅 thinking 步,内存上限 16000 字符
+    StringBuilder safetyPending;   // 思考流安全尾部缓冲(复用 text_delta 机制)
+    String conclusion; String detailJson;
+    long startNanos; Long durationMs;
+}
+```
+
+timeline 公开方法:`startStep / updateStep / endStep / thinkingDelta / abortRunning(reason) / toStepLogs(messageId) / summarize()`;构造入参 `(SseEmitter, sessionId, seqStart)`。
+
+### 5.2 kind / 标题 / 图标
+
+| kind | 标题(后端拼好) | 前端图标(i-mdi) |
+|---|---|---|
+| thinking | `深度思考`;专家侧=`专家「X」思考` | `brain` |
+| route | `路由决策` | `share-variant-outline` |
+| tool | `调用「{toolLabel}」`(toolLabelResolver 中文名) | `tools` |
+| expert | `咨询专家「X」`;attemptNo>1 追加`(第 N 次)` | `account-tie-outline` |
+| confirm | `人工确认` | `lock-outline` |
+| integration | `汇总整合` | `playlist-check` |
+
+### 5.3 结论生成规则(确定性,零 LLM 成本;timeline 内静态方法)
+
+| kind | conclusion(≤80 字) | detail_json |
+|---|---|---|
+| thinking | 思考文本首个非空行截 80 字;无文本→`思考了 X 秒` | `{text(≤8000,截断标记), truncated}` |
+| route | route:`数剑判定:需咨询专家「X」`+decisionJson.reason 截 60 字;self→`数剑判定:本轮由自己回答`;pinned→`已指定专家:X`;fallback 时 updateStep 为降级说明 | `{action, reason, confidence, taskContext(≤2000)}` |
+| tool | 成功:output 首个有意义行截 80 字(跳过空行/`Exit code: 0`),空→`执行完成`;失败→`执行失败:{state}`;DENIED→`已拒绝执行` | `{toolCallId, toolName, input(≤2000), output(≤toolOutputPreviewChars), state, source}`,落库前过 `safetyGuard.mask(TOOL_RESULT)`(与 buildToolLogs 同口径) |
+| expert | 成功:rawOutput 首行截 80 字,空→`专家「X」已回答`;失败/超时→reason;暂停→`等待你确认后继续` | `{expertAgentId, expertKey, attemptNo, callKind, rawOutput(≤8000), validationError, tools:[{toolName,state,durationMs}]}`(tools 来自专家 state.tools) |
+| confirm | `等待你确认:「工具中文名」`;恢复段回填`已允许执行`/`已拒绝:原因`/`确认已失效` | `{toolCalls:[{toolCallId,toolName,toolLabel}], decisions}` |
+| integration | `已汇总 N 位专家结论` | `{text(≤2000)}` |
+
+### 5.4 专家输出展示专节(D4)
+
+1. **实时镜像**:`text_delta` 追加 `speaker/expertName/stepKey`(桥接层本就持有 `speakerExpertName`,零额外体积)。前端当存在 running 的 expert 步且 `speaker=expert` 时,把 delta **同时**追加进最终正文(现状不变)与该专家步详情文本 → 过程面板实时可见"专家正在输出什么"。
+2. **完成后**:`expert_result` 时 `step_end(expert)` 给结论行(专家回答首行);完整原文 live 沿用 `syncExpertConclusions()`/`syncSteps()` 回填,**并随步骤 detail_json 持久化**(rawOutput≤8000 + 子工具列表),回放同样可见。
+3. **直答接管场景**:专家正文即最终回答(answer_reset 丢弃入口正文)——面板保留入口 thinking/route 步(解释路由决策)+ 专家步(镜像输出+结论+原文),正文区照常显示专家回答;专家步完成后默认折叠,避免与正文重复刷屏。
+4. **多专家/整合**:每位专家各一步(attemptNo 区分重试);整合轮 integration 步显示`已汇总 N 位专家结论`。
+5. **零泄漏口径不变**:专家内部工具仅透出 name/state/duration(来自 state.tools),**不下发也不持久化 input/output**;入口侧工具步照常给入参/结果详情(落库前 mask)。
+
+### 5.5 思考流安全
+
+- `onThinkingDelta` 复用 `onTextDelta` 的尾部缓冲 + `alignCutToSafeBoundary`(把该 private static 方法改为**包级可见**,一行改动),场景用 `SafetyScene.OUTPUT`。
+- BLOCK 时该思考步整体丢弃(status=skipped,conclusion=`思考内容未通过安全审核`),**不影响正文**。
+- 落库前整段再 mask 一次。
+
+### 5.6 截断 / 脱敏 / 上限
+
+| 项 | 上限 | 超限行为 |
+|---|---|---|
+| 思考文本(内存) | 16000 字符 | 停止追加但继续计时 |
+| 思考文本(落库) | 8000 字符 | 截断 + truncated 标记 |
+| 专家原文 | 8000 字符 | 既有口径 |
+| 一行结论 | 80 字(varchar 500) | 截断 |
+| 单步 detail_json | 16KB | 截断 |
+| 单消息步骤数 | 200 | 超出只计数,摘要显示`200+ 个步骤` |
+| 工具入参/出参 | 2000 / toolOutputPreviewChars | 既有口径 + mask |
+
+### 5.7 可选 LLM 一句话结论(P3,默认关)
+
+异步调 `LlmService`(enableThinking=false)为每步生成更精炼的一句话结论;配置开关默认关;失败/超时回退确定性结论。成本/时延明确后再上,**P1/P2 不做**。
+
+---
+
+## 6. 数据库设计
+
+### 6.1 DDL(`sql/ai_message_step.sql`,幂等,照 `sql/ai_orchestration.sql:639-657` 约定)
+
+```sql
+create table if not exists ai_message_step (
+    id           bigint       not null,
+    session_id   bigint       not null,
+    message_id   bigint       not null,
+    seq          integer      not null,
+    step_key     varchar(128) not null,
+    kind         varchar(20)  not null,
+    speaker      varchar(10)  default 'entry',
+    expert_name  varchar(100),
+    agent_id     bigint,
+    title        varchar(200) not null,
+    status       varchar(20)  not null,
+    conclusion   varchar(500),
+    detail_json  text,
+    duration_ms  bigint,
+    remark       varchar(500),
+    create_by    bigint,
+    create_time  timestamp,
+    update_by    bigint,
+    update_time  timestamp,
+    constraint pk_ai_message_step primary key (id)
+);
+create unique index if not exists uk_ai_message_step_key on ai_message_step (message_id, step_key);
+create index if not exists idx_ai_message_step_session on ai_message_step (session_id, message_id, seq);
+comment on table ai_message_step is 'AI 助手消息执行步骤表(思考/路由/工具/专家/确认/整合,物理追加+按步键幂等更新,仅新数据写入)';
+comment on column ai_message_step.id is '主键(雪花)';
+comment on column ai_message_step.session_id is '所属会话(ai_session.id)';
+comment on column ai_message_step.message_id is '所属助手消息(ai_message.id)';
+comment on column ai_message_step.seq is '轮内步骤序号(恢复段续接 maxSeq+n)';
+comment on column ai_message_step.step_key is '步骤键(轮内唯一,HITL 恢复段 upsert 依据)';
+comment on column ai_message_step.kind is '步骤类型 thinking/route/tool/expert/confirm/integration';
+comment on column ai_message_step.speaker is '说话人 entry/expert';
+comment on column ai_message_step.expert_name is '专家名(speaker=expert 时)';
+comment on column ai_message_step.agent_id is '关联智能体主键(专家步)';
+comment on column ai_message_step.title is '步骤标题(后端拼好)';
+comment on column ai_message_step.status is '状态 running/success/error/skipped/waiting/approved/rejected/expired/aborted';
+comment on column ai_message_step.conclusion is '一行结论(≤80 字)';
+comment on column ai_message_step.detail_json is '详情 JSON(思考全文/工具入参出参/专家原文+子工具/路由理由/确认处置,已脱敏)';
+comment on column ai_message_step.duration_ms is '步骤耗时(毫秒)';
+```
+
+要点:明细表**物理删除、无 del_flag、无外键**;雪花 bigint 主键 + 审计四列(照 `AiToolCallLog`)。
+
+### 6.2 upsert 语义
+
+`uk(message_id, step_key)` 支撑 HITL 恢复段:暂停段 confirm 步 waiting 已落库 → 恢复段按 decisions 回填终态(update status/conclusion/detail/duration,**seq 保留原值**);expert 步同键续跑;恢复段新步 `seq = maxSeq + n`。`saveSteps` 实现:先查已有键,命中 update,未命中 insert。
+
+### 6.3 写入时机
+
+`AiTurnFinisher` 四路径(`finish`:229 / `finishPending`:346 / `finishPendingResume`:385 / `finishCancelled`:174)在**消息落库成功后**追加:
+
+```java
+try {
+    stepService.saveSteps(sessionId, assistant.getId(), state.process.toStepLogs(assistant.getId()));
+} catch (Exception e) {
+    log.warn("步骤落库失败(不影响回答),messageId={}", assistant.getId(), e);
+}
+```
+
+与 memoryPipeline 同口径:**绝不影响回答落库**。`finishPending` 时 confirm 步 status=waiting 一并落库。error 路径(`persistAssistantFailure`)同样落步骤供排障。
+
+### 6.4 级联删除
+
+`AiSessionServiceImpl.deleteAnswerMessages`(:447-465)与 `deleteChatRound` 事务内追加 `stepService.deleteByMessageIds(ids)` → 重新生成/删轮次无残留。
+
+### 6.5 审计保留
+
+`AiAuditRetentionMapper` / `AiAuditRetentionTask` 追加 `ai_message_step` 的 count/delete(照 `ai_tool_call_log` 样式),按 create_time cutoff 统一清理。
+
+### 6.6 存量边界
+
+**仅新数据写入**;不回填、不迁移(D3)。旧消息无步骤行,前端 legacy 渲染。
+
+---
+
+## 7. REST API
+
+### 7.1 新增端点(照 toolCalls 样式,Controller:238-244)
+
+```java
+/**
+ * 查询会话的消息执行步骤(供对话页精确回放过程时间线;仅新数据,存量旧消息无行)
+ */
+@SaCheckPermission("ai:chat:query")   // 复用既有权限码,不新增
+@GetMapping("/session/{sessionId}/steps")
+public R<List<AiMessageStepVo>> listSteps(@NotNull(message = "会话不能为空")
+                                          @PathVariable("sessionId") Long sessionId) {
+    aiSessionService.assertSessionInCurrentCase(sessionId);
+    return R.ok(aiSessionService.queryOwnedSteps(sessionId));
+}
+```
+
+`queryOwnedSteps` 照 `queryOwnedToolCalls`(AiSessionServiceImpl:1027-1031):`getOwnedSession(sessionId)` 归属校验 + `stepService.listBySession(sessionId)`(按 message_id, seq 排序)。
+
+### 7.2 AiMessageStepVo 字段
+
+| 字段 | 类型 | 说明 |
+|---|---|---|
+| id / messageId / sessionId | Long | 主键/关联 |
+| seq | Integer | 轮内序号 |
+| stepKey | String | 步骤键 |
+| kind | String | thinking/route/tool/expert/confirm/integration |
+| speaker / expertName / agentId | String/String/Long | 说话人 |
+| title | String | 标题 |
+| status | String | 终态(回放无 running) |
+| conclusion | String | 一行结论 |
+| detailJson | String | 详情 JSON(前端解析) |
+| durationMs | Long | 耗时 |
+| createTime | Date | 创建时间 |
+
+### 7.3 前端 API 封装(`F/workbench/api/chat.ts` 追加)
+
+```ts
+export interface ChatMessageStepVO {
+  id: Id; messageId: Id; seq: number; stepKey: string;
+  kind: 'thinking' | 'route' | 'tool' | 'expert' | 'confirm' | 'integration';
+  speaker?: 'entry' | 'expert'; expertName?: string; title: string; status: string;
+  conclusion?: string; detailJson?: string; durationMs?: number; createTime?: string;
+}
+export function listChatSteps(sessionId: Id): Promise<ChatMessageStepVO[]> {
+  return aiGet(`/ai/chat/session/${sessionId}/steps`);
+}
+```
+
+### 7.4 错误与降级
+
+steps 请求失败 → 降级空数组(照现有历史加载逐项降级风格)→ 该会话消息走 legacy 卡片渲染,不阻断会话打开。
+
+---
+
+## 8. 前端设计
+
+### 8.1 组件树(新增 `F/workbench/components/chat/`)
+
+```
+chat/index.vue (既有,外科手术)
+└─ ProcessPanel.vue (新增,容器)
+   └─ ProcessStepItem.vue ×N (新增,步骤节点)
+      ├─ ThinkingDetail.vue (新增,thinking 步详情)
+      ├─ pre.tool-code (tool 入参/出参,复用既有样式)
+      ├─ pre.tool-code (expert 镜像文本/原文 + 子工具列表)
+      └─ route/confirm 只读详情
+```
+
+### 8.2 processTypes.ts(纯函数,可单测,index.vue 不膨胀)
+
+```ts
+export interface ProcessStep {
+  stepKey: string; seq: number;
+  kind: 'thinking' | 'route' | 'tool' | 'expert' | 'confirm' | 'integration';
+  title: string; status: string;
+  speaker?: 'entry' | 'expert'; expertName?: string; refKey?: string;
+  conclusion?: string; durationMs?: number;
+  thinkingText?: string;        // thinking 步流式累积
+  mirrorText?: string;          // expert 步实时镜像
+  detail?: Record<string, any>; // 解析后的 detailJson / route detail
+  linkedPart?: MessagePart;     // tool 步关联的既有 tool part(入参/出参)
+}
+// reducer:start 追加 / delta 拼接 / end 归一;按 stepKey upsert;乱序/重复 end 容错
+export function applyStepEvent(steps: ProcessStep[], event: any): void;
+export function mirrorExpertDelta(steps: ProcessStep[], event: any): void;
+export function buildStepsFromVo(vos: ChatMessageStepVO[]): ProcessStep[]; // 解析 detailJson
+export function summarizeSteps(steps: ProcessStep[]): { count: number; thinkingMs: number; activeTitle?: string };
+export function findLinkedPart(parts: MessagePart[], step: ProcessStep): MessagePart | undefined;
+```
+
+### 8.3 ProcessPanel.vue
+
+| props | 类型 | 说明 |
+|---|---|---|
+| steps | ProcessStep[] | 步骤列表 |
+| streaming | boolean | 本轮是否流式中 |
+| durationMs / thinkingMs | number? | 总耗时 / 思考耗时 |
+| expanded | boolean | 展开态(父级管理) |
+
+emits:`toggle`。头部状态机:
+- 流式中:脉冲点 + 当前活动步标题(`正在:{activeTitle}`);
+- 完成:摘要行 `已完成 N 个步骤 · 用时 X 秒`(有思考步前缀 `已深度思考 Y 秒 ·`;中止 `已中止 · 完成 N 个步骤`;超上限 `200+ 个步骤`)。
+折叠体:步骤纵列,左侧 1px 时间线轨;展开过渡用 max-height/opacity(照 tool-card 模式)。
+
+### 8.4 ProcessStepItem.vue
+
+props:`step / expanded`;emits:`toggle`。节点行:kind 图标 + 标题 + `a-tag` 状态 + 耗时 + **一行结论**(`--wb-text-2`,单行省略)。展开详情按 kind 分发:
+
+| kind | 详情内容 |
+|---|---|
+| thinking | ThinkingDetail(markdown 全文 + 光标 + 耗时) |
+| tool | 调用入参 / 结果摘要 `pre.tool-code`(数据取 linkedPart 或 detail) |
+| expert | 镜像文本/原文 `pre.tool-code` + 子工具列表(name/state/duration) |
+| route | 判定理由 / 置信度 / 任务片段 |
+| confirm | 只读状态(工具中文名 + 处置结果);**交互按钮不在此** |
+| integration | 整合说明 |
+
+running 标题微光扫动;状态色映射见 §8.10。
+
+### 8.5 ThinkingDetail.vue
+
+`AiMarkdown` 渲染 thinkingText + 流式光标(复用 `.typing-cursor`)+ 底部 `思考了 X 秒`;流式中自动滚到容器底(仅当面板展开且 stickToBottom)。
+
+### 8.6 状态模型变更
+
+- `LocalMessage`(index.vue:933)追加 `steps?: ProcessStep[]`、`processUserToggled?: boolean`;**MessagePart 不动**。
+- 新增 `expandedProcessKeys = ref<string[]>([])`(照 expandedSourceKeys:1571 模式,键=msg.id);切会话清空(:2427 旁)。
+
+### 8.7 index.vue 逐点改动清单(逻辑零重写)
+
+| # | 位置 | 改动 |
+|---|---|---|
+| 1 | :933 LocalMessage | 追加 steps / processUserToggled 字段 |
+| 2 | :137 bubble 内、parts 循环前 | 插 `<ProcessPanel v-if="msg.steps?.length" ...>`;旧 tool/expert/route 三分支(:140/:176/:208)各加 `&& !msg.steps?.length` 抑制(数据照旧构建);**confirm 交互卡(:212)与 text 分支不动** |
+| 3 | :2817 handleStreamEvent | 追加 `case 'step_start'/'step_delta'/'step_end'` → applyStepEvent;text_delta 分支追加 speaker=expert 镜像(正文逻辑不变);step_start 且未手动操作→自动展开;done/aborted 末尾→未手动操作则自动折叠 + `syncSteps(msg)`;**answer_reset 不清 steps**;phase 分支保留兜底 |
+| 4 | :1482-1582 展开键区 | expandedProcessKeys + toggleProcess(置 processUserToggled=true,用户操作优先) |
+| 5 | :2430 handleSelectSession | Promise.all 增第 4 路 listChatSteps(失败降级空数组);按 messageId 分组 buildStepsFromVo 挂 local.steps;**无步骤旧消息走原路径不动** |
+| 6 | :2740 handleStop | 本地把 running 步标 aborted(与 msg.status='3' 同口径) |
+| 7 | :2688 handleRegenerate | backup 浅拷贝追加 steps;预检拒绝→restoreRegenerateBackup 恢复 |
+| 8 | 滚动 | 沿用 scrollToBottomSoon()(每事件已调用),面板高度增长由 stickToBottom 自然跟随 |
+
+`syncSteps(msg)`:拉 steps REST 覆盖 live 构建的 steps(权威对齐,顺带带回专家 rawOutput 与子工具详情);legacy 消息保留 `syncExpertConclusions()`。
+
+### 8.8 历史回放路径(D3)
+
+有步骤的消息:`buildStepsFromVo` 精确还原顺序/结论/详情(含专家原文)→ ProcessPanel 渲染,legacy 卡抑制。
+无步骤的存量旧消息:原 `toLocalMessage/appendRouteParts` 不动 → legacy 卡片渲染(**不回填**)。
+
+### 8.9 交互细节
+
+- **自动展开/折叠与用户优先**:step_start 自动展开、done/aborted 自动折叠;用户手动 toggle 后 `processUserToggled=true`,自动行为让位。
+- **滚动**:面板展开时思考流高度增长由既有 stickToBottom 跟随;ThinkingDetail 内部独立滚动到底。
+- **动画**:脉冲点 1.2s、chevron 旋转 0.2s ease、running 标题微光扫动、流式光标 1s steps(全部复用既有节奏)。
+- **a11y**:节点头 `role="button" tabindex="0"` + Enter/Space 切换 + `aria-expanded`(照 tool-card:141-148)。
+
+### 8.10 视觉规格(全部 `--wb-*` 令牌,不引入新依赖)
+
+| 令牌 | 值 | 用途 |
+|---|---|---|
+| `--wb-primary` | #2a50ec | running 状态、时间线轨、图标 |
+| `--wb-primary-soft` | #e8eefc | 面板底色渐变 `linear-gradient(135deg, var(--wb-primary-soft), transparent)` |
+| `--wb-success` | #16a34a | success/approved |
+| `--wb-warning` | #d97706 | waiting |
+| `--wb-error` | #dc2626 | error/rejected |
+| `--wb-text-muted` | #94a3b8 | skipped/expired/aborted |
+| `--wb-border` | #e5e9f2 | 面板/节点边框 |
+| `--wb-text-2` | #64748b | 结论行 |
+| `--wb-radius` | 8px | 圆角 |
+
+滚动条按项目既有样式口径(宽度/轨道/滑块取色自上述令牌),不用浏览器默认。
+
+### 8.11 线框图
+
+流式中(自动展开):
+
+```
+┌ 助手气泡 ────────────────────────────────────────────┐
+│ ┌ 执行过程 ─────────────────────────── ▾ ┐           │
+│ │ ● 正在:调用「车辆登记查询」            │           │
+│ │ │                                      │           │
+│ │ ├ 🧠 深度思考        [成功] 3.2s       │           │
+│ │ │   结论:用户想查某人名下车辆…         │           │
+│ │ ├ 🔀 路由决策        [成功] 0.4s       │           │
+│ │ │   结论:数剑判定:需咨询车辆分析专家  │           │
+│ │ ├ 👤 咨询专家「车辆分析专家」 [运行中]  │           │
+│ │ │   ┌ 专家输出(实时镜像)──────────┐  │           │
+│ │ │   │ 根据查询结果,该人名下共有…▌  │  │           │
+│ │ │   └─────────────────────────────┘  │           │
+│ │ └ 🔧 调用「车辆登记查询」 [运行中]     │           │
+│ └────────────────────────────────────────┘           │
+│ (正文区:专家回答流式输出中…)                        │
+└──────────────────────────────────────────────────────┘
+```
+
+完成后(自动折叠):
+
+```
+┌ 助手气泡 ────────────────────────────────────────────┐
+│ ▸ 已深度思考 3.2 秒 · 已完成 6 个步骤 · 用时 12.3 秒   │
+│                                                      │
+│ 根据查询结果,该人名下共有 2 辆车辆登记记录…(正文)   │
+│ 📎 参考来源(折叠)                                  │
+└──────────────────────────────────────────────────────┘
+```
+
+展开回看(含专家原文):
+
+```
+│ ▾ 已深度思考 3.2 秒 · 已完成 6 个步骤 · 用时 12.3 秒   │
+│ ├ 🧠 深度思考 [成功] 3.2s  结论:用户想查某人名下车辆… │
+│ │   ▸ 展开查看思考全文(markdown)                    │
+│ ├ 🔀 路由决策 [成功] 0.4s  结论:需咨询车辆分析专家    │
+│ ├ 👤 咨询专家「车辆分析专家」 [成功] 8.1s             │
+│ │   结论:该人名下共有 2 辆车辆登记记录               │
+│ │   ▾ 专家原始结论(原文留证)                        │
+│ │     ┌────────────────────────────────────────┐     │
+│ │     │ 根据车辆登记库查询…(rawOutput 全文)   │     │
+│ │     └────────────────────────────────────────┘     │
+│ │     子工具:车辆登记查询 [成功] 842ms               │
+│ ├ 🔧 调用「车辆登记查询」 [成功] 842ms                │
+│ │   结论:查询到 2 条车辆登记记录                     │
+│ │   ▸ 入参 / 结果摘要                                 │
+│ └ …                                                  │
+```
+
+### 8.12 窄屏(P3)
+
+900px 以下单列适配:面板全宽、详情 pre 横向滚动、结论行省略不折行。
+
+---
+
+## 9. 边缘场景与兼容矩阵
+
+| 场景 | 行为 |
+|---|---|
+| 无 reasoning 模型 | 无 Thinking 事件→无 thinking 步,面板仅执行步;纯自答零步骤→面板不渲染(与现状一致) |
+| 中止(停止/断连) | `timeline.abortRunning("用户停止生成")`:running 步→aborted;finishCancelled 落库;摘要`已中止 · 完成 N 个步骤`;前端 handleStop 本地兜底 |
+| 流中错误 | error 回调 abortRunning(errorMsg),失败消息也落步骤,面板保留已走步骤供排障 |
+| HITL 暂停 | confirm 步 waiting + 既有 tool_confirm 交互卡原位;步骤随 finishPending 落库;SSE 关闭 |
+| HITL 恢复 | seqStart=maxSeq;confirm 步按 decisions 回填终态(upsert 同键);expert 步同键续跑;新 thinking/tool 步追加;前端同一 LocalMessage 累积 |
+| 二次暂停 | confirm 键含 pendingReplyId 区分批次;旧 pending 卡 expired 逻辑不动 |
+| 重新生成 | 新回答落库后级联删旧步骤;预检拒绝→backup 恢复 steps |
+| answer_reset / 专家接管 | 只清 text parts;入口 thinking/route 步**保留**(解释路由决策);专家步 speaker=expert 追加+镜像输出 |
+| 专家超时/降级 | expert 步 error+reason;route 步 conclusion 更新降级说明(route_fallback → step_end 重发) |
+| 超长思考/输出 | 内存 16000/落库 8000 截断(停止追加继续计时)、结论 80、detail 16KB、单消息 200 步 |
+| 并发会话 | timeline 每轮独立实例,无共享态;seq 轮内单调 |
+| 刷新/重连/切会话 | **步骤经 steps REST 精确回放**(暂停段已落库不丢);无 Last-Event-ID(维持现状) |
+| 存量旧消息 | steps 无行→legacy 卡片渲染原样,**不回填不迁移**(D3) |
+| 总开关关闭 | 全链路回到现状(逐帧一致,仅多可选字段) |
+
+---
+
+## 10. 后端改动清单
+
+### 10.1 新增文件(7 个)
+
+| 路径(B 下) | 内容 |
+|---|---|
+| `core/agent/AiProcessTimeline.java` | 时间线:startStep/updateStep/endStep/thinkingDelta/abortRunning/toStepLogs/summarize;synchronized + AtomicInteger;emitter null 只累积 |
+| `domain/AiMessageStep.java` | `@TableName("ai_message_step") extends BaseEntity`,照 AiToolCallLog.java 风格(@Data/@EqualsAndHashCode/@TableId/字段 javadoc) |
+| `domain/vo/AiMessageStepVo.java` | 照 AiToolCallLogVo |
+| `mapper/AiMessageStepMapper.java` | `extends BaseMapperPlus<AiMessageStep, AiMessageStepVo>` |
+| `service/IAiMessageStepService.java` + `service/impl/AiMessageStepServiceImpl.java` | saveSteps(upsert)、listBySession、deleteByMessageIds、maxSeq |
+| `sql/ai_message_step.sql`(仓库根 sql/) | §6.1 DDL |
+
+### 10.2 修改文件(钩子全部为追加行/追加分支)
+
+| 文件 | 改动 |
+|---|---|
+| `core/agent/AiStreamEventBridge.java` | ① handle 加三个 `instanceof ThinkingBlock*Event` 分支(:181 兜底前)→ onThinkingStart/Delta/End;② onToolCallStart 末尾追加 startStep(**放在 forwardToolEvents 判断之前**,专家内部工具也记步骤,但 SSE 下发受 forwardToolEvents 门控);③ onToolResultEnd 追加 endStep;④ text_delta 载荷追加 speaker/expertName/stepKey(取 state.speakerExpertName);⑤ alignCutToSafeBoundary 改包级可见 |
+| `core/agent/AiStreamState.java` | 加字段 `AiProcessTimeline process;`(可空→未装配零行为变化) |
+| `core/agent/AiRouteContext.java` | 加字段 `volatile AiProcessTimeline timeline;` |
+| `core/agent/AiChatFacade.java` | ① streamChat:state 建好后装配 timeline 挂 state.process + route.timeline;② streamResume(:688 附近):seqStart=maxSeq,新建 timeline;恢复开始即对 confirm:{pendingReplyId} 发 step_end(approved/rejected,取 pending.decisions);③ error 回调 abortRunning + 失败消息落步骤 |
+| `core/agent/AiRouteOrchestrator.java` | ① route_decision 处(:213-217)startStep+endStep(route)(self/pinned 同样建步);② runExpert:state.process=route.timeline;expert_start 处 startStep,expert_result/取消/超时/暂停各分支 endStep(暂停→waiting 不发终态,与现有口径一致);③ route_fallback 处 updateStep(route 结论) |
+| `core/agent/AiIntegrationDriver.java` | 整合轮 state 挂 route.timeline;PHASE_INTEGRATING 处 startStep(integration),收尾 endStep |
+| `core/agent/AiExpertResumeDriver.java` | 恢复段 state 挂 timeline(seqStart=maxSeq);续跑专家步复用 expert:{agentId}#{attempt} 键 |
+| `core/agent/AiTurnFinisher.java` | finish/finishPending/finishPendingResume/finishCancelled 四处消息落库成功后追加 saveSteps(try/catch 只告警);done/aborted 载荷追加 stepCount/thinkingDurationMs;finishPending 时 confirm 步 waiting 落库 |
+| `service/impl/AiSessionServiceImpl.java` | deleteAnswerMessages/deleteChatRound 事务内追加 deleteByMessageIds;新增 queryOwnedSteps(照 queryOwnedToolCalls:1027) |
+| `controller/AiChatController.java` | 新增 steps 端点(§7.1,复用 ai:chat:query) |
+| `AiAuditRetentionMapper.java` / `AiAuditRetentionTask.java` | 追加 ai_message_step count/delete |
+| `config/AiProperties.java` | Chat 内新增 §3.6 四配置 |
+
+### 10.3 改动纪律
+
+- 全部增量追加;**不改既有事件语义、不改编排逻辑、不动 buildMiddlewares、不新增权限码**。
+- `RouteDecisionTool` / 专家直答接管 / detectWriteTools 等审计逻辑不动。
+- steps=展示权威,toolCalls/routeRuns=审计权威,双份数据并存不互斥。
+
+---
+
+## 11. 分阶段实施计划
+
+### Phase 1 — 实时过程可见(独立可发布,无 DB 变更)
+
+后端:AiProcessTimeline(内存+SSE)、AiStreamState.process、Bridge thinking 分支 + tool 钩子 + text_delta speaker、AiRouteContext.timeline、Facade.streamChat 装配、Orchestrator route/expert/fallback 钩子、Properties 开关。
+前端:processTypes.ts、ProcessPanel/ProcessStepItem/ThinkingDetail、chat.ts 类型、index.vue 第 1/2/3/4/6/7 点。
+
+**验收**:思考模型流式可见思考步 + 工具/专家步 + 结论行;专家输出实时镜像;done 自动折叠摘要;HITL 暂停/恢复步骤续接(内存态);无思考模型仅执行步;旧消息渲染不变。
+
+### Phase 2 — 持久化与历史回放(仅新数据,存量不回填)
+
+后端:sql/ai_message_step.sql、实体/VO/Mapper/Service(upsert)、TurnFinisher 四收尾落库 + done/aborted 追加字段、streamResume/ExpertResumeDriver/IntegrationDriver 挂接 + seqStart、confirm 步、steps 端点、级联删除、审计保留、error 路径落库。
+前端:listChatSteps、handleSelectSession 第 4 路、buildStepsFromVo、syncSteps、regenerate backup steps。
+
+**验收**:刷新/切会话后步骤顺序/结论/详情(含专家原文)与流式一致;HITL 暂停→恢复步骤连续且 confirm 终态正确;重新生成旧步骤清除;保留任务清理生效;**存量旧会话渲染不变(无回填)**。
+
+### Phase 3 — 打磨与可选增强
+
+integration 步详情完善、专家步子工具列表渲染、步骤详情复制/导出、与审计 trace 页互跳(a-timeline 参照 audit/trace:237)、900px 窄屏适配、可选 LLM 一句话结论(§5.7)、可选模型级 enable_thinking 配置列(ai_model_config 加列 + AgentAssembler:290 传覆盖,null 保持现状)。
+
+---
+
+## 12. 风险与缓解
+
+| # | 风险 | 缓解 |
+|---|---|---|
+| R1 | 模型不吐 reasoning(qwen 系默认可能关) | P1 验收用 deepseek-reasoner 类模型;**验证步骤**:jshell 查 `ai_model_config` 确认模型/供应商 → curl 直连 stream 观察是否有 Thinking 事件(或临时加 debug 日志);P3 可选 enable_thinking 列;**不全局强制开启**(LlmService:345 教训) |
+| R2 | 线程可见性(入口订阅线程 vs 专家 boundedElastic) | timeline synchronized + seq AtomicInteger;遵守「不引入 subscribeOn/publishOn」约束,钩子在既有回调线程同步调用 |
+| R3 | 思考流 PII 泄漏(逐片下发切断连续串) | 复用尾部缓冲 + alignCutToSafeBoundary(项目已验证方案);落库整段再 mask;BLOCK 整步 skipped |
+| R4 | SSE 体积/频率 | 专家输出用 text_delta speaker 镜像,不重复发 delta;step 事件每步 2~3 帧;大文本走 REST;总开关一键回退 |
+| R5 | 落库失败拖垮回答 | try/catch 只告警(memoryPipeline 同口径),回答事务不受影响 |
+| R6 | 双份数据重复渲染 | 有 steps 抑制 legacy 卡;toolCalls/routeRuns 审计链路不动 |
+| R7 | 框架签名差异 | 已核实 2.0.5 jar 含全部 Thinking 事件(含 sources);实施第一步 javap 复核 `ThinkingBlock*Event` 的 getReplyId/getBlockId/getDelta 签名 |
+
+---
+
+## 13. 测试与验证计划
+
+### 13.1 单元
+
+- `AiProcessTimeline`:结论生成/截断/upsert 键规则/abortRunning/summarize。
+- `processTypes.ts` reducer:start/delta/end、乱序、重复 end、恢复段 upsert、mirrorExpertDelta。
+
+### 13.2 SSE 注入与真实帧核对
+
+- dev 环境 devtools 覆写 openChatStream handlers 逐帧注入(thinking 多轮 / expert 镜像 / HITL 暂停-恢复 / aborted),验证前端状态机。
+- curl 直连 `GET /js/a/ai/chat/stream?sessionId&messageId`(带 x-token)核对真实帧序与 text_delta speaker 字段。
+
+### 13.3 浏览器实测(:3100 → 代理 :8980,admin/admin123)
+
+- [ ] 思考模型多轮工具问答:思考步流式 + 工具步 + 结论行 + done 折叠摘要
+- [ ] 专家路由问答:专家输出实时镜像 + 结论 + 原文展开 + 子工具列表
+- [ ] HITL 允许/记住/拒绝/过期:confirm 步 waiting→终态,交互卡原位
+- [ ] 流中停止:running 步 aborted,摘要正确
+- [ ] 重新生成(含写工具预检拒绝回滚):旧步骤清除/backup 恢复
+- [ ] 流中刷新 / 切会话:步骤精确回放(顺序/结论/详情含专家原文)
+- [ ] 双会话并发:互不串扰
+- [ ] 长思考(>8000 字):截断展示 + truncated 标记
+- [ ] **存量旧会话打开:仍为现有卡片渲染(无回填)**
+- [ ] 桌面 + 900px 窄屏:无溢出/遮挡/滚动条样式正确
+
+### 13.4 DB 核对(jshell + PG 驱动,192.168.0.106:5432/zsjz-ai,本机无 psql)
+
+```
+jshell --class-path D:/soft/repository/org/postgresql/postgresql/42.7.13/postgresql-42.7.13.jar script.jsh
+```
+
+- [ ] ai_message_step seq 连续性、(message_id,step_key) 唯一
+- [ ] 恢复段 upsert 无重复行(confirm waiting→终态同键)
+- [ ] detail_json 已脱敏(无明文手机号/身份证等)
+- [ ] deleteChatRound/regenerate 后无残留
+- [ ] 保留任务 cutoff 清理生效
+- [ ] **存量消息无步骤行(未回填)**
+
+### 13.5 回归
+
+- `processStepsEnabled=false`:全链路与改动前逐帧一致(仅多可选字段)。
+- 旧历史会话渲染不变;无人值守链路(emitter=null)只累积不下发,行为不变。
+
+---
+
+## 14. 附录
+
+### A. 对标产品体验对照
+
+| 维度 | DeepSeek | ChatGPT o 系列 | Manus | 本方案 |
+|---|---|---|---|---|
+| 思考展示 | 原始推理流式 | 摘要(LLM 生成) | 无独立思考块 | 原始推理流式(D2),可选 LLM 摘要(P3) |
+| 过程形态 | 单思考块 | 折叠活动行 | 步骤时间线/双栏 | 统一折叠面板 + 纵向时间线(D1) |
+| 每步结论 | 无 | 部分 | 有(结果摘要) | 有(确定性,≤80 字) |
+| 专家/子代理输出 | — | — | 实时可见 | 实时镜像 + 原文持久化(D4) |
+| 历史回放 | 思考可回看 | 可回看 | 可回看 | steps REST 精确回放(D3,存量不回填) |
+| 完成后 | 折叠"已深度思考 X 秒" | 折叠"Thought for Xs" | 任务完成态 | 折叠"已完成 N 步 · 用时 X 秒" |
+
+### B. 术语表
+
+| 术语 | 含义 |
+|---|---|
+| 入口智能体 | 数剑(ai_entry_agent),负责路由与自答 |
+| 专家 | ai_expert_agent,经 route_decision 咨询的领域智能体 |
+| 直答接管 | 专家正文直传为最终回答,入口正文经 answer_reset 丢弃 |
+| HITL | Human-in-the-loop,工具需人工确认(tool_confirm→confirm→resume) |
+| 步骤键 stepKey | 轮内唯一步骤标识,HITL 恢复段 upsert 依据 |
+| 镜像 | 专家 text_delta 同时追加进正文与专家步详情(零额外流式体积) |
+| 存量数据 | 开关启用前数据库中已有的会话/消息(不回填不迁移) |
+
+### C. 参考文件索引
+
+- 后端:`B/core/agent/{AiStreamEventBridge, AiPhaseSupport, AiSseSupport, AiStreamState, AiRouteContext, AiChatFacade, AiRouteOrchestrator, AiIntegrationDriver, AiExpertResumeDriver, AiTurnFinisher, AgentModelFactory, AgentAssembler}.java`、`B/domain/{AiMessage, AiToolCallLog, AiTrace, AiRouteRun, AiRouteExpertCall}.java`、`B/controller/AiChatController.java`、`B/service/impl/AiSessionServiceImpl.java`、`B/config/AiProperties.java`
+- 前端:`F/workbench/views/chat/index.vue`、`F/workbench/api/{chat.ts, chatSse.ts}`、`F/workbench/components/AiMarkdown.vue`、`F/workbench/styles/workbench.less`、`F/core/http/aiConstants.ts`、`F/workbench/views/audit/trace/index.vue`
+- 框架:`D:\soft\repository\io\agentscope\agentscope-core\2.0.5\`(含 sources)、`agentscope-extensions-model-openai\2.0.5\`(含 sources)
+- SQL 约定:`sql/ai_orchestration.sql:639-657`

BIN
gui-test-screenshots/drawer-fixed-header.png


BIN
gui-test-screenshots/drawer-state.png


BIN
gui-test-screenshots/memory-scope-names.png


+ 52 - 0
sql/ai_message_step.sql

@@ -0,0 +1,52 @@
+-- AI 助手消息执行步骤表(思考过程 + 分步结论,docs/design/chat-process-timeline-plan.md)
+-- 追加型明细,物理删除,不设 del_flag;仅承接开关启用后新产生的对话,存量历史会话不回填。
+-- 幂等:create table / index if not exists,可重复执行。
+
+create table if not exists ai_message_step (
+    id           bigint       not null,
+    session_id   bigint       not null,
+    message_id   bigint       not null,
+    seq          integer      not null,
+    step_key     varchar(128) not null,
+    kind         varchar(20)  not null,
+    speaker      varchar(10)  default 'entry',
+    expert_name  varchar(100),
+    agent_id     bigint,
+    title        varchar(200),
+    status       varchar(20)  not null,
+    conclusion   varchar(500),
+    detail_json  text,
+    duration_ms  bigint,
+    remark       varchar(500),
+    create_by    bigint,
+    create_time  timestamp,
+    update_by    bigint,
+    update_time  timestamp,
+    constraint pk_ai_message_step primary key (id)
+);
+
+-- HITL 恢复段按 (message_id, step_key) upsert:暂停段 waiting → 恢复段终态,seq 保留原值
+create unique index if not exists uk_ai_message_step_key on ai_message_step (message_id, step_key);
+-- 会话级回放:按消息分组、轮内序号排序
+create index if not exists idx_ai_message_step_session on ai_message_step (session_id, message_id, seq);
+
+comment on table ai_message_step is 'AI 助手消息执行步骤表(思考/路由/工具/专家/确认/整合,物理追加+按步键幂等更新,仅新数据写入)';
+comment on column ai_message_step.id is '主键(雪花)';
+comment on column ai_message_step.session_id is '所属会话(ai_session.id)';
+comment on column ai_message_step.message_id is '所属助手消息(ai_message.id)';
+comment on column ai_message_step.seq is '轮内步骤序号(恢复段续接 maxSeq+n)';
+comment on column ai_message_step.step_key is '步骤键(轮内唯一,HITL 恢复段 upsert 依据)';
+comment on column ai_message_step.kind is '步骤类型 thinking/route/tool/expert/confirm/integration';
+comment on column ai_message_step.speaker is '说话人 entry/expert';
+comment on column ai_message_step.expert_name is '专家名(speaker=expert 时)';
+comment on column ai_message_step.agent_id is '关联智能体主键(专家步/确认步)';
+comment on column ai_message_step.title is '步骤标题(后端拼好)';
+comment on column ai_message_step.status is '状态 running/success/error/skipped/waiting/approved/rejected/expired/aborted';
+comment on column ai_message_step.conclusion is '一行结论(≤80 字)';
+comment on column ai_message_step.detail_json is '详情 JSON(思考全文/工具入参出参/专家原文+子工具/路由理由/确认处置,已脱敏)';
+comment on column ai_message_step.duration_ms is '步骤耗时(毫秒)';
+comment on column ai_message_step.remark is '备注';
+comment on column ai_message_step.create_by is '创建者';
+comment on column ai_message_step.create_time is '创建时间';
+comment on column ai_message_step.update_by is '更新者';
+comment on column ai_message_step.update_time is '更新时间';

+ 4 - 0
sql/ai_model_enable_thinking.sql

@@ -0,0 +1,4 @@
+-- 模型级思考模式覆盖列(执行过程面板思考步的数据来源开关,null 保持现状)
+-- 幂等:add column if not exists,可重复执行。
+alter table ai_model_config add column if not exists enable_thinking boolean;
+comment on column ai_model_config.enable_thinking is '思考模式覆盖(仅对话模型):true 强制开启 / false 强制关闭 / null 跟随模型与供应商默认';

+ 371 - 0
test-reports-20261119-process-display/build-report.mjs

@@ -0,0 +1,371 @@
+import fs from 'node:fs';
+import path from 'node:path';
+
+const DIR = path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'));
+const SHOTS = path.join(DIR, 'shots');
+const b64 = (f) => 'data:image/png;base64,' + fs.readFileSync(path.join(SHOTS, f)).toString('base64');
+
+const shots = {
+  s1: b64('01-collapsed-summaries.png'),
+  s2: b64('02-expanded-thinking.png'),
+  s3: b64('03-expert-output.png'),
+  s4: b64('04-expert-raw-subtools.png'),
+  s5: b64('05-expert-detail.png'),
+  s6: b64('06-live-streaming.png'),
+  s7: b64('07-hitl-waiting.png'),
+  s8: b64('08-legacy-session.png'),
+  s9: b64('09-model-thinking-config.png'),
+};
+
+// ---- data ----
+const kindDist = [
+  { k: 'tool', label: '工具调用', n: 39, c: '#f59e0b', avg: 146 },
+  { k: 'thinking', label: '深度思考', n: 32, c: '#4d7cff', avg: 1805 },
+  { k: 'confirm', label: '人工确认', n: 5, c: '#16a34a', avg: 0 },
+  { k: 'expert', label: '专家咨询', n: 2, c: '#db2777', avg: 22524 },
+  { k: 'route', label: '路由决策', n: 2, c: '#06b6d4', avg: 0 },
+];
+const statusDist = [
+  { k: 'success', label: '成功', n: 70, c: '#16a34a' },
+  { k: 'error', label: '失败', n: 4, c: '#dc2626' },
+  { k: 'rejected', label: '已拒绝', n: 4, c: '#f59e0b' },
+  { k: 'approved', label: '已允许', n: 2, c: '#06b6d4' },
+];
+const perMsg = [
+  { rn: 1, name: '知识库检索', steps: 14, ms: 15366, st: 0 },
+  { rn: 2, name: '专家文件清单', steps: 7, ms: 22447, st: 0 },
+  { rn: 3, name: '写文件·允许', steps: 4, ms: 7067, st: 0 },
+  { rn: 4, name: '报告·多次暂停', steps: 11, ms: 45075, st: 0 },
+  { rn: 5, name: '流水·拒绝', steps: 4, ms: 9726, st: 0 },
+  { rn: 6, name: '全量·中止', steps: 13, ms: 16055, st: 3 },
+  { rn: 7, name: '车辆登记检索', steps: 6, ms: 8057, st: 0 },
+  { rn: 8, name: '逐文件读取', steps: 19, ms: 62395, st: 0 },
+  { rn: 9, name: '写报告·断连', steps: 2, ms: 31412, st: 3 },
+];
+const tests = [
+  ['T01', '模型思考流式渲染', 'P1', 'pass', 's6', 'ThinkingBlock 事件桥接,推理文本逐片流入思考步,多轮 ReAct 各成一步'],
+  ['T02', '工具步 + 一行结论', 'P1', 'pass', 's2', '工具步带状态/耗时/首行结论,入参出参可展开'],
+  ['T03', '路由步 + 判定理由', 'P1', 'pass', 's3', '路由步结论含决策理由,详情展示动作/置信度/任务片段'],
+  ['T04', '专家输出镜像 + 原文 + 子工具', 'P1', 'pass', 's5', '专家回答实时镜像;完成后原文留证 + 子工具仅名称/状态/耗时'],
+  ['T05', '完成后折叠摘要', 'P1', 'pass', 's1', '自动折叠为「已深度思考 X · 已完成 N 步 · 用时 Y」'],
+  ['T06', '展开步骤详情', 'P1', 'pass', 's2', '思考全文 markdown + 光标 + 耗时脚注 + 复制'],
+  ['T07', '刷新 / 切会话精确回放', 'P2', 'pass', 's1', 'steps REST 还原顺序/结论/详情,与流式一致'],
+  ['T08', 'HITL 暂停等待态', 'P1', 'pass', 's7', '等待摘要 + 进行中工具步 + 等待确认步 + 原位确认卡'],
+  ['T09', 'HITL 允许 → 续接 upsert', 'P2', 'pass', 's7', 'confirm 步 waiting→approved,同键 upsert 无重复行'],
+  ['T10', 'HITL 拒绝 → 专家适配', 'P2', 'pass', 's4', 'confirm→rejected 带原因,专家收 DENIED 后切换工具'],
+  ['T11', '多次暂停 upsert 无重复', 'P2', 'pass', 's4', '11 步 / 11 键,跨两段暂停-恢复 seq 保留'],
+  ['T12', '流中停止 → aborted', 'P1', 'pass', 's1', 'message status=3,步骤保留,摘要「已中止」'],
+  ['T13', '重新生成替换旧回答', 'P1', 'pass', 's1', '旧回答替换无重复,步骤备份/恢复路径正常'],
+  ['T14', '存量旧会话不回填', 'P2', 'pass', 's8', '旧会话 0 面板 + legacy 工具卡,无 backfill'],
+  ['T15', '零步骤自答降级', 'P1', 'pass', 's1', '纯自答无步骤 → 不渲染面板,与现状一致'],
+  ['T16', '模型思考模式配置', 'P3', 'pass', 's9', '思考模式 select 渲染;保存→DB true→还原 null'],
+  ['T17', '控制台零报错', 'QA', 'pass', null, '修复 prop 告警后 console error=0'],
+  ['T18', '改动文件类型检查零错误', 'QA', 'pass', null, 'vue-tsc 改动文件 0 错误(其余为存量无关错误)'],
+  ['T19', '后端编译 + 健康检查', 'QA', 'pass', null, 'mvn BUILD SUCCESS;/sys/health 200'],
+  ['T20', '窄屏适配', 'P3', 'pass', null, '900px 媒体查询就位(代码审查验证)'],
+];
+const bugs = [
+  ['B1', '耗时显示天文数字', '后端 Jackson 将 Long 序列化为字符串,前端 += 变字符串拼接,摘要出现「10403409143223.1 s」', 'processTypes 增加 toNum 归一,formatDuration/ThinkingDetail 同步处理', '#dc2626'],
+  ['B2', '展开态在 id 归位后丢失', 'done/tool_confirm 将占位 id 换为真实 messageId,展开键失配导致面板意外折叠', '新增 rekeyProcess,在 id 替换时迁移展开键', '#f59e0b'],
+  ['B3', '暂停期摘要误显示「已完成」', 'HITL 暂停时 streaming=false,摘要走完成分支', '摘要等待态感知:「等待你确认 · 共 N 步」+ 时钟图标', '#f59e0b'],
+  ['B4', '专家思考步标题专家名重复', '标题已含「专家「X」思考」,又追加 speaker 后缀', '移除冗余 speaker 后缀', '#06b6d4'],
+  ['B5', 'ProcessPanel prop 类型告警', 'durationMs 声明 Number 但收到 Long→String 字符串', 'prop 放宽为 number|string', '#06b6d4'],
+];
+
+// ---- svg helpers ----
+const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+function donut(data, size = 220, thick = 30) {
+  const total = data.reduce((a, d) => a + d.n, 0);
+  const r = (size - thick) / 2, cx = size / 2, cy = size / 2, C = 2 * Math.PI * r;
+  let off = 0, segs = '';
+  for (const d of data) {
+    const frac = d.n / total, len = frac * C;
+    segs += `<circle cx="${cx}" cy="${cy}" r="${r}" fill="none" stroke="${d.c}" stroke-width="${thick}" stroke-dasharray="${len.toFixed(2)} ${(C - len).toFixed(2)}" stroke-dashoffset="${(-off).toFixed(2)}" transform="rotate(-90 ${cx} ${cy})" stroke-linecap="butt"><title>${d.label} ${d.n}</title></circle>`;
+    off += len;
+  }
+  return `<svg viewBox="0 0 ${size} ${size}" class="donut">${segs}<text x="${cx}" y="${cy - 6}" text-anchor="middle" class="donut-num">${total}</text><text x="${cx}" y="${cy + 18}" text-anchor="middle" class="donut-cap">步骤总数</text></svg>`;
+}
+function legend(data) {
+  return `<div class="legend">${data.map(d => `<span class="lg"><i style="background:${d.c}"></i>${d.label}<b>${d.n}</b></span>`).join('')}</div>`;
+}
+function msgBars(data) {
+  const W = 560, H = 240, pad = 34, bw = (W - pad * 2) / data.length;
+  const max = Math.max(...data.map(d => d.steps));
+  let bars = '', grid = '';
+  for (let g = 0; g <= 4; g++) {
+    const y = H - pad - (g / 4) * (H - pad * 2);
+    grid += `<line x1="${pad}" y1="${y}" x2="${W - pad}" y2="${y}" class="grid"/><text x="${pad - 6}" y="${y + 4}" text-anchor="end" class="axis">${Math.round(max * g / 4)}</text>`;
+  }
+  data.forEach((d, i) => {
+    const h = (d.steps / max) * (H - pad * 2);
+    const x = pad + i * bw + bw * 0.18, w = bw * 0.64, y = H - pad - h;
+    const col = d.st === 3 ? '#f59e0b' : 'url(#gbar)';
+    bars += `<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${w.toFixed(1)}" height="${h.toFixed(1)}" rx="4" fill="${col}"><title>${d.name} ${d.steps} 步</title></rect>`;
+    bars += `<text x="${(x + w / 2).toFixed(1)}" y="${(y - 6).toFixed(1)}" text-anchor="middle" class="barval">${d.steps}</text>`;
+    bars += `<text x="${(x + w / 2).toFixed(1)}" y="${H - pad + 16}" text-anchor="middle" class="axis">${d.rn}</text>`;
+  });
+  return `<svg viewBox="0 0 ${W} ${H}" class="bars"><defs><linearGradient id="gbar" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#4d7cff"/><stop offset="1" stop-color="#2a50ec"/></linearGradient></defs>${grid}${bars}</svg>`;
+}
+function hbars(data, valKey, fmt) {
+  const max = Math.max(...data.map(d => d[valKey]));
+  return `<div class="hbars">${data.map(d => {
+    const w = max ? (d[valKey] / max) * 100 : 0;
+    return `<div class="hrow"><span class="hlab"><i style="background:${d.c}"></i>${d.label}</span><span class="htrack"><span class="hfill" style="width:${w.toFixed(1)}%;background:${d.c}"></span></span><span class="hval">${fmt(d[valKey])}</span></div>`;
+  }).join('')}</div>`;
+}
+const fmtMs = (v) => v >= 1000 ? (v / 1000).toFixed(1) + ' s' : v + ' ms';
+
+const passCount = tests.filter(t => t[3] === 'pass').length;
+const phaseCount = (p) => tests.filter(t => t[2] === p).length;
+
+// ---- html ----
+const html = `<!doctype html>
+<html lang="zh-CN">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<title>数剑 · 执行过程展示 — 自动化测试报告</title>
+<style>
+:root{
+  --bg:#070b16;--bg2:#0b1220;--surface:#101a2e;--surface2:#16233c;--border:#1e2d4a;
+  --text:#e6edf7;--text2:#93a4c3;--muted:#5d6f92;
+  --blue:#2a50ec;--blue-b:#4d7cff;--cyan:#06b6d4;--amber:#f59e0b;--magenta:#db2777;--green:#16a34a;--red:#dc2626;--violet:#7c3aed;
+  --radius:14px;
+}
+*{box-sizing:border-box;margin:0;padding:0}
+html{scroll-behavior:smooth;scroll-padding-top:76px}
+body{
+  background:var(--bg);color:var(--text);
+  font:15px/1.65 "Segoe UI",system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;
+  -webkit-font-smoothing:antialiased;overflow-x:hidden;
+}
+body::before{content:"";position:fixed;inset:0;pointer-events:none;z-index:0;
+  background:
+    radial-gradient(900px 500px at 12% -8%,rgba(42,80,236,.20),transparent 60%),
+    radial-gradient(800px 480px at 92% 4%,rgba(6,182,212,.13),transparent 60%),
+    radial-gradient(700px 600px at 50% 108%,rgba(219,39,119,.10),transparent 60%);
+}
+body::after{content:"";position:fixed;inset:0;pointer-events:none;z-index:0;opacity:.05;
+  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='140' height='140'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2'/%3E%3C/filter%3E%3Crect width='140' height='140' filter='url(%23n)' opacity='.6'/%3E%3C/svg%3E");}
+::selection{background:rgba(77,124,255,.35)}
+/* custom scrollbars */
+*{scrollbar-width:thin;scrollbar-color:#24365c transparent}
+::-webkit-scrollbar{width:10px;height:10px}
+::-webkit-scrollbar-track{background:var(--bg2)}
+::-webkit-scrollbar-thumb{background:#24365c;border-radius:6px;border:2px solid var(--bg2)}
+::-webkit-scrollbar-thumb:hover{background:#33508f}
+.wrap{position:relative;z-index:1;max-width:1180px;margin:0 auto;padding:0 26px}
+/* nav */
+nav{position:sticky;top:0;z-index:50;backdrop-filter:blur(14px);background:rgba(7,11,22,.82);border-bottom:1px solid var(--border)}
+.nav-in{max-width:1180px;margin:0 auto;padding:14px 26px;display:flex;align-items:center;gap:20px}
+.brand{display:flex;align-items:center;gap:10px;font-weight:700;letter-spacing:.3px}
+.brand .logo{width:30px;height:30px;border-radius:9px;background:linear-gradient(135deg,var(--blue),var(--cyan));display:grid;place-items:center;box-shadow:0 0 18px rgba(42,80,236,.5)}
+.brand .logo svg{width:17px;height:17px}
+.nav-links{display:flex;gap:4px;margin-left:auto;flex-wrap:wrap}
+.nav-links a{color:var(--text2);text-decoration:none;font-size:13px;padding:6px 11px;border-radius:8px;transition:.18s}
+.nav-links a:hover{color:var(--text);background:var(--surface2)}
+.verdict{font-size:12px;font-weight:700;color:#04140a;background:linear-gradient(135deg,#22c55e,#16a34a);padding:5px 12px;border-radius:999px;box-shadow:0 0 16px rgba(22,163,74,.45)}
+/* hero */
+header{padding:64px 0 30px}
+.kicker{display:inline-flex;align-items:center;gap:8px;font-size:12px;letter-spacing:2.5px;color:var(--cyan);text-transform:uppercase;font-weight:700}
+.kicker::before{content:"";width:26px;height:2px;background:var(--cyan)}
+h1{font-size:clamp(30px,4.6vw,50px);line-height:1.12;font-weight:800;letter-spacing:-.5px;margin:14px 0 12px}
+h1 .grad{background:linear-gradient(100deg,var(--blue-b),var(--cyan) 55%,var(--magenta));-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}
+.sub{color:var(--text2);max-width:760px;font-size:15.5px}
+.meta{display:flex;gap:10px;flex-wrap:wrap;margin-top:20px}
+.chip{font-size:12.5px;color:var(--text2);background:var(--surface);border:1px solid var(--border);padding:6px 13px;border-radius:999px}
+.chip b{color:var(--text)}
+/* stats */
+.stats{display:grid;grid-template-columns:repeat(6,1fr);gap:14px;margin:34px 0 8px}
+.stat{background:linear-gradient(160deg,var(--surface),var(--bg2));border:1px solid var(--border);border-radius:var(--radius);padding:18px 16px;position:relative;overflow:hidden;transition:.22s}
+.stat:hover{transform:translateY(-3px);border-color:#2c4070;box-shadow:0 12px 30px rgba(0,0,0,.4)}
+.stat::after{content:"";position:absolute;left:0;top:0;bottom:0;width:3px;background:var(--sc,var(--blue))}
+.stat .n{font-size:30px;font-weight:800;font-variant-numeric:tabular-nums;letter-spacing:-.5px}
+.stat .l{font-size:12px;color:var(--text2);margin-top:2px}
+/* sections */
+section{padding:44px 0 6px}
+.sec-h{display:flex;align-items:baseline;gap:14px;margin-bottom:20px}
+.sec-h .idx{font-size:13px;font-weight:800;color:var(--blue-b);font-variant-numeric:tabular-nums}
+h2{font-size:23px;font-weight:800;letter-spacing:-.3px}
+.sec-h .rule{flex:1;height:1px;background:linear-gradient(90deg,var(--border),transparent)}
+.card{background:linear-gradient(165deg,var(--surface),var(--bg2));border:1px solid var(--border);border-radius:var(--radius);padding:22px}
+.grid2{display:grid;grid-template-columns:1fr 1fr;gap:16px}
+.grid3{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
+.card h3{font-size:15px;font-weight:700;margin-bottom:4px}
+.card .desc{font-size:12.5px;color:var(--muted);margin-bottom:16px}
+/* charts */
+.donut{width:200px;height:200px;display:block;margin:0 auto}
+.donut-num{fill:var(--text);font-size:38px;font-weight:800}
+.donut-cap{fill:var(--muted);font-size:12px}
+.legend{display:flex;flex-wrap:wrap;gap:8px 16px;justify-content:center;margin-top:16px}
+.lg{display:inline-flex;align-items:center;gap:7px;font-size:12.5px;color:var(--text2)}
+.lg i{width:10px;height:10px;border-radius:3px}
+.lg b{color:var(--text);font-variant-numeric:tabular-nums}
+.bars{width:100%;height:auto}
+.grid{stroke:#1a2740;stroke-width:1}
+.axis{fill:var(--muted);font-size:10.5px}
+.barval{fill:var(--text2);font-size:11px;font-weight:700}
+.hbars{display:flex;flex-direction:column;gap:13px}
+.hrow{display:grid;grid-template-columns:96px 1fr 70px;align-items:center;gap:12px}
+.hlab{display:flex;align-items:center;gap:8px;font-size:12.5px;color:var(--text2)}
+.hlab i{width:9px;height:9px;border-radius:3px;flex:none}
+.htrack{height:12px;background:var(--bg2);border-radius:6px;overflow:hidden;border:1px solid var(--border)}
+.hfill{display:block;height:100%;border-radius:6px;transition:width .8s cubic-bezier(.2,.8,.2,1)}
+.hval{font-size:12.5px;color:var(--text);text-align:right;font-variant-numeric:tabular-nums}
+/* table */
+table{width:100%;border-collapse:collapse;font-size:13.5px}
+th{text-align:left;color:var(--muted);font-size:11.5px;letter-spacing:1px;text-transform:uppercase;font-weight:700;padding:10px 12px;border-bottom:1px solid var(--border)}
+td{padding:11px 12px;border-bottom:1px solid #14203a;vertical-align:top;color:var(--text2)}
+tr:hover td{background:rgba(77,124,255,.05)}
+td.tid{font-weight:800;color:var(--blue-b);font-variant-numeric:tabular-nums;white-space:nowrap}
+td .tname{color:var(--text);font-weight:600}
+.badge{display:inline-block;font-size:11px;font-weight:700;padding:3px 10px;border-radius:999px}
+.badge.pass{color:#052e16;background:#22c55e}
+.badge.p1{color:#dbeafe;background:rgba(77,124,255,.2);border:1px solid rgba(77,124,255,.4)}
+.badge.p2{color:#cffafe;background:rgba(6,182,212,.16);border:1px solid rgba(6,182,212,.4)}
+.badge.p3{color:#fce7f3;background:rgba(219,39,119,.16);border:1px solid rgba(219,39,119,.4)}
+.badge.qa{color:#e9d5ff;background:rgba(124,58,237,.18);border:1px solid rgba(124,58,237,.4)}
+.shotref{font-size:11px;color:var(--cyan);font-variant-numeric:tabular-nums}
+/* gallery */
+.gal{display:grid;grid-template-columns:1fr 1fr;gap:16px}
+.shot{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;transition:.22s}
+.shot:hover{border-color:#2c4070;box-shadow:0 14px 34px rgba(0,0,0,.45);transform:translateY(-3px)}
+.shot img{width:100%;display:block;border-bottom:1px solid var(--border);background:#fff}
+.shot .cap{padding:13px 16px}
+.shot .cap b{display:block;font-size:13.5px;color:var(--text)}
+.shot .cap span{font-size:12px;color:var(--muted)}
+.shot .tag{float:right;font-size:10.5px;color:var(--cyan);border:1px solid rgba(6,182,212,.4);padding:2px 8px;border-radius:999px}
+/* bugs */
+.bug{border-left:3px solid var(--bc);background:var(--surface);border-radius:0 var(--radius) var(--radius) 0;padding:16px 18px;margin-bottom:12px}
+.bug .bh{display:flex;align-items:center;gap:10px;margin-bottom:6px}
+.bug .bid{font-weight:800;color:var(--bc);font-size:13px}
+.bug .bt{font-weight:700;font-size:14.5px}
+.bug .fixed{margin-left:auto;font-size:11px;color:#052e16;background:#22c55e;padding:2px 10px;border-radius:999px;font-weight:700}
+.bug p{font-size:13px;color:var(--text2)}
+.bug .fix{color:var(--green);margin-top:4px}
+/* pipeline */
+.pipe{width:100%;height:auto}
+.pipe .node{fill:var(--surface2);stroke:#2c4070;stroke-width:1.2;rx:10}
+.pipe .nt{fill:var(--text);font-size:12.5px;font-weight:700}
+.pipe .ns{fill:var(--muted);font-size:10.5px}
+.pipe .edge{stroke:#33508f;stroke-width:1.6;fill:none;marker-end:url(#arr)}
+.pipe .elab{fill:var(--cyan);font-size:10px}
+/* reveal */
+.rv{opacity:0;transform:translateY(22px);transition:opacity .6s ease,transform .6s cubic-bezier(.2,.8,.2,1)}
+.rv.on{opacity:1;transform:none}
+footer{margin:60px 0 40px;padding-top:24px;border-top:1px solid var(--border);color:var(--muted);font-size:12.5px;display:flex;justify-content:space-between;gap:14px;flex-wrap:wrap}
+@media(max-width:900px){
+  .stats{grid-template-columns:repeat(3,1fr)}
+  .grid2,.grid3,.gal{grid-template-columns:1fr}
+  .nav-links{display:none}
+  .hrow{grid-template-columns:80px 1fr 60px}
+}
+@media(max-width:560px){.stats{grid-template-columns:repeat(2,1fr)}.wrap{padding:0 16px}}
+</style>
+</head>
+<body>
+<nav><div class="nav-in">
+  <span class="brand"><span class="logo"><svg viewBox="0 0 24 24" fill="none"><path d="M12 2l2.4 6.6L21 11l-6.6 2.4L12 20l-2.4-6.6L3 11l6.6-2.4z" fill="#fff"/></svg></span>数剑 · 过程观测</span>
+  <div class="nav-links">
+    <a href="#overview">概览</a><a href="#charts">图表</a><a href="#matrix">用例</a><a href="#evidence">截图</a><a href="#bugs">缺陷修复</a><a href="#pipeline">链路</a>
+  </div>
+  <span class="verdict">全部通过 ${passCount}/${tests.length}</span>
+</div></nav>
+
+<div class="wrap">
+<header id="overview">
+  <span class="kicker">Automated Browser Test Report</span>
+  <h1>AI 聊天「思考过程 + 分步结论」<br><span class="grad">自动化测试报告</span></h1>
+  <p class="sub">对标 DeepSeek / ChatGPT / Manus 的执行过程展示功能,经内置浏览器自动化逐流程实测:思考流式、工具/路由/专家步骤与结论、HITL 暂停-恢复、中止、重新生成、历史精确回放与存量降级。本报告汇总实测数据、图表与截图证据。</p>
+  <div class="meta">
+    <span class="chip">日期 <b>2026-11-19</b></span>
+    <span class="chip">环境 <b>dev · :3100 → :8980</b></span>
+    <span class="chip">模型 <b>deepseek-v4.1-flash</b></span>
+    <span class="chip">依据 <b>docs/design/chat-process-timeline-plan.md</b></span>
+  </div>
+  <div class="stats">
+    <div class="stat" style="--sc:var(--green)"><div class="n">${passCount}/${tests.length}</div><div class="l">用例通过</div></div>
+    <div class="stat" style="--sc:var(--blue-b)"><div class="n">80</div><div class="l">落库步骤</div></div>
+    <div class="stat" style="--sc:var(--cyan)"><div class="n">9</div><div class="l">覆盖消息轮</div></div>
+    <div class="stat" style="--sc:var(--magenta)"><div class="n">5</div><div class="l">缺陷发现并修复</div></div>
+    <div class="stat" style="--sc:var(--amber)"><div class="n">1.8s</div><div class="l">平均思考耗时</div></div>
+    <div class="stat" style="--sc:var(--violet)"><div class="n">0</div><div class="l">控制台报错</div></div>
+  </div>
+</header>
+
+<section id="charts">
+  <div class="sec-h"><span class="idx">01</span><h2>数据图表</h2><span class="rule"></span></div>
+  <div class="grid2">
+    <div class="card rv"><h3>步骤终态分布</h3><div class="desc">ai_message_step 全量 80 步按终态统计</div>${donut(statusDist)}${legend(statusDist)}</div>
+    <div class="card rv"><h3>各轮步骤数</h3><div class="desc">9 个助手消息轮的过程步骤数(橙色 = 中止轮)</div>${msgBars(perMsg)}${legend([{label:'正常完成',c:'#4d7cff',n:7},{label:'中止',c:'#f59e0b',n:2}])}</div>
+    <div class="card rv"><h3>步骤类型分布</h3><div class="desc">按 kind 统计步骤数量</div>${hbars(kindDist,'n',v=>v+' 步')}</div>
+    <div class="card rv"><h3>各类型平均耗时</h3><div class="desc">专家咨询含同步等待,耗时显著高于工具</div>${hbars(kindDist,'avg',fmtMs)}</div>
+  </div>
+</section>
+
+<section id="matrix">
+  <div class="sec-h"><span class="idx">02</span><h2>测试用例矩阵</h2><span class="rule"></span></div>
+  <div class="card rv" style="padding:8px 12px">
+    <table>
+      <thead><tr><th>编号</th><th>用例</th><th>阶段</th><th>结果</th><th>证据</th><th>说明</th></tr></thead>
+      <tbody>
+      ${tests.map(t=>`<tr><td class="tid">${t[0]}</td><td><span class="tname">${esc(t[1])}</span></td><td><span class="badge ${t[2].toLowerCase()}">${t[2]}</span></td><td><span class="badge pass">通过</span></td><td>${t[4]?`<span class="shotref">${t[4].toUpperCase()}</span>`:'—'}</td><td>${esc(t[5])}</td></tr>`).join('')}
+      </tbody>
+    </table>
+  </div>
+</section>
+
+<section id="evidence">
+  <div class="sec-h"><span class="idx">03</span><h2>截图证据</h2><span class="rule"></span></div>
+  <div class="gal">
+    <div class="shot rv"><img src="${shots.s1}" alt="折叠摘要"><div class="cap"><span class="tag">S1</span><b>折叠摘要 + 中止态</b><span>完成后自动折叠为「已深度思考 X · 已完成 N 步 · 用时 Y」;中止轮显示「已中止」</span></div></div>
+    <div class="shot rv"><img src="${shots.s2}" alt="展开思考"><div class="cap"><span class="tag">S2</span><b>展开思考步详情</b><span>推理全文 markdown 流式渲染 + 「思考了 1 秒」脚注 + 复制详情</span></div></div>
+    <div class="shot rv"><img src="${shots.s3}" alt="路由详情"><div class="cap"><span class="tag">S3</span><b>路由步判定详情</b><span>动作 / 置信度 0.8 / 判定理由 / 任务片段</span></div></div>
+    <div class="shot rv"><img src="${shots.s5}" alt="专家原文+子工具"><div class="cap"><span class="tag">S5</span><b>专家原文 + 子工具</b><span>原文留证可展开;子工具仅名称/状态/耗时(零入参出参泄漏)</span></div></div>
+    <div class="shot rv"><img src="${shots.s6}" alt="实时流式"><div class="cap"><span class="tag">S6</span><b>实时流式执行</b><span>思考步 + 工具步累积,phase 播报「数剑正在调用…」+ 停止按钮</span></div></div>
+    <div class="shot rv"><img src="${shots.s7}" alt="HITL等待"><div class="cap"><span class="tag">S7</span><b>HITL 暂停等待态</b><span>「等待你确认」摘要 + 进行中工具步 + 等待确认步 + 原位确认卡</span></div></div>
+    <div class="shot rv"><img src="${shots.s8}" alt="legacy会话"><div class="cap"><span class="tag">S8</span><b>存量旧会话降级</b><span>旧会话无步骤行 → 0 面板 + legacy 工具卡(不回填)</span></div></div>
+    <div class="shot rv"><img src="${shots.s9}" alt="模型思考配置"><div class="cap"><span class="tag">S9</span><b>模型思考模式配置</b><span>「思考模式」select + 说明文案;保存链路 DB 验证 true→null</span></div></div>
+  </div>
+</section>
+
+<section id="bugs">
+  <div class="sec-h"><span class="idx">04</span><h2>缺陷发现与修复</h2><span class="rule"></span></div>
+  ${bugs.map(b=>`<div class="bug rv" style="--bc:${b[4]}"><div class="bh"><span class="bid">${b[0]}</span><span class="bt">${esc(b[1])}</span><span class="fixed">已修复</span></div><p>${esc(b[2])}</p><p class="fix">✓ ${esc(b[3])}</p></div>`).join('')}
+</section>
+
+<section id="pipeline">
+  <div class="sec-h"><span class="idx">05</span><h2>数据链路</h2><span class="rule"></span></div>
+  <div class="card rv">
+    <svg viewBox="0 0 900 250" class="pipe">
+      <defs><marker id="arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0L10 5L0 10z" fill="#33508f"/></marker></defs>
+      <rect class="node" x="10" y="30" width="150" height="56" rx="10"/><text class="nt" x="85" y="54" text-anchor="middle">模型 API</text><text class="ns" x="85" y="72" text-anchor="middle">reasoning_content</text>
+      <rect class="node" x="200" y="30" width="160" height="56" rx="10"/><text class="nt" x="280" y="54" text-anchor="middle">AgentScope 2.0.5</text><text class="ns" x="280" y="72" text-anchor="middle">ThinkingBlock* 事件</text>
+      <rect class="node" x="400" y="30" width="160" height="56" rx="10"/><text class="nt" x="480" y="54" text-anchor="middle">AiStreamEventBridge</text><text class="ns" x="480" y="72" text-anchor="middle">+ thinking/tool 钩子</text>
+      <rect class="node" x="600" y="30" width="150" height="56" rx="10"/><text class="nt" x="675" y="54" text-anchor="middle">AiProcessTimeline</text><text class="ns" x="675" y="72" text-anchor="middle">步骤 + 结论</text>
+      <rect class="node" x="790" y="30" width="100" height="56" rx="10"/><text class="nt" x="840" y="54" text-anchor="middle">SSE</text><text class="ns" x="840" y="72" text-anchor="middle">step_*</text>
+      <path class="edge" d="M160 58H200"/><path class="edge" d="M360 58H400"/><path class="edge" d="M560 58H600"/><path class="edge" d="M750 58H790"/>
+      <rect class="node" x="600" y="150" width="150" height="56" rx="10"/><text class="nt" x="675" y="174" text-anchor="middle">ai_message_step</text><text class="ns" x="675" y="192" text-anchor="middle">upsert 落库</text>
+      <rect class="node" x="400" y="150" width="160" height="56" rx="10"/><text class="nt" x="480" y="174" text-anchor="middle">GET /steps</text><text class="ns" x="480" y="192" text-anchor="middle">历史精确回放</text>
+      <rect class="node" x="180" y="150" width="180" height="56" rx="10"/><text class="nt" x="270" y="174" text-anchor="middle">ProcessPanel</text><text class="ns" x="270" y="192" text-anchor="middle">折叠面板 + 时间线</text>
+      <path class="edge" d="M675 86V150"/><text class="elab" x="682" y="122">收尾/暂停</text>
+      <path class="edge" d="M600 178H560"/><path class="edge" d="M400 178H360"/>
+      <path class="edge" d="M840 86V120H270V150"/><text class="elab" x="500" y="114">实时 step_start / delta / end</text>
+    </svg>
+  </div>
+</section>
+
+<footer>
+  <span>数剑智能研判系统 · 执行过程展示功能测试报告</span>
+  <span>生成于 2026-11-19 · 内置浏览器自动化实测 · 单文件自包含</span>
+</footer>
+</div>
+<script>
+const io=new IntersectionObserver(es=>es.forEach(e=>{if(e.isIntersecting){e.target.classList.add('on');io.unobserve(e.target)}}),{threshold:.12});
+document.querySelectorAll('.rv').forEach(el=>io.observe(el));
+</script>
+</body>
+</html>`;
+
+fs.writeFileSync(path.join(DIR, 'report.html'), html);
+console.log('report.html written:', (html.length / 1024 / 1024).toFixed(2), 'MB');

File diff suppressed because it is too large
+ 178 - 0
test-reports-20261119-process-display/report.html


BIN
test-reports-20261119-process-display/shots/01-collapsed-summaries.png


BIN
test-reports-20261119-process-display/shots/02-expanded-thinking.png


BIN
test-reports-20261119-process-display/shots/03-expert-output.png


BIN
test-reports-20261119-process-display/shots/04-expert-raw-subtools.png


BIN
test-reports-20261119-process-display/shots/05-expert-detail.png


BIN
test-reports-20261119-process-display/shots/06-live-streaming.png


BIN
test-reports-20261119-process-display/shots/07-hitl-waiting.png


BIN
test-reports-20261119-process-display/shots/08-legacy-session.png


BIN
test-reports-20261119-process-display/shots/09-model-thinking-config.png


BIN
test-reports-20261119-process-display/shots/10-agent-chat-chart.png


BIN
test-reports-20261119-process-display/shots/11-agent-html-artifact.png


BIN
test-reports-20261119-process-display/shots/modal-01-fullscreen-filled.png


BIN
test-reports-20261119-process-display/shots/modal-02-html-fullscreen.png


BIN
test-reports-20261119-process-display/shots/plan-00-state.png


BIN
test-reports-20261119-process-display/shots/plan-01-before-rawjson.png


BIN
test-reports-20261119-process-display/shots/plan-02-after-card.png


BIN
test-reports-20261119-process-display/shots/plan-03-md-rendered.png


BIN
test-reports-20261119-process-display/shots/plan-04-plandoc-rendered.png


BIN
test-reports-20261119-process-display/shots/report-charts.png


BIN
test-reports-20261119-process-display/shots/report-gallery.png


BIN
test-reports-20261119-process-display/shots/report-hero.png


BIN
test-reports-20261119-process-display/shots/report-pipeline.png


Some files were not shown because too many files changed in this diff