Browse Source

feat(agent): 完善关系图交互与代码块高亮

- 关系图:点击节点高亮一跳邻居、点击关系线高亮两端;节点样式复用既有 ai-graph-node;全屏画布按容器重算尺寸

- 代码块:改用 streamdown-vue/Shiki 渲染 Python/SQL/JSON/HTML 等,HTML 源码视图同步高亮

- Python:移除代码内容黑名单;execute_python 结果去掉 hint/durationMs;关系边 relation 缺失时回退 label/关联

- 提示词:代码使用带语言围栏;压缩 execute_python 描述
cc 2 weeks ago
parent
commit
adcb38f623

+ 4 - 2
AI_AGENT.md

@@ -310,8 +310,10 @@ emit_relation_graph(nodes=[...], edges=[...], title="人物社交关系")
   `RelationGraphPayload`(`module/agent/render`)做结构校验/去重/裁剪(500 节点 / 300 边 / 60k 字符),
   `PythonAnalysisTool` 以 `relationGraph` 字段返回;前端按工具步骤自动渲染。
 - 边界:`get_case_graph` 只覆盖预置 `rel_edge` 的案件对象关系;其他表不要硬套,统一走本契约。
-- 为什么不让模型自己写文件:`PythonExecutor#validateCode` 禁止用户代码出现 `open(` / `pathlib`;
-  `zgraph.py` 由后端注入,只做序列化,分析逻辑仍全部在模型写的 Python 里。
+- Python 代码可以直接用 `open` / `pathlib` 读写沙箱当前目录(关系图 HTML、CSV 报告等);
+  生成的文件由 `collectGeneratedFiles` 自动收进产物栏。`zgraph.py` 只是关系图的便捷序列化入口。
+- Python 代码不做内容拦截,拥有完整文件/进程/网络权限;只保留空代码校验、执行超时和输出截断。
+  生产环境必须用容器/受限 OS 用户隔离,或只挂载当前案件目录。
 
 **关键实现约束**:因为表格是裸 JSON 而非围栏,`utils/scanner.ts` 必须做**字符级花括号配平扫描**
 (字符串/转义感知)并按载荷形态校验,不能只按围栏切分。流式期间的增量策略是

+ 83 - 78
ai-electron/frontend/src/ai/components/blocks/CodeBlock.vue

@@ -1,21 +1,19 @@
 <template>
-  <div class="ai-code">
-    <div class="ai-code__head">
-      <span class="ai-code__lang">{{ lang || 'text' }}</span>
-      <span class="ai-code__spacer"></span>
-      <span v-if="pending" class="ai-code__pending">输出中…</span>
-      <button class="ai-code__btn" type="button" @click="copy">
-        {{ copied ? '已复制' : '复制' }}
-      </button>
-    </div>
-    <pre class="ai-code__pre ai-scroll-area"><code>{{ text }}</code></pre>
+  <div class="ai-code" :class="{ 'is-pending': pending }">
+    <StreamMarkdown :content="markdown" />
   </div>
 </template>
 
 <script lang="ts" setup>
-  /** 普通代码块(SQL / JSON / Python 等):保留原文,提供复制 */
-  import { ref } from 'vue';
-  import { useClipboard } from '@vueuse/core';
+  /**
+   * 代码块
+   *
+   * 直接复用 streamdown-vue 的 Markdown 代码块渲染:Shiki 语法高亮、语言标签、复制按钮,
+   * 与正文 markdown 里的代码块保持同一套排版。外层只控制间距、最大高度和流式态边框。
+   */
+  import { computed } from 'vue';
+  import { StreamMarkdown } from 'streamdown-vue';
+  import 'streamdown-vue/style.css';
 
   const props = withDefaults(
     defineProps<{
@@ -26,85 +24,92 @@
     { lang: '', pending: false },
   );
 
-  const { copy: writeClipboard, isSupported } = useClipboard();
-  const copied = ref(false);
+  const LANG_ALIASES: Record<string, string> = {
+    py: 'python',
+    python3: 'python',
+    js: 'javascript',
+    ts: 'typescript',
+    sh: 'bash',
+    shell: 'bash',
+    zsh: 'bash',
+    yml: 'yaml',
+    md: 'markdown',
+    htm: 'html',
+    cxx: 'cpp',
+    'c++': 'cpp',
+    cs: 'csharp',
+    'c#': 'csharp',
+    txt: 'text',
+    plaintext: 'text',
+  };
 
-  async function copy() {
-    if (!isSupported.value) return;
-    await writeClipboard(props.text || '');
-    copied.value = true;
-    setTimeout(() => (copied.value = false), 1600);
-  }
+  /** Shiki 常见语言白名单;未知语言退回 text,避免高亮器直接报错 */
+  const SUPPORTED_LANGS = new Set([
+    'python',
+    'javascript',
+    'typescript',
+    'json',
+    'sql',
+    'html',
+    'xml',
+    'css',
+    'scss',
+    'less',
+    'bash',
+    'java',
+    'c',
+    'cpp',
+    'csharp',
+    'go',
+    'rust',
+    'php',
+    'ruby',
+    'yaml',
+    'markdown',
+    'vue',
+    'text',
+  ]);
+
+  const normalizedLang = computed(() => {
+    const raw = String(props.lang || '').toLowerCase();
+    const lang = LANG_ALIASES[raw] || raw || 'text';
+    return SUPPORTED_LANGS.has(lang) ? lang : 'text';
+  });
+
+  /** 围栏长度必须大于代码里最长的反引号串,否则代码中的 ``` 会提前闭合围栏 */
+  const fence = computed(() => {
+    const longest = (props.text || '').match(/`+/g)?.reduce((max, run) => Math.max(max, run.length), 0) || 0;
+    return '`'.repeat(Math.max(3, longest + 1));
+  });
+
+  const markdown = computed(() => {
+    const code = props.text || '';
+    const body = code.endsWith('\n') ? code : `${code}\n`;
+    return `${fence.value}${normalizedLang.value}\n${body}${fence.value}`;
+  });
 </script>
 
 <style lang="less" scoped>
   .ai-code {
     margin: var(--ai-sp-3) 0;
-    border: 1px solid var(--ai-border);
-    border-radius: var(--ai-radius);
-    background: var(--ai-code-bg);
-    overflow: hidden;
-
-    &__head {
-      display: flex;
-      align-items: center;
-      gap: var(--ai-sp-2);
-      padding: var(--ai-sp-1) var(--ai-sp-2) var(--ai-sp-1) var(--ai-sp-3);
-      border-bottom: 1px solid var(--ai-border);
-      background: var(--ai-bg);
-    }
-
-    &__lang {
-      font-family: 'SFMono-Regular', Consolas, monospace;
-      font-size: 11px;
-      letter-spacing: 0.04em;
-      text-transform: uppercase;
-      color: var(--ai-text-2);
-    }
 
-    &__spacer {
-      flex: 1 1 auto;
-    }
-
-    &__pending {
-      font-size: 11px;
-      color: var(--ai-primary);
+    /* 代码块组件自带边框/圆角,外层只控制间距与最大高度 */
+    :deep(.streamdown-vue) {
+      margin: 0;
     }
 
-    &__btn {
-      padding: 2px 8px;
-      font-size: 11px;
-      color: var(--ai-text-2);
-      background: transparent;
-      border: 1px solid transparent;
-      border-radius: var(--ai-radius-sm);
-      cursor: pointer;
-      transition: all 0.15s ease-out;
-
-      &:hover {
-        color: var(--ai-primary);
-        border-color: fade(@primary-color, 35%);
-        background: var(--ai-primary-soft);
-      }
+    :deep([data-streamdown='code-block']) {
+      margin: 0;
     }
 
-    &__pre {
-      margin: 0;
-      padding: var(--ai-sp-3);
+    :deep([data-streamdown='code-body']) {
       max-height: 420px;
       overflow: auto;
-      font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
-      font-size: 12.5px;
-      line-height: 1.65;
-      white-space: pre;
-      color: var(--ai-text);
+    }
 
-      code {
-        font-family: inherit;
-        background: none;
-        border: none;
-        padding: 0;
-      }
+    /* 流式输出时给出一个轻量状态,不额外占一行文字 */
+    &.is-pending :deep([data-streamdown='code-block']) {
+      border-color: var(--ai-primary, #2a50ec);
     }
   }
 </style>

+ 15 - 11
ai-electron/frontend/src/ai/components/blocks/HtmlBlock.vue

@@ -15,7 +15,9 @@
 
     <div v-if="pending" class="ai-html__skeleton ai-skeleton" :style="{ height: '160px' }"></div>
 
-    <pre v-else-if="mode === 'source'" class="ai-html__source ai-scroll-area"><code>{{ html }}</code></pre>
+    <div v-else-if="mode === 'source'" class="ai-html__source">
+      <CodeBlock :text="html" lang="html" />
+    </div>
 
     <iframe
       v-else
@@ -39,6 +41,7 @@
    * 高度自适应通过注入脚本 postMessage 回传,父级校验 event.source 后采用。
    */
   import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
+  import CodeBlock from './CodeBlock.vue';
 
   const props = withDefaults(
     defineProps<{
@@ -159,16 +162,17 @@
     }
 
     &__source {
-      margin: 0;
-      padding: var(--ai-sp-3);
-      max-height: 420px;
-      overflow: auto;
-      font-family: 'SFMono-Regular', Consolas, monospace;
-      font-size: 12.5px;
-      line-height: 1.65;
-      white-space: pre-wrap;
-      word-break: break-all;
-      color: var(--ai-text);
+      padding: 0;
+
+      :deep(.ai-code) {
+        margin: 0;
+      }
+
+      /* 外层 .ai-html 已有边框,源码视图不再重复一圈 */
+      :deep([data-streamdown='code-block']) {
+        border: 0;
+        border-radius: 0;
+      }
     }
 
     &__skeleton {

+ 3 - 1
ai-electron/frontend/src/ai/components/relation/RelationGraphBlock.vue

@@ -31,7 +31,9 @@
       </div>
     </div>
 
-    <div v-if="isFullscreen" class="ai-relation__hint"> 滚轮缩放 · 拖动画布平移 · 按 Esc 退出全屏 </div>
+    <div v-if="isFullscreen" class="ai-relation__hint">
+      滚轮缩放 · 拖动画布平移 · 点击节点高亮相邻节点 · 点击关系线高亮两端 · 按 Esc 退出全屏
+    </div>
   </section>
 </template>
 

+ 256 - 36
ai-electron/frontend/src/ai/components/relation/RelationGraphViewer.vue

@@ -37,24 +37,18 @@
   /**
    * 通用关系图画布(基础渲染)
    *
-   * 与案件图谱的 GraphAnalysisViewer 完全独立:数据模型、G6 注册名(ai-relation-*)、
-   * 样式都单独一套,但布局复用 graphLayout(对象关系分析页的布局实现),
-   * 保证同类图在聊天里的节点分布一致。
+   * 数据模型/解析独立,但节点视觉复用案件图谱的 ai-graph-node(彩色图标方块 + 下方标签),
+   * 与项目中既有关系图组件保持一致;布局复用 graphLayout。
    *
    * 基础交互:缩放/拖拽/适配/全屏 + 节点类型图例;不做查找、过滤、条件重排、节点明细下钻。
    */
   import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';
-  import { Graph, GraphEvent } from '@antv/g6';
+  import { CanvasEvent, EdgeEvent, Graph, GraphEvent, NodeEvent, type IElementEvent } from '@antv/g6';
   import Icon from '@/core/components/Icon/src/Icon.vue';
   import type { ParsedGraph } from '../graph/graphData';
+  import { getEntityMeta, registerAIGraphElements } from '../graph/graphElements';
   import { layoutGraph } from '../graph/graphLayout';
-  import {
-    RELATION_TYPE_META_LIST,
-    buildRelationG6Data,
-    relationTypeMeta,
-    type ParsedRelationGraph,
-  } from './relationData';
-  import { registerRelationElements } from './relationElements';
+  import { RELATION_TYPE_META_LIST, buildRelationG6Data, type ParsedRelationGraph } from './relationData';
 
   const props = defineProps<{
     model: ParsedRelationGraph;
@@ -108,7 +102,7 @@
   /* ---------------- 生命周期 ---------------- */
 
   onMounted(() => {
-    registerRelationElements();
+    registerAIGraphElements();
     void rebuild();
   });
 
@@ -161,26 +155,52 @@
     stageResizeObserver.observe(stageRef.value);
   }
 
+  /** 关系图节点类型 → 项目既有实体类型(复用案件图谱的图标与配色) */
+  function toEntityKind(type: string): string {
+    switch (type) {
+      case 'person':
+        return 'person';
+      case 'phone':
+        return 'phone';
+      case 'card':
+      case 'account':
+        return 'bank';
+      case 'org':
+        return 'group';
+      case 'place':
+        return 'house';
+      case 'vehicle':
+        return 'car';
+      default:
+        return 'other';
+    }
+  }
+
   function createNodeOptions() {
     return {
-      type: 'ai-relation-node',
+      // 复用案件图谱的 ai-graph-node:彩色图标方块 + 下方主标签,两套关系图视觉一致
+      type: 'ai-graph-node',
       style: (node: any) => {
-        const meta = relationTypeMeta(String(node.data?.type || 'other'));
-        const label = String(node.data?.label || node.id || '');
-        const degree = Number(node.data?.degree || 0);
+        const meta = getEntityMeta(toEntityKind(String(node.data?.type || 'other')));
         return {
-          // 标签越长节点越宽,限制在 120~190,避免长名称溢出或节点过小
-          boxWidth: Math.min(190, Math.max(120, 96 + label.length * 8)),
-          boxHeight: 38,
+          size: 96,
+          iconBoxSize: 40,
+          iconBoxRadius: 11,
+          iconSize: 32,
           fill: meta.color,
-          fillOpacity: 0.96,
-          stroke: degree >= 6 ? 'rgba(255,255,255,0.92)' : 'rgba(255,255,255,0.42)',
-          lineWidth: degree >= 6 ? 2 : 1,
+          fillOpacity: 1,
+          stroke: 'rgba(255,255,255,0.22)',
+          strokeOpacity: 1,
+          lineWidth: 1,
           cursor: 'pointer',
-          labelText: label,
-          labelFill: '#ffffff',
-          labelFontSize: 12,
+          iconSrc: meta.icon,
+          iconOpacity: 1,
+          labelText: String(node.data?.label || node.id || ''),
+          labelFill: '#334155',
+          labelFontSize: 13,
           labelFontWeight: 600,
+          labelOpacity: 1,
+          secondaryLabelText: '',
         };
       },
       state: {
@@ -189,15 +209,34 @@
           haloStroke: '#1677ff',
           haloLineWidth: 2,
           stroke: '#1677ff',
+          strokeOpacity: 1,
           lineWidth: 3,
+          fillOpacity: 1,
+        },
+        highlight: {
+          halo: true,
+          haloStroke: '#60a5fa',
+          haloLineWidth: 2,
+          stroke: '#60a5fa',
+          strokeOpacity: 1,
+          lineWidth: 2,
+          fillOpacity: 1,
+        },
+        inactive: {
+          fillOpacity: 0.15,
+          iconOpacity: 0.15,
+          labelOpacity: 0.15,
+          secondaryLabelOpacity: 0.15,
+          strokeOpacity: 0.15,
         },
       },
     };
   }
 
   function createEdgeOptions() {
-    // 边太多时隐藏关系名,避免标签把画布糊住;节点本身的色块仍可辨识
-    const showLabel = props.model.edges.length <= 80;
+    // 边标签始终显示:否则用户无法判断关系线代表什么。
+    // 边很多时缩小字号,并由底部关系名图例辅助识别。
+    const dense = props.model.edges.length > 120;
     return {
       type: (edge: any) => String(edge.type || 'line'),
       style: (edge: any) => {
@@ -211,19 +250,177 @@
           endArrow: Boolean(edge.data?.directed),
           endArrowFill: '#94a3b8',
           endArrowSize: 8,
-          labelText: showLabel ? String(edge.data?.label || '') : '',
+          labelText: String(edge.data?.label || edge.data?.relation || '关联'),
           labelPlacement: 'center',
           labelFill: '#516076',
-          labelFontSize: 10,
-          labelOpacity: 0.9,
+          labelFontSize: dense ? 9 : 10,
+          labelOpacity: dense ? 0.85 : 0.95,
           labelBackground: true,
           labelBackgroundFill: 'rgba(255,255,255,0.92)',
           labelBackgroundRadius: 4,
         };
       },
+      state: {
+        selected: {
+          stroke: '#2563eb',
+          lineWidth: 3,
+          endArrowFill: '#2563eb',
+          labelFill: '#1d4ed8',
+          labelFontSize: 11,
+          labelOpacity: 1,
+        },
+        highlight: {
+          stroke: '#3b82f6',
+          lineWidth: 2.5,
+          opacity: 1,
+          endArrowFill: '#3b82f6',
+          labelFill: '#1d4ed8',
+          labelFontSize: 11,
+          labelOpacity: 1,
+        },
+        inactive: {
+          opacity: 0.12,
+          labelOpacity: 0.08,
+        },
+      },
     };
   }
 
+  /* ---------------- 选中节点/关系线:高亮相关点线 ---------------- */
+
+  /** 当前高亮的中心节点;再次点击同一节点时取消 */
+  let activeNodeId = '';
+  /** 当前高亮的关系线;再次点击同一条线时取消 */
+  let activeEdgeId = '';
+
+  async function clearHighlight() {
+    const graph = graphRef.value;
+    if (!graph) return;
+    const tasks: Array<Promise<unknown>> = [];
+    try {
+      graph.getNodeData().forEach((node) => {
+        tasks.push(graph.setElementState(String(node.id), [], false));
+      });
+      graph.getEdgeData().forEach((edge) => {
+        tasks.push(graph.setElementState(String(edge.id), [], false));
+      });
+      await Promise.all(tasks);
+    } catch {
+      /* 忽略状态清理异常 */
+    }
+  }
+
+  async function highlightNeighbors(id: string) {
+    const graph = graphRef.value;
+    if (!graph) return;
+
+    // 再点同一个节点 = 取消高亮
+    if (activeNodeId === id) {
+      activeNodeId = '';
+      activeEdgeId = '';
+      await clearHighlight();
+      return;
+    }
+    activeNodeId = id;
+    activeEdgeId = '';
+
+    const neighborNodes = new Set<string>();
+    const neighborEdges = new Set<string>();
+    props.model.edges.forEach((edge) => {
+      if (edge.source === id || edge.target === id) {
+        neighborEdges.add(edge.id);
+        neighborNodes.add(edge.source === id ? edge.target : edge.source);
+      }
+    });
+
+    await clearHighlight();
+    const tasks: Array<Promise<unknown>> = [];
+    try {
+      tasks.push(graph.setElementState(id, ['selected'], false));
+      neighborNodes.forEach((nodeId) => {
+        tasks.push(graph.setElementState(nodeId, ['highlight'], false));
+      });
+      neighborEdges.forEach((edgeId) => {
+        tasks.push(graph.setElementState(edgeId, ['highlight'], false));
+      });
+      props.model.nodes.forEach((node) => {
+        if (node.id === id || neighborNodes.has(node.id)) return;
+        tasks.push(graph.setElementState(node.id, ['inactive'], false));
+      });
+      props.model.edges.forEach((edge) => {
+        if (neighborEdges.has(edge.id)) return;
+        tasks.push(graph.setElementState(edge.id, ['inactive'], false));
+      });
+      await Promise.all(tasks);
+    } catch {
+      /* 忽略状态高亮异常 */
+    }
+  }
+
+  async function highlightEdge(edgeId: string) {
+    const graph = graphRef.value;
+    if (!graph) return;
+
+    // 再点同一条线 = 取消高亮
+    if (activeEdgeId === edgeId) {
+      activeEdgeId = '';
+      await clearHighlight();
+      return;
+    }
+    const edge = props.model.edges.find((item) => item.id === edgeId);
+    if (!edge) return;
+
+    activeEdgeId = edgeId;
+    activeNodeId = '';
+
+    await clearHighlight();
+    const tasks: Array<Promise<unknown>> = [];
+    try {
+      tasks.push(graph.setElementState(edgeId, ['selected'], false));
+      tasks.push(graph.setElementState(edge.source, ['highlight'], false));
+      tasks.push(graph.setElementState(edge.target, ['highlight'], false));
+      props.model.nodes.forEach((node) => {
+        if (node.id === edge.source || node.id === edge.target) return;
+        tasks.push(graph.setElementState(node.id, ['inactive'], false));
+      });
+      props.model.edges.forEach((item) => {
+        if (item.id === edgeId) return;
+        tasks.push(graph.setElementState(item.id, ['inactive'], false));
+      });
+      await Promise.all(tasks);
+    } catch {
+      /* 忽略状态高亮异常 */
+    }
+  }
+
+  let lastElementClickAt = 0;
+
+  function bindGraphEvents(graph: Graph) {
+    graph.on<IElementEvent>(NodeEvent.CLICK, (event: IElementEvent) => {
+      const id = String(event.target?.id || '');
+      if (!id) return;
+      lastElementClickAt = Date.now();
+      void highlightNeighbors(id);
+    });
+
+    graph.on<IElementEvent>(EdgeEvent.CLICK, (event: IElementEvent) => {
+      const id = String(event.target?.id || '');
+      if (!id) return;
+      lastElementClickAt = Date.now();
+      void highlightEdge(id);
+    });
+
+    graph.on(CanvasEvent.CLICK, () => {
+      window.setTimeout(() => {
+        // 部分 G6 版本里节点/边点击也会冒泡到 canvas;刚点过元素时不要立刻清掉高亮
+        if (Date.now() - lastElementClickAt < 120) return;
+        activeNodeId = '';
+        activeEdgeId = '';
+        void clearHighlight();
+      }, 0);
+    });
+  }
+
   async function rebuild() {
     const element = stageRef.value;
     if (!element || !props.model.nodes.length) {
@@ -237,6 +434,8 @@
       return;
     }
     try {
+      activeNodeId = '';
+      activeEdgeId = '';
       destroyGraph();
       const size = getCanvasSize();
       const data = buildRelationG6Data(props.model);
@@ -277,6 +476,7 @@
       } as any);
 
       graphRef.value = graph;
+      bindGraphEvents(graph);
       graph.on(GraphEvent.AFTER_TRANSFORM, refreshZoom);
       await graph.render();
       observeStageSize();
@@ -326,11 +526,24 @@
 
   async function resizeAndFit() {
     await nextTick();
-    // 等一帧让 autoResize 完成尺寸测量,否则全屏后会按旧尺寸 fit
+    // 等两帧让全屏浮层的 flex 尺寸稳定;autoResize 在浮层切换时可能拿不到最终高度,
+    // 这里再显式 resize 一次,避免画布只铺满上半截。
     await new Promise<void>((resolve) => {
-      if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => resolve());
-      else window.setTimeout(resolve, 0);
+      if (typeof requestAnimationFrame === 'function') {
+        requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
+      } else {
+        window.setTimeout(resolve, 0);
+      }
     });
+    const graph = graphRef.value;
+    const element = stageRef.value;
+    if (graph && element) {
+      try {
+        graph.resize(Math.max(1, element.clientWidth), Math.max(1, element.clientHeight));
+      } catch {
+        /* 忽略尺寸同步异常 */
+      }
+    }
     await fitView();
   }
 
@@ -340,15 +553,20 @@
 <style lang="less" scoped>
   .ai-relation-viewer {
     position: relative;
+    display: flex;
+    flex: 1 1 auto;
+    flex-direction: column;
     width: 100%;
     height: 100%;
-    min-height: 280px;
+    min-height: 0;
     background: var(--ai-bg-subtle, #f7f8fa);
     overflow: hidden;
 
     &__stage {
-      position: absolute;
-      inset: 0;
+      position: relative;
+      flex: 1 1 auto;
+      width: 100%;
+      min-height: 0;
     }
 
     &__toolbar {
@@ -422,6 +640,8 @@
       }
     }
 
+    /* 关系名不放在底部图例:线上已有标签,避免重复堆数据 */
+
     &__dot {
       display: inline-block;
       width: 8px;

+ 3 - 3
ai-electron/frontend/src/ai/components/relation/relationData.ts

@@ -18,7 +18,7 @@ export interface RelationTypeMeta {
   color: string;
 }
 
-/** 节点类型配色:与案件图谱的实体色保持一致,但组件与注册名完全独立 */
+/** 节点类型配色:与案件图谱的实体色保持一致(节点本身复用 ai-graph-node 的图标样式) */
 export const RELATION_TYPE_META: Record<RelationNodeType, RelationTypeMeta> = {
   person: { type: 'person', label: '人物', color: '#b92a31' },
   phone: { type: 'phone', label: '手机号', color: '#0aa0b4' },
@@ -26,8 +26,8 @@ export const RELATION_TYPE_META: Record<RelationNodeType, RelationTypeMeta> = {
   org: { type: 'org', label: '机构', color: '#0f9f68' },
   place: { type: 'place', label: '地点', color: '#0f4c8a' },
   vehicle: { type: 'vehicle', label: '车辆', color: '#f29a1f' },
-  account: { type: 'account', label: '账号', color: '#2563eb' },
-  other: { type: 'other', label: '其他', color: '#64748b' },
+  account: { type: 'account', label: '账号', color: '#8441ae' },
+  other: { type: 'other', label: '其他', color: '#d4ac2b' },
 };
 
 export const RELATION_TYPE_META_LIST: RelationTypeMeta[] = [

+ 0 - 80
ai-electron/frontend/src/ai/components/relation/relationElements.ts

@@ -1,80 +0,0 @@
-/**
- * 通用关系图 —— 独立 G6 元素
- *
- * 注册名使用 `ai-relation-*`,与既有案件图谱的 `ai-graph-*` 完全隔离,
- * 避免两套组件在同一页面(同一 G6 全局注册表)里互相覆盖。
- */
-import { BaseNode, register } from '@antv/g6';
-import { Rect as GRect, Text as GText, type Group } from '@antv/g';
-
-/** 主节点:圆角矩形 + 居中标签;颜色由节点类型决定 */
-class RelationNode extends BaseNode {
-  protected drawKeyShape(attributes: Record<string, any>, container: Group) {
-    const width = Number(attributes.boxWidth || 140);
-    const height = Number(attributes.boxHeight || 38);
-    return this.upsert(
-      'key',
-      GRect,
-      {
-        x: -width / 2,
-        y: -height / 2,
-        width,
-        height,
-        className: 'key',
-        radius: 10,
-        fill: attributes.fill,
-        fillOpacity: Number(attributes.fillOpacity ?? 0.96),
-        stroke: attributes.stroke || 'rgba(255,255,255,0.42)',
-        strokeOpacity: Number(attributes.strokeOpacity ?? 1),
-        lineWidth: Number(attributes.lineWidth || 1),
-        shadowColor: 'rgba(15, 23, 42, 0.16)',
-        shadowBlur: 8,
-        shadowOffsetY: 3,
-        cursor: attributes.cursor || 'pointer',
-      } as any,
-      container,
-    );
-  }
-
-  public override render(attributes: Record<string, any> = this.parsedAttributes, container: Group = this) {
-    this.drawKeyShape(attributes, container);
-
-    if (!attributes.labelText) {
-      this.upsert('label', GText, false, container);
-      return;
-    }
-
-    this.upsert(
-      'label',
-      GText,
-      {
-        x: 0,
-        y: 0,
-        className: 'label',
-        text: String(attributes.labelText),
-        fill: attributes.labelFill || '#ffffff',
-        fontSize: Number(attributes.labelFontSize || 12),
-        fontWeight: Number(attributes.labelFontWeight || 600),
-        textAlign: 'center',
-        textBaseline: 'middle',
-        maxLines: 1,
-        wordWrap: false,
-        pointerEvents: 'none',
-      } as any,
-      container,
-    );
-  }
-}
-
-let elementsRegistered = false;
-
-export function registerRelationElements(): void {
-  if (elementsRegistered) return;
-  try {
-    register('node', 'ai-relation-node', RelationNode as any);
-  } catch (error) {
-    // HMR / 同模块重复加载时 G6 可能拒绝重复注册;已注册过的元素仍可复用
-    console.warn('register relation graph elements failed', error);
-  }
-  elementsRegistered = true;
-}

+ 22 - 34
ai-server/src/main/java/com/zsjz/ai/module/agent/python/PythonExecutor.java

@@ -22,12 +22,16 @@ import java.util.concurrent.TimeUnit;
 import java.util.stream.Stream;
 
 /**
- * Python 子进程沙箱执行器
+ * Python 子进程执行器(独立临时目录)。
  *
  * <p>每次执行使用独立临时目录({@code cases/{caseId}/ai/python/sandbox/{execId}}),
  * 超时强制终止、输出截断;执行后将沙箱内生成的图片移动到
  * {@code cases/{caseId}/ai/python/out/{execId}} 供文件服务接口输出。
  *
+ * <p><b>不做代码内容拦截</b>:文件读写、子进程、网络等操作由 Python 代码自行决定,
+ * 只保留空代码校验、执行超时和输出截断。进程与 Java 同用户运行,需要隔离时
+ * 请使用容器/受限 OS 用户,或只挂载当前案件目录。
+ *
  * <h3>ETL_DB_PATH 指向的是「快照副本」而不是原库</h3>
  * DuckDB 单文件只允许一个进程读写打开,而案件库在本进程(Java)里是常驻打开的 ——
  * 子进程直接连原库必然失败(Windows 报「另一个程序正在使用此文件」)。
@@ -93,9 +97,9 @@ public class PythonExecutor {
     /**
      * 关系图辅助模块源码。
      *
-     * <p>为什么由后端注入而不是让模型自己写文件:{@link #validateCode(String)} 禁止用户代码
-     * 出现 {@code open(} / {@code pathlib},模型没有可靠的文件写出方式。这里给一个<b>只做序列化</b>
-     * 的小工具,节点/边的业务口径(查哪张表、怎么聚合、关系怎么命名)仍全部由模型在 Python 里决定。
+     * <p>为什么由后端注入:给模型一个稳定的关系图序列化入口,避免每次手写节点/边 JSON。
+     * Python 代码拥有完整文件/进程/网络权限,模型也可以直接用 {@code open}/{@code pathlib}
+     * 写 HTML/CSV;这里的小工具<b>只做序列化</b>,节点/边的业务口径仍全部由模型在 Python 里决定。
      */
     private static final String RELATION_HELPER_SOURCE = """
             # 关系图输出辅助模块(后端注入,随沙箱清理)
@@ -133,13 +137,24 @@ public class PythonExecutor {
             def emit_relation_graph(nodes=None, edges=None, title=None):
                 # nodes: list[dict] / DataFrame -> {id, label, type, value}
                 # edges: list[dict] / DataFrame -> {source, target, relation, weight, directed}
-                payload = {"nodes": _clean(_records(nodes)), "edges": _clean(_records(edges))}
+                # relation 是关系线标签(如通话/转账/亲属);缺失时回退 label,再回退“关联”
+                node_records = _clean(_records(nodes))
+                edge_records = _clean(_records(edges))
+                missing_relation = 0
+                for edge in edge_records:
+                    if isinstance(edge, dict) and not edge.get("relation") and not edge.get("label"):
+                        edge["relation"] = "关联"
+                        missing_relation += 1
+                payload = {"nodes": node_records, "edges": edge_records}
                 if title:
                     payload["title"] = str(title)[:100]
                 with open("relation_graph.json", "w", encoding="utf-8") as f:
                     json.dump(payload, f, ensure_ascii=False, default=str)
                 print("[relation-graph] %d nodes, %d edges -> relation_graph.json"
                       % (len(payload["nodes"]), len(payload["edges"])))
+                if missing_relation:
+                    print("[relation-graph] warning: %d edges have no relation; labeled 关联"
+                          % missing_relation)
             """;
 
     private final EtlProperties etlProperties;
@@ -190,9 +205,8 @@ public class PythonExecutor {
         if (!isAvailable()) {
             return PythonResult.error("Python 执行环境不可用(未安装或缺少依赖:pip install pandas duckdb matplotlib)");
         }
-        String codeProblem = validateCode(code);
-        if (codeProblem != null) {
-            return PythonResult.error(codeProblem);
+        if (code == null || code.isBlank()) {
+            return PythonResult.error("Python 代码不能为空");
         }
         // 只读 ThreadLocal:Agent 的流式链路跑在 Reactor 线程上,案件上下文由
         // AgentToolRegistry 在工具调用收口处用 CaseContextHolder.runWith 显式绑定。
@@ -304,32 +318,6 @@ public class PythonExecutor {
     record RelationGraphFile(String json, String error) {
     }
 
-    /**
-     * Python 代码的兜底黑名单。
-     *
-     * <p>这不是沙箱:真正的隔离要靠容器/受限 OS 用户。这里只拦住最直接的
-     * 文件系统/网络逃逸写法,降低模型被提示词注入后读取其他案件文件或外联的风险。
-     * 生产环境建议直接关闭 Python 工具,或把它跑在只挂载当前案件快照的容器里。
-     */
-    private static String validateCode(String code) {
-        if (code == null || code.isBlank()) {
-            return "Python 代码不能为空";
-        }
-        String normalized = code.toLowerCase();
-        List<String> forbidden = List.of(
-                "subprocess", "socket", "requests", "urllib", "shutil", "pathlib",
-                "os.system", "os.popen", "os.remove", "os.unlink", "os.rename",
-                "os.chdir", "os.listdir", "os.walk", "ctypes", "importlib",
-                "__import__", "glob.glob", "open(");
-        for (String token : forbidden) {
-            if (normalized.contains(token)) {
-                return "Python 代码包含禁止的文件/系统/网络操作: " + token
-                        + "(只能使用 ETL_DB_PATH 指向的当前案件快照做分析)";
-            }
-        }
-        return null;
-    }
-
     /**
      * 执行结果 record(error 非空表示未正常执行)。
      *

+ 4 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/render/RelationGraphPayload.java

@@ -353,6 +353,10 @@ public final class RelationGraphPayload {
 
     private static EdgeAcc toEdge(JsonNode item, String source, String target) {
         String relation = text(item.get("relation"), MAX_TEXT);
+        if (relation.isEmpty()) {
+            // 兼容模型把关系名写成 label 的情况;再兜底为“关联”
+            relation = text(item.get("label"), MAX_TEXT);
+        }
         if (relation.isEmpty()) {
             relation = "关联";
         }

+ 1 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/service/AgentService.java

@@ -688,6 +688,7 @@ public class AgentService extends ServiceImpl<AgentMapper, AgentEntity> {
 
                 ## 输出契约
                 - 表格类业务工具的结果会自动导出 CSV 产物;正文需要展示数据时用 Markdown 表格。
+                - 代码、SQL、JSON、HTML 等用 ```语言 围栏输出(如 ```python、```json、```html),前端会按语言高亮;不要用纯文本或截图代替代码。
                 - 可视化按对应工具 description 的返回契约输出(例如 render_chart 返回的 option 放进 ```echarts 围栏);前端会自动渲染,不要手写不支持的 chart series,也不要用文字罗列代替。""";
     }
 

+ 11 - 19
ai-server/src/main/java/com/zsjz/ai/module/agent/tools/PythonAnalysisTool.java

@@ -31,19 +31,16 @@ public class PythonAnalysisTool {
     }
 
     /**
-     * 在隔离沙箱中执行 Python 数据分析代码
+     * 执行 Python 代码(独立临时目录,不限文件/进程/网络操作)
      */
     @Tool(name = "execute_python",
-          description = "通用 Python 执行器:数据查询、多表 JOIN、pandas 处理、清洗/聚合、算法、"
-                  + "matplotlib 可视化、生成 CSV/Excel/HTML/Word 报告"
-                  + "(pandas/numpy/duckdb/matplotlib/openpyxl/python-docx)。"
-                  + "ETL_DB_PATH 是当前案件 DuckDB 的只读快照,可直接 connect 查询;"
-                  + "用 print() 输出结论,savefig/to_csv/to_excel/docx 等生成的文件自动进入产物栏。"
-                  + "需要输出通用关系图时,调用沙箱内置的 zgraph.emit_relation_graph(nodes, edges, title):"
-                  + "nodes=[{id,label,type,value}],edges=[{source,target,relation,weight,directed}],"
-                  + "source/target 对应 node.id;type 可选 person/phone/card/org/place/vehicle/account/other。"
-                  + "该调用会生成 relation_graph.json,前端自动渲染通用关系图。"
-                  + "单次执行默认 60 秒。",
+          description = "通用 Python 执行器(pandas/numpy/duckdb/matplotlib/openpyxl/python-docx):"
+                  + "查询、JOIN、清洗/聚合、算法、可视化、生成报告。"
+                  + "ETL_DB_PATH 是当前案件 DuckDB 的只读快照;print() 输出结论,"
+                  + "open/pathlib 可直接读写当前目录,生成文件自动进产物栏。"
+                  + "关系图用 zgraph.emit_relation_graph(nodes, edges, title):"
+                  + "nodes=[{id,label,type}],edges=[{source,target,relation,weight}];"
+                  + "source/target 对应 node.id,relation 是线标签。",
           readOnly = true)
     public ToolResultBlock executePython(
             @ToolParam(name = "code", description = "Python 3 代码,必填;单次执行默认 60 秒") String code) {
@@ -56,8 +53,9 @@ public class PythonAnalysisTool {
             if (result.stderr() != null && !result.stderr().isBlank()) {
                 data.put("stderr", result.stderr());
             }
-            data.put("imageUrls", result.imageUrls());
-            data.put("durationMs", result.durationMs());
+            if (result.imageUrls() != null && !result.imageUrls().isEmpty()) {
+                data.put("imageUrls", result.imageUrls());
+            }
 
             // 关系图载荷:模型调用 emit_relation_graph 时由沙箱写出,后端只做结构规范化/裁剪。
             // 解析失败不阻断 Python 结果,把可读错误交给模型自行修正脚本。
@@ -71,12 +69,6 @@ public class PythonAnalysisTool {
                 data.put("relationGraphError", result.relationGraphError());
             }
 
-            String hint = "图表和生成的文件会自动保存到产物栏;请在 stdout 用 print 输出关键结论,"
-                    + "正文不要贴大段原始数据。";
-            if (data.containsKey("relationGraph")) {
-                hint += "关系图已生成,前端会自动展示;正文只写结论。";
-            }
-            data.put("hint", hint);
             if (result.error() != null) {
                 data.put("error", result.error());
             }

+ 1 - 1
ai-server/src/test/java/com/zsjz/ai/module/agent/python/PythonExecutorTest.java

@@ -15,7 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
  * {@link PythonExecutor#readRelationGraph(Path)} 的边界测试。
  *
  * <p>关系图载荷由模型在沙箱里写出,执行器负责读取;这里不起 Python 进程,
- * 只验证「不存在 / 正常 / 超过 2MB」三条分支,避免大文件把后续 JSON 解析拖垮。
+ * 只验证「不存在 / 正常 / 超过 2MB」三条分支。
  */
 class PythonExecutorTest {
 

+ 16 - 0
ai-server/src/test/java/com/zsjz/ai/module/agent/render/RelationGraphPayloadTest.java

@@ -93,6 +93,22 @@ class RelationGraphPayloadTest {
         assertEquals(1, zhang.get("degree"));
     }
 
+    @Test
+    @DisplayName("边缺少 relation 时回退 label,再回退“关联”")
+    void fallsBackToLabelOrDefaultRelation() {
+        String json = """
+                {"edges": [
+                  {"source": "A", "target": "B", "label": "转账", "weight": 2},
+                  {"source": "B", "target": "C", "weight": 1}
+                ]}
+                """;
+        Map<String, Object> result = RelationGraphPayload.normalize(json);
+
+        assertEquals(2, list(result, "edges").size());
+        assertEquals("转账", edge(list(result, "edges"), "A", "B").get("relation"));
+        assertEquals("关联", edge(list(result, "edges"), "B", "C").get("relation"));
+    }
+
     @Test
     @DisplayName("无向边 A→B 与 B→A 合并,权重累加")
     void mergesReversedUndirectedEdges() {

+ 3 - 2
ai-server/src/test/java/com/zsjz/ai/module/agent/tools/PythonAnalysisToolTest.java

@@ -63,7 +63,7 @@ class PythonAnalysisToolTest {
     }
 
     @Test
-    @DisplayName("有 relation_graph.json:结果里带规范化后的 relationGraph,并提示前端会自动展示")
+    @DisplayName("有 relation_graph.json:结果里带规范化后的 relationGraph,且不塞冗余提示字段")
     void attachesRelationGraph() {
         stub(result("""
                 {"title": "人物社交关系",
@@ -78,7 +78,8 @@ class PythonAnalysisToolTest {
         assertEquals(2, payload.path("relationGraph").path("nodes").size());
         assertEquals(1, payload.path("relationGraph").path("edges").size());
         assertEquals("人物社交关系", payload.path("relationGraph").path("title").asText());
-        assertTrue(payload.path("hint").asText().contains("关系图已生成"));
+        assertFalse(payload.has("hint"), "结果里不要再带冗余 hint");
+        assertFalse(payload.has("durationMs"), "耗时只留在后端日志,不进模型上下文");
     }
 
     @Test