forked from longtao.wu/droboticflow
🐛 Render assistant Markdown and validated topology diagrams
Replace plain-text replies with react-markdown and GFM tables, lists, code and safe links. Recognize complete topology fences, JSON fences and standalone graph data in source order without promoting ordinary JSON. Render escaped SVG elements with cycle-safe layouts, zoom, node details and accessible data tables; show incomplete graphs as recoverable errors. Preserve finish_reason=length, prevent truncated tool calls from executing, and give concise topology replies a 4096-token budget. Tighten the prompt to return bounded, closed diagrams rather than an exhaustive node dump. Add parser, model-completion and isolated browser regression coverage. Fix existing frontend type declarations exposed by the React types now provided with react-markdown, without changing workflow execution. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
f1e0b8b081
commit
f1d71164ae
@ -116,6 +116,25 @@ the ops-runner Role is therefore kept to what the product-surface scripts call (
|
||||
only by name). Actions that need the developer's worktree, keychain, Docker or local credentials
|
||||
(image builds, deploys from a fresh build, drosync releases, `poc.configure-fixtures`) are CLI/Claude only.
|
||||
|
||||
### Assistant answer rendering
|
||||
|
||||
Assistant answers render GFM Markdown (headings, lists, tables, code and links). Complete
|
||||
`ops-topology` / `rca-topology` / `diagnostic-topology` / `topology` fences, JSON fences containing a
|
||||
graph, and standalone graph JSON are displayed as SVG diagrams. Ordinary JSON remains code;
|
||||
node-only arrays must include diagram fields and never gain inferred edges. Diagrams support
|
||||
zoom, keyboard-accessible node details and a tabular data view. Raw HTML is inert, unsafe links
|
||||
are removed, and model-selected image URLs are links rather than automatic image requests.
|
||||
|
||||
Replies that hit the model output cap persist `finishReason=length` and show a truncation notice.
|
||||
Incomplete graphs show an explanation with their source collapsed, not a fabricated partial
|
||||
relationship graph. Tool calls from truncated replies are not executed. Existing incomplete
|
||||
answers must be regenerated; missing nodes and edges cannot be recovered by the renderer.
|
||||
|
||||
Local browser regression: start the Vite dev server and run
|
||||
`node tests/frontend/assistant-rich-text-browser.mjs http://127.0.0.1:5191` (or your local port).
|
||||
It uses synthetic API fixtures and isolated Chrome, never production accounts or a real model.
|
||||
Screenshots are written under ignored `output/assistant-rendering/`.
|
||||
|
||||
## Account Security
|
||||
|
||||
The API supports HttpOnly cookie-session auth through `/api/auth/*` and super-admin organization/user management under `/api/admin/*`. Existing deployments keep their current behavior unless `DROBOTICFLOW_REQUIRE_SESSION_AUTH=true` is set. Before enabling it, bootstrap the first super admin and verify login through `/api/auth/login`.
|
||||
|
||||
@ -7,7 +7,8 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
const assistantMaxTokens = 2048
|
||||
// Leave room for a concise answer and a bounded topology in the same response.
|
||||
const assistantMaxTokens = 4096
|
||||
|
||||
// ChatService is the tool-calling chat used by the ops assistant. It is separate from Service so
|
||||
// workflow/operator generation does not depend on it.
|
||||
@ -16,11 +17,13 @@ type ChatService interface {
|
||||
}
|
||||
|
||||
type ChatMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
Reasoning string `json:"reasoning,omitempty"`
|
||||
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"`
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
Reasoning string `json:"reasoning,omitempty"`
|
||||
// FinishReason is response metadata, not part of the next chat request.
|
||||
FinishReason string `json:"-"`
|
||||
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"`
|
||||
}
|
||||
|
||||
type ToolCall struct {
|
||||
@ -61,7 +64,8 @@ type toolChatRequest struct {
|
||||
|
||||
type toolChatResponse struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
FinishReason string `json:"finish_reason"`
|
||||
Message struct {
|
||||
Content any `json:"content"`
|
||||
ReasoningContent string `json:"reasoning_content"`
|
||||
ToolCalls []ToolCall `json:"tool_calls"`
|
||||
@ -109,7 +113,7 @@ func (client *client) Chat(ctx context.Context, request ChatRequest) (*ChatMessa
|
||||
return nil, fmt.Errorf("AI 服务没有返回内容")
|
||||
}
|
||||
choice := response.Choices[0].Message
|
||||
message := &ChatMessage{Role: "assistant", Content: flattenContent(choice.Content), Reasoning: strings.TrimSpace(choice.ReasoningContent), ToolCalls: choice.ToolCalls}
|
||||
message := &ChatMessage{Role: "assistant", Content: flattenContent(choice.Content), Reasoning: strings.TrimSpace(choice.ReasoningContent), ToolCalls: choice.ToolCalls, FinishReason: response.Choices[0].FinishReason}
|
||||
for index := range message.ToolCalls {
|
||||
if message.ToolCalls[index].Type == "" {
|
||||
message.ToolCalls[index].Type = "function"
|
||||
|
||||
40
internal/ai/chat_test.go
Normal file
40
internal/ai/chat_test.go
Normal file
@ -0,0 +1,40 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestChatPreservesOutputLimitMetadataWithoutSendingItToProvider(t *testing.T) {
|
||||
for _, finish := range []string{"stop", "length"} {
|
||||
t.Run(finish, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var request map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if request["max_tokens"] != float64(4096) {
|
||||
t.Errorf("chat output budget = %v, want room for prose plus topology", request["max_tokens"])
|
||||
}
|
||||
messages := request["messages"].([]any)
|
||||
if _, ok := messages[0].(map[string]any)["FinishReason"]; ok {
|
||||
t.Error("response metadata leaked into request")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{"choices":[{"finish_reason":%q,"message":{"role":"assistant","content":"partial answer"}}]}`, finish)
|
||||
}))
|
||||
defer server.Close()
|
||||
chat := NewService(server.URL, "fixture-key", "fixture-model").(ChatService)
|
||||
reply, err := chat.Chat(t.Context(), ChatRequest{Messages: []ChatMessage{{Role: "user", Content: "画图", FinishReason: "length"}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reply.FinishReason != finish || reply.Content != "partial answer" {
|
||||
t.Fatalf("unexpected reply: %+v", reply)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -751,10 +751,13 @@ func (engine *Engine) modelRounds(ctx context.Context, sessionID string, userID
|
||||
return err
|
||||
}
|
||||
calls := []domain.AssistantToolCall{}
|
||||
for _, call := range reply.ToolCalls {
|
||||
calls = append(calls, domain.AssistantToolCall{ID: call.ID, Name: call.Function.Name, Arguments: call.Function.Arguments})
|
||||
// Retain partial prose for the user, but never execute tool calls from a truncated response.
|
||||
if reply.FinishReason != "length" {
|
||||
for _, call := range reply.ToolCalls {
|
||||
calls = append(calls, domain.AssistantToolCall{ID: call.ID, Name: call.Function.Name, Arguments: call.Function.Arguments})
|
||||
}
|
||||
}
|
||||
if err := engine.appendMessage(ctx, session, domain.AssistantMessage{Role: domain.AssistantMessageAssistant, Content: reply.Content, Reasoning: reply.Reasoning, ToolCalls: calls}); err != nil {
|
||||
if err := engine.appendMessage(ctx, session, domain.AssistantMessage{Role: domain.AssistantMessageAssistant, Content: reply.Content, Reasoning: reply.Reasoning, FinishReason: reply.FinishReason, ToolCalls: calls}); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(calls) == 0 {
|
||||
|
||||
@ -509,6 +509,30 @@ func TestNewMessageExpiresPendingModelConfirmations(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncatedModelReplyIsStoredButItsToolsAreNotExecuted(t *testing.T) {
|
||||
h := newHarness(t, true, true)
|
||||
reply := toolCall("call-truncated", "platform.projects", `{}`)
|
||||
reply.Content = "```ops-topology\n{\"nodes\":["
|
||||
reply.FinishReason = "length"
|
||||
h.chat.replies = []*ai.ChatMessage{reply}
|
||||
sessionID := h.session(t, admin)
|
||||
if err := h.engine.Send(t.Context(), admin, sessionID, "画出项目关系"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.drain()
|
||||
transcript, err := h.engine.GetTranscript(t.Context(), admin, sessionID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
last := transcript.Messages[len(transcript.Messages)-1]
|
||||
if last.FinishReason != "length" || last.Content != reply.Content || len(last.ToolCalls) != 0 {
|
||||
t.Fatalf("truncated response metadata was lost: %+v", last)
|
||||
}
|
||||
if len(h.http.calls) != 0 || len(h.runner.started) != 0 || transcript.Session.Busy {
|
||||
t.Fatal("truncated tool calls must not execute or leave the session busy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatDisabledStillAllowsSlashCommands(t *testing.T) {
|
||||
h := newHarness(t, false, false)
|
||||
sessionID := h.session(t, admin)
|
||||
|
||||
@ -27,9 +27,14 @@ const systemPrompt = `你是 droboticflow 平台的运维助手。用户通过
|
||||
4. 建议分为止血、根治、预防;只建议,不擅自执行变更。
|
||||
|
||||
【回答格式】中文,像同事回话:先一句话结论,再列证据(动作名 + 关键数字/名称),最后给下一步。不要复述整段 JSON。
|
||||
关系、依赖、影响范围、根因链,请额外放一个 ` + "```ops-topology" + ` 代码块,内容是严格 JSON:` +
|
||||
`{"title":"标题","nodes":[{"id":"短ID","label":"显示名","kind":"project|workflow|run|cluster|node|pod|symptom|cause|root|evidence|other","status":"ok|warning|error|unknown","detail":"可选"}],"edges":[{"from":"源","to":"目标","relation":"contains|causes|supports","label":"可选"}]}` +
|
||||
`。节点必须来自工具真实返回的对象,不得编造。`
|
||||
用 Markdown 的标题、列表、表格组织正文,代码与数据放在代码块里。
|
||||
关系、依赖、影响范围、根因链使用一个完整的 ops-topology 代码块。以下只是格式示例,不是真实资源:
|
||||
` + "```ops-topology\n" +
|
||||
`{"title":"项目与工作流","nodes":[{"id":"p","label":"示例项目","kind":"project","status":"unknown"},{"id":"w","label":"示例工作流","kind":"workflow","status":"unknown"}],"edges":[{"from":"p","to":"w","relation":"contains"}]}` + "\n```\n" +
|
||||
`实际节点和连线必须来自工具返回的证据,不得把示例或猜测当作真实对象。
|
||||
每次优先画重点对象,最多 12 个节点、20 条边;每个 label 最多 24 字,detail 可省略且最多 60 字,不要重复长 ID 或逐条抄整个目录。
|
||||
对象更多时按已知状态或类型聚合,说明省略了哪些内容。没有关系证据只列节点,不补画连线。
|
||||
必须完整输出外层对象、nodes 和 edges 数组及结束代码围栏;不要把节点列表写到一半。`
|
||||
|
||||
func toolName(actionID string) string {
|
||||
return strings.ReplaceAll(actionID, ".", "__")
|
||||
|
||||
@ -36,6 +36,7 @@ type AssistantMessage struct {
|
||||
Role AssistantMessageRole `json:"role" bson:"role"`
|
||||
Content string `json:"content" bson:"content"`
|
||||
Reasoning string `json:"reasoning,omitempty" bson:"reasoning,omitempty"`
|
||||
FinishReason string `json:"finishReason,omitempty" bson:"finishReason,omitempty"`
|
||||
ToolCalls []AssistantToolCall `json:"toolCalls,omitempty" bson:"toolCalls,omitempty"`
|
||||
ToolCallID string `json:"toolCallId,omitempty" bson:"toolCallId,omitempty"`
|
||||
StepID string `json:"stepId,omitempty" bson:"stepId,omitempty"`
|
||||
|
||||
1508
package-lock.json
generated
1508
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -90,9 +90,11 @@
|
||||
"motion": "^12.23.24",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-markdown": "10.1.0",
|
||||
"react-router-dom": "^7.14.0",
|
||||
"reactflow": "^11.11.4",
|
||||
"recharts": "^3.8.1",
|
||||
"remark-gfm": "4.0.1",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"three": "^0.185.1",
|
||||
"zod": "^4.1.11"
|
||||
|
||||
@ -122,7 +122,7 @@ export function Sidebar({ isCollapsed, onToggle }: SidebarProps) {
|
||||
if (!role) {
|
||||
return [];
|
||||
}
|
||||
return navItems.filter((item) => item.roles.includes(role));
|
||||
return navItems.filter((item) => item.roles.some((allowed) => allowed === role));
|
||||
}, [role]);
|
||||
|
||||
const { pathname } = useLocation();
|
||||
|
||||
67
src/components/assistant/AssistantRichText.tsx
Normal file
67
src/components/assistant/AssistantRichText.tsx
Normal file
@ -0,0 +1,67 @@
|
||||
import React, { memo, useMemo } from "react";
|
||||
import Markdown, { defaultUrlTransform, type Components } from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { splitRichContent } from "../../lib/assistant-topology.js";
|
||||
import { TopologyFigure } from "./TopologyFigure";
|
||||
import "./assistant-rich-text.css";
|
||||
|
||||
// Keep model HTML inert. Links are checked by react-markdown; images become links rather than
|
||||
// background requests to model-selected servers (which could track viewers).
|
||||
const components: Components = {
|
||||
a: ({ href, children }) =>
|
||||
href ? (
|
||||
<a href={href} target={href.startsWith("http") ? "_blank" : undefined} rel="noopener noreferrer">
|
||||
{children}
|
||||
</a>
|
||||
) : (
|
||||
<span>{children}</span>
|
||||
),
|
||||
img: ({ src, alt }) =>
|
||||
src ? (
|
||||
<a href={src} target="_blank" rel="noopener noreferrer">
|
||||
[图片:{alt || "打开图片"}]
|
||||
</a>
|
||||
) : (
|
||||
<span>[图片地址不可用]</span>
|
||||
),
|
||||
table: ({ children }) => (
|
||||
<div className="assistant-table-scroll">
|
||||
<table>{children}</table>
|
||||
</div>
|
||||
),
|
||||
};
|
||||
|
||||
function safeURL(url: string) {
|
||||
if (url.startsWith("//") || url.includes("\\")) return "";
|
||||
return defaultUrlTransform(url);
|
||||
}
|
||||
|
||||
export const AssistantRichText = memo(function AssistantRichText({
|
||||
text,
|
||||
finishReason,
|
||||
}: {
|
||||
text: string;
|
||||
finishReason?: string;
|
||||
}) {
|
||||
const parts = useMemo(() => splitRichContent(text), [text]);
|
||||
return (
|
||||
<div className="assistant-rich-text">
|
||||
{parts.map((part, index) => (
|
||||
<React.Fragment key={index}>
|
||||
{part.type === "topology" ? (
|
||||
<TopologyFigure source={part.source} />
|
||||
) : (
|
||||
<Markdown remarkPlugins={[remarkGfm]} components={components} urlTransform={safeURL} skipHtml>
|
||||
{part.text}
|
||||
</Markdown>
|
||||
)}
|
||||
</React.Fragment>
|
||||
))}
|
||||
{finishReason === "length" && (
|
||||
<p className="assistant-response-warning" role="note">
|
||||
这条回复达到模型输出上限,内容被截断。可以让助手只画重点项目,或分批展示拓扑;未完整返回的工具调用没有执行。
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
261
src/components/assistant/TopologyFigure.tsx
Normal file
261
src/components/assistant/TopologyFigure.tsx
Normal file
@ -0,0 +1,261 @@
|
||||
import React, { useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { Maximize2, Minus, Plus } from "lucide-react";
|
||||
import { layoutTopology, parseTopology } from "../../lib/assistant-topology.js";
|
||||
|
||||
const STATUS = {
|
||||
ok: { label: "正常", symbol: "✓" },
|
||||
warning: { label: "需关注", symbol: "!" },
|
||||
error: { label: "异常", symbol: "×" },
|
||||
unknown: { label: "未确认", symbol: "?" },
|
||||
};
|
||||
const KIND = {
|
||||
cloud: "云",
|
||||
cluster: "集群",
|
||||
node: "节点",
|
||||
namespace: "命名空间",
|
||||
workload: "工作负载",
|
||||
pod: "Pod",
|
||||
service: "服务",
|
||||
loadbalancer: "负载均衡",
|
||||
instance: "实例",
|
||||
project: "项目",
|
||||
workflow: "工作流",
|
||||
run: "运行",
|
||||
operator: "算子",
|
||||
symptom: "现象",
|
||||
trigger: "触发事件",
|
||||
cause: "原因",
|
||||
factor: "促成因素",
|
||||
root: "根因",
|
||||
evidence: "证据",
|
||||
rejected: "已排除",
|
||||
other: "对象",
|
||||
};
|
||||
const RELATION = { contains: "包含", causes: "导致", supports: "支持", refutes: "反驳" };
|
||||
|
||||
export function TopologyFigure({ source }: { source: string }) {
|
||||
const parsed = useMemo(() => parseTopology(source), [source]);
|
||||
if (!parsed.ok) {
|
||||
return (
|
||||
<div className="assistant-diagram-error" role="note">
|
||||
<strong>拓扑暂未显示</strong>
|
||||
<p>{parsed.reason}。不会用残缺数据生成关系图。</p>
|
||||
<details>
|
||||
<summary>查看原始拓扑数据</summary>
|
||||
<pre>{source}</pre>
|
||||
</details>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <TopologyCanvas topology={parsed.topology} />;
|
||||
}
|
||||
|
||||
function TopologyCanvas({ topology }: { topology: NonNullable<ReturnType<typeof parseTopology>["topology"]> }) {
|
||||
const layout = useMemo(() => layoutTopology(topology), [topology]);
|
||||
const id = useId().replace(/[^a-zA-Z0-9_-]/g, "");
|
||||
const viewport = useRef<HTMLDivElement>(null);
|
||||
const [viewportWidth, setViewportWidth] = useState(0);
|
||||
const [zoom, setZoom] = useState<number | null>(null);
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
const [hovered, setHovered] = useState<string | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const element = viewport.current;
|
||||
if (!element) return;
|
||||
const measure = () => setViewportWidth(element.clientWidth);
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(element);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
// Fit horizontally, but do not shrink a large graph to unreadable dots. Overflow remains scrollable.
|
||||
const scale = zoom ?? Math.max(0.5, Math.min(1, (viewportWidth || layout.width) / layout.width));
|
||||
const changeZoom = (factor: number) => setZoom(Math.max(0.5, Math.min(2, scale * factor)));
|
||||
const active = topology.nodes.find((node) => node.id === (hovered || selected));
|
||||
const title = topology.title || "关系拓扑";
|
||||
const presentStatuses = Object.keys(STATUS).filter((status) => topology.nodes.some((node) => node.status === status));
|
||||
const names = new Map(topology.nodes.map((node) => [node.id, node.label]));
|
||||
|
||||
return (
|
||||
<figure className="assistant-topology">
|
||||
<div className="assistant-topology-header">
|
||||
<figcaption id={`${id}-title`}>{title}</figcaption>
|
||||
<div className="assistant-topology-controls" aria-label="拓扑缩放">
|
||||
<button
|
||||
type="button"
|
||||
title="缩小拓扑"
|
||||
aria-label="缩小拓扑"
|
||||
onClick={() => changeZoom(0.8)}
|
||||
disabled={scale <= 0.5}
|
||||
>
|
||||
<Minus size={14} />
|
||||
</button>
|
||||
<span aria-live="polite">{Math.round(scale * 100)}%</span>
|
||||
<button
|
||||
type="button"
|
||||
title="放大拓扑"
|
||||
aria-label="放大拓扑"
|
||||
onClick={() => changeZoom(1.25)}
|
||||
disabled={scale >= 2}
|
||||
>
|
||||
<Plus size={14} />
|
||||
</button>
|
||||
<button type="button" title="适应宽度" aria-label="适应宽度" onClick={() => setZoom(null)}>
|
||||
<Maximize2 size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="assistant-topology-legend" aria-label="节点状态">
|
||||
{presentStatuses.map((status) => (
|
||||
<span key={status}>
|
||||
<i className={`assistant-status-dot status-${status}`} aria-hidden="true" />
|
||||
{STATUS[status].symbol} {STATUS[status].label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
ref={viewport}
|
||||
className="assistant-topology-viewport"
|
||||
tabIndex={0}
|
||||
aria-label={`${title}画布,可滚动或缩放`}
|
||||
>
|
||||
<svg
|
||||
width={layout.width * scale}
|
||||
height={layout.height * scale}
|
||||
viewBox={`0 0 ${layout.width} ${layout.height}`}
|
||||
role="img"
|
||||
aria-labelledby={`${id}-title`}
|
||||
aria-describedby={`${id}-help`}
|
||||
>
|
||||
<defs>
|
||||
<marker
|
||||
id={`${id}-arrow`}
|
||||
viewBox="0 0 10 10"
|
||||
refX="9"
|
||||
refY="5"
|
||||
markerWidth="6"
|
||||
markerHeight="6"
|
||||
orient="auto"
|
||||
>
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" className="assistant-topology-arrow" />
|
||||
</marker>
|
||||
</defs>
|
||||
{layout.edges.map((edge, index) => (
|
||||
<g key={`edge-${index}`}>
|
||||
<polyline
|
||||
points={edge.points.map((point) => `${point.x},${point.y}`).join(" ")}
|
||||
fill="none"
|
||||
className="assistant-topology-edge"
|
||||
strokeDasharray={edge.relation === "refutes" ? "5 4" : undefined}
|
||||
markerEnd={`url(#${id}-arrow)`}
|
||||
/>
|
||||
<text x={edge.labelX} y={edge.labelY - 4} textAnchor="middle" className="assistant-topology-edge-label">
|
||||
{edge.label || RELATION[edge.relation] || ""}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
{layout.nodes.map((node) => {
|
||||
const label = Array.from(node.label);
|
||||
const lines = [label.slice(0, 13).join(""), label.slice(13, 25).join("") + (label.length > 25 ? "…" : "")];
|
||||
const state = STATUS[node.status];
|
||||
return (
|
||||
<g
|
||||
key={node.id}
|
||||
transform={`translate(${node.x},${node.y})`}
|
||||
className={`assistant-topology-node status-${node.status}`}
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
aria-label={`${node.label},${KIND[node.kind]},${state.label}${node.detail ? `,${node.detail}` : ""}`}
|
||||
aria-pressed={selected === node.id}
|
||||
onMouseEnter={() => setHovered(node.id)}
|
||||
onMouseLeave={() => setHovered(null)}
|
||||
onFocus={() => setHovered(node.id)}
|
||||
onBlur={() => setHovered(null)}
|
||||
onClick={() => setSelected(selected === node.id ? null : node.id)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
setSelected(selected === node.id ? null : node.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<title>
|
||||
{node.label}
|
||||
{node.detail ? `\n${node.detail}` : ""}
|
||||
</title>
|
||||
<rect width={node.width} height={node.height} rx="8" className="assistant-topology-node-box" />
|
||||
<circle cx={14} cy={node.height - 16} r={4} className="assistant-topology-node-status" />
|
||||
<text x={12} y={23} className="assistant-topology-node-label">
|
||||
<tspan x={12}>{lines[0]}</tspan>
|
||||
{lines[1] && (
|
||||
<tspan x={12} dy={18}>
|
||||
{lines[1]}
|
||||
</tspan>
|
||||
)}
|
||||
</text>
|
||||
<text x={24} y={node.height - 12} className="assistant-topology-node-meta">
|
||||
{KIND[node.kind]} {state.symbol} {state.label}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
</div>
|
||||
<div className="assistant-topology-detail" id={`${id}-help`} aria-live="polite">
|
||||
{active ? (
|
||||
<>
|
||||
<strong>{active.label}</strong>:{active.detail || `${KIND[active.kind]},${STATUS[active.status].label}`}
|
||||
</>
|
||||
) : topology.edges.length ? (
|
||||
"悬停、点击或用 Tab 选择节点,查看完整信息。"
|
||||
) : (
|
||||
"仅显示已提供的节点;数据没有连线,未推测对象之间的关系。"
|
||||
)}
|
||||
</div>
|
||||
<details className="assistant-topology-data">
|
||||
<summary>查看节点和连线数据</summary>
|
||||
<div className="assistant-table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>节点</th>
|
||||
<th>类型</th>
|
||||
<th>状态</th>
|
||||
<th>说明</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{topology.nodes.map((node) => (
|
||||
<tr key={node.id}>
|
||||
<td>{node.label}</td>
|
||||
<td>{KIND[node.kind]}</td>
|
||||
<td>{STATUS[node.status].label}</td>
|
||||
<td>{node.detail || "—"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{topology.edges.length > 0 && (
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>起点</th>
|
||||
<th>关系</th>
|
||||
<th>终点</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{topology.edges.map((edge, index) => (
|
||||
<tr key={index}>
|
||||
<td>{names.get(edge.from)}</td>
|
||||
<td>{edge.label || RELATION[edge.relation] || "关联"}</td>
|
||||
<td>{names.get(edge.to)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</details>
|
||||
</figure>
|
||||
);
|
||||
}
|
||||
289
src/components/assistant/assistant-rich-text.css
Normal file
289
src/components/assistant/assistant-rich-text.css
Normal file
@ -0,0 +1,289 @@
|
||||
.assistant-rich-text {
|
||||
--assistant-surface: #151619;
|
||||
--assistant-canvas: #111214;
|
||||
--assistant-border: #2a2b2f;
|
||||
--assistant-text: #e5e7eb;
|
||||
--assistant-muted: #9ca3af;
|
||||
--assistant-link: #60a5fa;
|
||||
color: var(--assistant-text);
|
||||
font-size: 14px;
|
||||
line-height: 1.75;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.assistant-rich-text > :first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
.assistant-rich-text > :last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.assistant-rich-text :where(p, ul, ol, blockquote, pre, table, figure, .assistant-table-scroll) {
|
||||
margin: 0.75rem 0;
|
||||
}
|
||||
.assistant-rich-text :where(h1, h2, h3, h4, h5, h6) {
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
margin: 1.25rem 0 0.5rem;
|
||||
}
|
||||
.assistant-rich-text h1 {
|
||||
font-size: 1.3rem;
|
||||
}
|
||||
.assistant-rich-text h2 {
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
.assistant-rich-text :where(h3, h4, h5, h6) {
|
||||
font-size: 1rem;
|
||||
}
|
||||
.assistant-rich-text :where(ul, ol) {
|
||||
padding-left: 1.5rem;
|
||||
}
|
||||
.assistant-rich-text ul {
|
||||
list-style: disc;
|
||||
}
|
||||
.assistant-rich-text ol {
|
||||
list-style: decimal;
|
||||
}
|
||||
.assistant-rich-text li {
|
||||
margin: 0.25rem 0;
|
||||
}
|
||||
.assistant-rich-text li > p {
|
||||
margin: 0.25rem 0;
|
||||
}
|
||||
.assistant-rich-text .contains-task-list {
|
||||
list-style: none;
|
||||
padding-left: 0.25rem;
|
||||
}
|
||||
.assistant-rich-text .task-list-item input {
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
.assistant-rich-text strong {
|
||||
font-weight: 650;
|
||||
}
|
||||
.assistant-rich-text em {
|
||||
font-style: italic;
|
||||
}
|
||||
.assistant-rich-text a {
|
||||
color: var(--assistant-link);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
.assistant-rich-text blockquote {
|
||||
border-left: 3px solid #64748b;
|
||||
padding-left: 1rem;
|
||||
color: var(--assistant-muted);
|
||||
}
|
||||
.assistant-rich-text hr {
|
||||
border: 0;
|
||||
border-top: 1px solid var(--assistant-border);
|
||||
margin: 1rem 0;
|
||||
}
|
||||
.assistant-rich-text :where(pre, code) {
|
||||
font-family: ui-monospace, SFMono-Regular, Consolas, monospace;
|
||||
font-size: 0.86em;
|
||||
}
|
||||
.assistant-rich-text :not(pre) > code {
|
||||
background: var(--assistant-canvas);
|
||||
border-radius: 4px;
|
||||
padding: 0.15em 0.3em;
|
||||
}
|
||||
.assistant-rich-text pre {
|
||||
background: var(--assistant-canvas);
|
||||
border: 1px solid var(--assistant-border);
|
||||
border-radius: 6px;
|
||||
padding: 0.75rem;
|
||||
overflow: auto;
|
||||
white-space: pre;
|
||||
max-width: 100%;
|
||||
max-height: 24rem;
|
||||
}
|
||||
.assistant-rich-text pre code {
|
||||
font-size: inherit;
|
||||
}
|
||||
.assistant-rich-text table {
|
||||
border-collapse: collapse;
|
||||
font-size: 0.9em;
|
||||
text-align: left;
|
||||
min-width: 100%;
|
||||
}
|
||||
.assistant-rich-text :where(th, td) {
|
||||
border-bottom: 1px solid var(--assistant-border);
|
||||
padding: 0.5rem 0.75rem;
|
||||
vertical-align: top;
|
||||
}
|
||||
.assistant-rich-text th {
|
||||
background: var(--assistant-canvas);
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.assistant-rich-text .assistant-table-scroll {
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.assistant-rich-text .assistant-response-warning {
|
||||
border-left: 3px solid #facc15;
|
||||
padding-left: 0.75rem;
|
||||
}
|
||||
.assistant-rich-text .assistant-diagram-error {
|
||||
padding: 0.75rem;
|
||||
border: 1px solid var(--assistant-border);
|
||||
border-left: 3px solid #facc15;
|
||||
margin: 1rem 0;
|
||||
}
|
||||
.assistant-rich-text .assistant-diagram-error :where(p, summary) {
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.assistant-rich-text summary {
|
||||
cursor: pointer;
|
||||
color: var(--assistant-muted);
|
||||
}
|
||||
.assistant-rich-text :where(a, button, summary, [tabindex]):focus-visible {
|
||||
outline: 2px solid var(--assistant-link);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
.assistant-rich-text .assistant-topology {
|
||||
border: 1px solid var(--assistant-border);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: var(--assistant-canvas);
|
||||
}
|
||||
.assistant-topology-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
padding: 0.65rem 0.75rem 0.25rem;
|
||||
}
|
||||
.assistant-topology-header figcaption {
|
||||
font-weight: 600;
|
||||
}
|
||||
.assistant-topology-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
font-size: 11px;
|
||||
}
|
||||
.assistant-topology-controls button {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border: 1px solid var(--assistant-border);
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.assistant-topology-controls button:hover {
|
||||
background: var(--assistant-surface);
|
||||
}
|
||||
.assistant-topology-controls button:disabled {
|
||||
opacity: 0.35;
|
||||
cursor: default;
|
||||
}
|
||||
.assistant-topology-controls span {
|
||||
min-width: 36px;
|
||||
text-align: center;
|
||||
}
|
||||
.assistant-topology-legend {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.8rem;
|
||||
padding: 0.25rem 0.75rem;
|
||||
font-size: 11px;
|
||||
color: var(--assistant-muted);
|
||||
}
|
||||
.assistant-topology-legend span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
.assistant-status-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--status-color);
|
||||
}
|
||||
.assistant-topology .status-ok {
|
||||
--status-color: #4ade80;
|
||||
}
|
||||
.assistant-topology .status-warning {
|
||||
--status-color: #facc15;
|
||||
}
|
||||
.assistant-topology .status-error {
|
||||
--status-color: #f87171;
|
||||
}
|
||||
.assistant-topology .status-unknown {
|
||||
--status-color: #94a3b8;
|
||||
}
|
||||
.assistant-topology-viewport {
|
||||
overflow: auto;
|
||||
max-height: 480px;
|
||||
max-width: 100%;
|
||||
}
|
||||
.assistant-topology-viewport svg {
|
||||
display: block;
|
||||
max-width: none;
|
||||
}
|
||||
.assistant-topology-edge {
|
||||
stroke: #94a3b8;
|
||||
stroke-width: 2;
|
||||
}
|
||||
.assistant-topology-arrow {
|
||||
fill: #94a3b8;
|
||||
}
|
||||
.assistant-topology-edge-label {
|
||||
fill: var(--assistant-text);
|
||||
font-size: 11px;
|
||||
paint-order: stroke;
|
||||
stroke: var(--assistant-canvas);
|
||||
stroke-width: 4px;
|
||||
}
|
||||
.assistant-topology-node {
|
||||
cursor: pointer;
|
||||
}
|
||||
.assistant-topology-node-box {
|
||||
fill: var(--assistant-surface);
|
||||
stroke: #64748b;
|
||||
stroke-width: 1;
|
||||
}
|
||||
.assistant-topology-node:is(:hover, :focus, [aria-pressed="true"]) .assistant-topology-node-box {
|
||||
stroke: var(--assistant-link);
|
||||
stroke-width: 2;
|
||||
}
|
||||
.assistant-topology-node-status {
|
||||
fill: var(--status-color);
|
||||
}
|
||||
.assistant-topology-node-label {
|
||||
fill: var(--assistant-text);
|
||||
font-size: 13px;
|
||||
}
|
||||
.assistant-topology-node-meta {
|
||||
fill: var(--assistant-muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
.assistant-topology-detail {
|
||||
font-size: 12px;
|
||||
padding: 0.5rem 0.75rem;
|
||||
min-height: 44px;
|
||||
border-top: 1px solid var(--assistant-border);
|
||||
color: var(--assistant-muted);
|
||||
}
|
||||
.assistant-topology-data {
|
||||
border-top: 1px solid var(--assistant-border);
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 12px;
|
||||
}
|
||||
@media (forced-colors: active) {
|
||||
.assistant-topology-node-box {
|
||||
fill: Canvas;
|
||||
stroke: CanvasText;
|
||||
}
|
||||
.assistant-topology :where(text, circle, path) {
|
||||
fill: CanvasText;
|
||||
}
|
||||
.assistant-topology-edge {
|
||||
stroke: CanvasText;
|
||||
}
|
||||
}
|
||||
@ -157,8 +157,16 @@ export function summarizeStep(step, action) {
|
||||
return `${title}已返回:${keys.join("、")}。`;
|
||||
}
|
||||
}
|
||||
if (typeof step.output === "string" && step.output.trim() && !step.output.trim().startsWith("{") && !step.output.trim().startsWith("[")) {
|
||||
const first = step.output.trim().split("\n").find((line) => line.trim());
|
||||
if (
|
||||
typeof step.output === "string" &&
|
||||
step.output.trim() &&
|
||||
!step.output.trim().startsWith("{") &&
|
||||
!step.output.trim().startsWith("[")
|
||||
) {
|
||||
const first = step.output
|
||||
.trim()
|
||||
.split("\n")
|
||||
.find((line) => line.trim());
|
||||
return first ? `${title}完成。${first.slice(0, 120)}` : `${title}已完成。`;
|
||||
}
|
||||
return step.httpStatus ? `${title}完成(HTTP ${step.httpStatus})。` : `${title}已完成。`;
|
||||
@ -202,6 +210,11 @@ export function buildTimeline(transcript) {
|
||||
.map((message) => [message.toolCallId, message.content]),
|
||||
);
|
||||
const placed = new Set();
|
||||
/** @type {Array<
|
||||
* {kind: 'message' | 'command', key: string, message: import('../services/api/assistant').AssistantMessage} |
|
||||
* {kind: 'step', key: string, step: import('../services/api/assistant').AssistantStep} |
|
||||
* {kind: 'refused-call', key: string, call: import('../services/api/assistant').AssistantToolCall, reason: string}
|
||||
* >} */
|
||||
const items = [];
|
||||
const placeStep = (step) => {
|
||||
if (step && !placed.has(step.id)) {
|
||||
@ -218,7 +231,7 @@ export function buildTimeline(transcript) {
|
||||
placeStep(stepsById.get(message.stepId));
|
||||
continue;
|
||||
}
|
||||
if (message.content.trim() || String(message.reasoning || "").trim()) {
|
||||
if (message.content.trim() || String(message.reasoning || "").trim() || message.finishReason === "length") {
|
||||
items.push({ kind: "message", key: message.id, message });
|
||||
}
|
||||
for (const call of message.toolCalls || []) {
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
/** Untrusted model output: every field is checked, nothing is rendered as HTML, size is bounded. */
|
||||
import dagre from "dagre";
|
||||
|
||||
/** Model output is untrusted; incomplete graphs are never repaired with invented nodes or edges. */
|
||||
export const NODE_KINDS = [
|
||||
"cloud",
|
||||
"cluster",
|
||||
@ -23,216 +24,245 @@ export const NODE_KINDS = [
|
||||
"rejected",
|
||||
"other",
|
||||
];
|
||||
|
||||
export const NODE_STATUSES = ["ok", "warning", "error", "unknown"];
|
||||
export const RELATIONS = ["causes", "supports", "refutes", "contains"];
|
||||
export const TOPOLOGY_LIMITS = { nodes: 60, edges: 120, source: 128_000, id: 64, label: 40, detail: 160, title: 60 };
|
||||
|
||||
const LIMITS = { nodes: 60, edges: 120, label: 40, detail: 160, title: 60 };
|
||||
const TOPOLOGY_LANGUAGES = new Set(["ops-topology", "rca-topology", "diagnostic-topology", "topology"]);
|
||||
const JSON_LANGUAGES = new Set(["", "json", "application/json"]);
|
||||
const isRecord = (value) => Boolean(value && typeof value === "object" && !Array.isArray(value));
|
||||
const validText = (value) => typeof value === "string" && value.trim() && !/[\u0000-\u001f\u007f]/.test(value);
|
||||
const text = (value, limit) => (validText(value) ? [...value.trim()].slice(0, limit).join("") : undefined);
|
||||
const idText = (value) =>
|
||||
validText(value) && [...value.trim()].length <= TOPOLOGY_LIMITS.id ? value.trim() : undefined;
|
||||
|
||||
function text(value, max) {
|
||||
if (typeof value !== "string" || !value.trim() || /[\u0000-\u001f\u007f]/.test(value)) {
|
||||
return undefined;
|
||||
}
|
||||
return [...value.trim()].slice(0, max).join("");
|
||||
// A list of business records with IDs is NOT a diagram. Bare arrays must carry diagram-specific fields.
|
||||
function isTopologyNode(value) {
|
||||
return (
|
||||
isRecord(value) &&
|
||||
validText(value.id) &&
|
||||
validText(value.label) &&
|
||||
NODE_KINDS.includes(value.kind) &&
|
||||
NODE_STATUSES.includes(value.status)
|
||||
);
|
||||
}
|
||||
|
||||
function pick(value, allowed, fallback) {
|
||||
return allowed.includes(value) ? value : fallback;
|
||||
function looksLikeTopology(value) {
|
||||
return (
|
||||
(isRecord(value) && Array.isArray(value.nodes)) ||
|
||||
(Array.isArray(value) && value.length > 0 && value.every(isTopologyNode))
|
||||
);
|
||||
}
|
||||
|
||||
// Recognize interrupted graph output without treating generic JSON or a list of projects as a graph.
|
||||
function startsTopology(source) {
|
||||
return (
|
||||
/^\s*\{\s*(?:"title"\s*:\s*"(?:[^"\\]|\\.)*"\s*,\s*)?"nodes"\s*:/u.test(source) ||
|
||||
/^\s*\[\s*\{[^{}]*"label"\s*:[^{}]*"kind"\s*:[^{}]*"status"\s*:/u.test(source)
|
||||
);
|
||||
}
|
||||
|
||||
export function parseTopology(source) {
|
||||
if (typeof source !== "string" || source.length > TOPOLOGY_LIMITS.source) {
|
||||
return { ok: false, reason: "拓扑数据过大,请只画重点对象" };
|
||||
}
|
||||
let raw;
|
||||
try {
|
||||
raw = JSON.parse(source);
|
||||
} catch {
|
||||
return { ok: false, reason: "拓扑数据不是有效的 JSON" };
|
||||
return { ok: false, reason: "拓扑数据不完整或 JSON 格式有误,请让助手重新输出完整的简化拓扑" };
|
||||
}
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
||||
if (Array.isArray(raw) && raw.length > 0 && raw.every(isTopologyNode)) {
|
||||
raw = { nodes: raw, edges: [] };
|
||||
}
|
||||
if (!isRecord(raw)) {
|
||||
return { ok: false, reason: "拓扑数据格式不正确" };
|
||||
}
|
||||
if (!Array.isArray(raw.nodes) || !raw.nodes.length) {
|
||||
return { ok: false, reason: "拓扑中没有节点" };
|
||||
}
|
||||
if (raw.nodes.length > LIMITS.nodes) {
|
||||
return { ok: false, reason: `节点超过 ${LIMITS.nodes} 个` };
|
||||
if (raw.nodes.length > TOPOLOGY_LIMITS.nodes) {
|
||||
return { ok: false, reason: `节点超过 ${TOPOLOGY_LIMITS.nodes} 个,请让助手聚合后重画` };
|
||||
}
|
||||
const edgesIn = Array.isArray(raw.edges) ? raw.edges : [];
|
||||
if (edgesIn.length > LIMITS.edges) {
|
||||
return { ok: false, reason: `连线超过 ${LIMITS.edges} 条` };
|
||||
if (raw.edges !== undefined && !Array.isArray(raw.edges)) {
|
||||
return { ok: false, reason: "拓扑连线必须是数组" };
|
||||
}
|
||||
const edgesIn = raw.edges || [];
|
||||
if (edgesIn.length > TOPOLOGY_LIMITS.edges) {
|
||||
return { ok: false, reason: `连线超过 ${TOPOLOGY_LIMITS.edges} 条` };
|
||||
}
|
||||
const nodes = [];
|
||||
const seen = new Set();
|
||||
for (const value of raw.nodes) {
|
||||
const item = value && typeof value === "object" ? value : {};
|
||||
const id = text(item.id, 64);
|
||||
const label = text(item.label, LIMITS.label) ?? id;
|
||||
for (const item of raw.nodes) {
|
||||
const id = idText(item?.id);
|
||||
const label = text(item?.label, TOPOLOGY_LIMITS.label);
|
||||
if (!id || !label || seen.has(id)) {
|
||||
return { ok: false, reason: "节点缺少 ID 或 ID 重复" };
|
||||
return { ok: false, reason: "节点缺少名称、ID 无效或重复" };
|
||||
}
|
||||
seen.add(id);
|
||||
nodes.push({
|
||||
id,
|
||||
label,
|
||||
kind: pick(item.kind, NODE_KINDS, "other"),
|
||||
status: pick(item.status, NODE_STATUSES, "unknown"),
|
||||
detail: text(item.detail, LIMITS.detail),
|
||||
kind: NODE_KINDS.includes(item.kind) ? item.kind : "other",
|
||||
status: NODE_STATUSES.includes(item.status) ? item.status : "unknown",
|
||||
detail: text(item.detail, TOPOLOGY_LIMITS.detail),
|
||||
});
|
||||
}
|
||||
const edges = [];
|
||||
const pairs = new Set();
|
||||
for (const value of edgesIn) {
|
||||
const item = value && typeof value === "object" ? value : {};
|
||||
const from = text(item.from, 64);
|
||||
const to = text(item.to, 64);
|
||||
if (!from || !to || from === to || !seen.has(from) || !seen.has(to) || pairs.has(`${from}\0${to}`)) {
|
||||
for (const item of edgesIn) {
|
||||
const from = idText(item?.from);
|
||||
const to = idText(item?.to);
|
||||
if (!from || !to || !seen.has(from) || !seen.has(to)) {
|
||||
return { ok: false, reason: "拓扑连线引用了不存在的节点" };
|
||||
}
|
||||
const relation = RELATIONS.includes(item.relation) ? item.relation : undefined;
|
||||
const label = text(item.label, 24);
|
||||
const key = JSON.stringify([from, to, relation, label]);
|
||||
if (pairs.has(key)) continue;
|
||||
pairs.add(key);
|
||||
edges.push({ from, to, relation, label });
|
||||
}
|
||||
return { ok: true, topology: { title: text(raw.title, TOPOLOGY_LIMITS.title), nodes, edges } };
|
||||
}
|
||||
|
||||
/** Dagre is already used by the workflow editor; it also handles cycles and disconnected nodes. */
|
||||
export function layoutTopology(topology) {
|
||||
const width = 208;
|
||||
const height = 84;
|
||||
const padding = 24;
|
||||
if (!topology.edges.length) {
|
||||
const columns = Math.min(3, topology.nodes.length);
|
||||
const nodes = topology.nodes.map((node, index) => ({
|
||||
...node,
|
||||
width,
|
||||
height,
|
||||
x: padding + (index % columns) * (width + 24),
|
||||
y: padding + Math.floor(index / columns) * (height + 24),
|
||||
}));
|
||||
return {
|
||||
nodes,
|
||||
edges: [],
|
||||
width: columns * (width + 24) + 24,
|
||||
height: Math.ceil(nodes.length / columns) * (height + 24) + 24,
|
||||
};
|
||||
}
|
||||
const graph = new dagre.graphlib.Graph({ multigraph: true })
|
||||
.setGraph({ rankdir: "LR", marginx: padding, marginy: padding, ranksep: 92, nodesep: 32 })
|
||||
.setDefaultEdgeLabel(() => ({}));
|
||||
// Keep user IDs out of graphlib's object keys (e.g. "__proto__" is a valid external ID).
|
||||
const ids = new Map(topology.nodes.map((node, index) => [node.id, `node-${index}`]));
|
||||
for (const node of topology.nodes) graph.setNode(ids.get(node.id), { width, height });
|
||||
topology.edges.forEach((edge, index) =>
|
||||
graph.setEdge(ids.get(edge.from), ids.get(edge.to), { width: 70, height: 16 }, String(index)),
|
||||
);
|
||||
dagre.layout(graph);
|
||||
return {
|
||||
nodes: topology.nodes.map((node) => {
|
||||
const placed = graph.node(ids.get(node.id));
|
||||
return { ...node, width, height, x: placed.x - width / 2, y: placed.y - height / 2 };
|
||||
}),
|
||||
edges: topology.edges.map((edge, index) => {
|
||||
const placed = graph.edge({ v: ids.get(edge.from), w: ids.get(edge.to), name: String(index) });
|
||||
return { ...edge, points: placed.points, labelX: placed.x, labelY: placed.y };
|
||||
}),
|
||||
width: graph.graph().width,
|
||||
height: graph.graph().height,
|
||||
};
|
||||
}
|
||||
|
||||
// A balanced scan understands strings/escapes and both bracket types; it never fishes nodes out
|
||||
// of a truncated outer object or promotes nested application JSON to an unrelated graph.
|
||||
function jsonEnd(source, start) {
|
||||
const stack = [];
|
||||
let quoted = false;
|
||||
let escaped = false;
|
||||
for (let index = start; index < source.length; index += 1) {
|
||||
const char = source[index];
|
||||
if (quoted) {
|
||||
if (escaped) escaped = false;
|
||||
else if (char === "\\") escaped = true;
|
||||
else if (char === '"') quoted = false;
|
||||
continue;
|
||||
}
|
||||
pairs.add(`${from}\0${to}`);
|
||||
edges.push({
|
||||
from,
|
||||
to,
|
||||
label: text(item.label, 24),
|
||||
relation: RELATIONS.includes(item.relation) ? item.relation : undefined,
|
||||
});
|
||||
if (char === '"') quoted = true;
|
||||
else if (char === "{" || char === "[") stack.push(char === "{" ? "}" : "]");
|
||||
else if (char === "}" || char === "]") {
|
||||
if (stack.pop() !== char) return { end: index + 1, complete: false };
|
||||
if (!stack.length) return { end: index + 1, complete: true };
|
||||
}
|
||||
}
|
||||
return { ok: true, topology: { title: text(raw.title, LIMITS.title), nodes, edges } };
|
||||
return { end: source.length, complete: false };
|
||||
}
|
||||
|
||||
export function layoutTopology(topology) {
|
||||
const incoming = new Map(topology.nodes.map((node) => [node.id, 0]));
|
||||
for (const edge of topology.edges) {
|
||||
incoming.set(edge.to, (incoming.get(edge.to) || 0) + 1);
|
||||
function topologySource(source) {
|
||||
try {
|
||||
return looksLikeTopology(JSON.parse(source));
|
||||
} catch {
|
||||
return startsTopology(source);
|
||||
}
|
||||
const layers = new Map();
|
||||
const queue = topology.nodes.filter((node) => (incoming.get(node.id) || 0) === 0).map((node) => node.id);
|
||||
if (!queue.length) {
|
||||
queue.push(topology.nodes[0].id);
|
||||
}
|
||||
const remaining = new Map(incoming);
|
||||
while (queue.length) {
|
||||
const id = queue.shift();
|
||||
const layer = layers.get(id) || 0;
|
||||
for (const edge of topology.edges) {
|
||||
if (edge.from !== id) {
|
||||
}
|
||||
|
||||
/** Split Markdown and diagrams in source order. Leave ordinary code and inline JSON alone. */
|
||||
export function splitRichContent(markdown) {
|
||||
const value = String(markdown || "");
|
||||
/** @type {Array<{type: 'markdown', text: string} | {type: 'topology', source: string}>} */
|
||||
const parts = [];
|
||||
const pushMarkdown = (source) => {
|
||||
const last = parts[parts.length - 1];
|
||||
if (last?.type === "markdown") last.text += source;
|
||||
else if (source.trim()) parts.push({ type: "markdown", text: source });
|
||||
};
|
||||
const pushPlain = (source) => {
|
||||
// Only promote standalone JSON blocks; inline examples and Markdown links remain Markdown.
|
||||
const candidates = /^ {0,3}(?=[{[])/gm;
|
||||
let cursor = 0;
|
||||
let match;
|
||||
while ((match = candidates.exec(source))) {
|
||||
const start = match.index + match[0].length;
|
||||
if (!/^(?:\{\s*"|\[\s*\{)/.test(source.slice(start))) {
|
||||
candidates.lastIndex = start + 1;
|
||||
continue;
|
||||
}
|
||||
layers.set(edge.to, Math.max(layers.get(edge.to) || 0, layer + 1));
|
||||
remaining.set(edge.to, (remaining.get(edge.to) || 1) - 1);
|
||||
if (remaining.get(edge.to) === 0) {
|
||||
queue.push(edge.to);
|
||||
const scanned = jsonEnd(source, start);
|
||||
const candidate = source.slice(start, scanned.end);
|
||||
if (topologySource(candidate)) {
|
||||
pushMarkdown(source.slice(cursor, start));
|
||||
parts.push({ type: "topology", source: candidate });
|
||||
cursor = scanned.end;
|
||||
}
|
||||
candidates.lastIndex = Math.max(scanned.end, start + 1);
|
||||
}
|
||||
if (!layers.has(id)) {
|
||||
layers.set(id, layer);
|
||||
pushMarkdown(source.slice(cursor));
|
||||
};
|
||||
|
||||
const opening = /^ {0,3}(`{3,}|~{3,})([^\r\n]*)\r?$/gm;
|
||||
let cursor = 0;
|
||||
let match;
|
||||
while ((match = opening.exec(value))) {
|
||||
if (match.index < cursor) continue;
|
||||
pushPlain(value.slice(cursor, match.index));
|
||||
const marker = match[1][0];
|
||||
const language = match[2].trim().split(/\s+/)[0].toLowerCase();
|
||||
const bodyStart = match.index + match[0].length + (value[match.index + match[0].length] === "\n" ? 1 : 0);
|
||||
const closing = new RegExp(`^ {0,3}${marker}{${match[1].length},}[ \\t]*\\r?$`, "gm");
|
||||
closing.lastIndex = bodyStart;
|
||||
const end = closing.exec(value);
|
||||
const body = value.slice(bodyStart, end ? end.index : value.length).trim();
|
||||
cursor = end ? end.index + end[0].length : value.length;
|
||||
if (TOPOLOGY_LANGUAGES.has(language) || (JSON_LANGUAGES.has(language) && topologySource(body))) {
|
||||
parts.push({ type: "topology", source: body });
|
||||
} else {
|
||||
pushMarkdown(value.slice(match.index, cursor));
|
||||
}
|
||||
opening.lastIndex = cursor;
|
||||
}
|
||||
for (const node of topology.nodes) {
|
||||
if (!layers.has(node.id)) {
|
||||
layers.set(node.id, 0);
|
||||
}
|
||||
}
|
||||
const columns = [];
|
||||
for (const node of topology.nodes) {
|
||||
const layer = layers.get(node.id) || 0;
|
||||
(columns[layer] || (columns[layer] = [])).push(node);
|
||||
}
|
||||
const width = 160;
|
||||
const height = 56;
|
||||
const gapX = 48;
|
||||
const gapY = 28;
|
||||
const placed = [];
|
||||
const byId = new Map();
|
||||
columns.forEach((column, x) => {
|
||||
column.forEach((node, y) => {
|
||||
const item = {
|
||||
...node,
|
||||
x: 24 + x * (width + gapX),
|
||||
y: 24 + y * (height + gapY),
|
||||
width,
|
||||
height,
|
||||
};
|
||||
placed.push(item);
|
||||
byId.set(node.id, item);
|
||||
});
|
||||
});
|
||||
const lines = topology.edges
|
||||
.map((edge) => {
|
||||
const from = byId.get(edge.from);
|
||||
const to = byId.get(edge.to);
|
||||
if (!from || !to) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
...edge,
|
||||
x1: from.x + from.width,
|
||||
y1: from.y + from.height / 2,
|
||||
x2: to.x,
|
||||
y2: to.y + to.height / 2,
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
const maxX = Math.max(...placed.map((node) => node.x + node.width), 320);
|
||||
const maxY = Math.max(...placed.map((node) => node.y + node.height), 120);
|
||||
return { nodes: placed, edges: lines, width: maxX + 24, height: maxY + 24 };
|
||||
}
|
||||
|
||||
const STATUS_FILL = {
|
||||
ok: "#14532d",
|
||||
warning: "#854d0e",
|
||||
error: "#7f1d1d",
|
||||
unknown: "#1f2937",
|
||||
};
|
||||
|
||||
const STATUS_STROKE = {
|
||||
ok: "#4ade80",
|
||||
warning: "#facc15",
|
||||
error: "#f87171",
|
||||
unknown: "#64748b",
|
||||
};
|
||||
|
||||
export function topologySvg(layout, title) {
|
||||
const nodes = layout.nodes
|
||||
.map((node) => {
|
||||
const fill = STATUS_FILL[node.status] || STATUS_FILL.unknown;
|
||||
const stroke = STATUS_STROKE[node.status] || STATUS_STROKE.unknown;
|
||||
const detail = node.detail ? `\n${escapeXml(node.detail)}` : "";
|
||||
return `<g>
|
||||
<rect x="${node.x}" y="${node.y}" width="${node.width}" height="${node.height}" rx="10" fill="${fill}" stroke="${stroke}"/>
|
||||
<text x="${node.x + 12}" y="${node.y + 22}" fill="#e5e7eb" font-size="12">${escapeXml(node.label)}</text>
|
||||
<text x="${node.x + 12}" y="${node.y + 40}" fill="#94a3b8" font-size="10">${escapeXml(node.kind)}${detail ? "" : ""}</text>
|
||||
<title>${escapeXml(node.label)}${detail}</title>
|
||||
</g>`;
|
||||
})
|
||||
.join("");
|
||||
const edges = layout.edges
|
||||
.map(
|
||||
(edge) =>
|
||||
`<line x1="${edge.x1}" y1="${edge.y1}" x2="${edge.x2}" y2="${edge.y2}" stroke="#64748b" stroke-width="1.5" marker-end="url(#arrow)"/>`,
|
||||
)
|
||||
.join("");
|
||||
const heading = title
|
||||
? `<text x="24" y="16" fill="#cbd5e1" font-size="12">${escapeXml(title)}</text>`
|
||||
: "";
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${layout.width} ${layout.height + (title ? 8 : 0)}" width="100%" role="img">
|
||||
<defs><marker id="arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="#64748b"/></marker></defs>
|
||||
${heading}${edges}${nodes}
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
function escapeXml(value) {
|
||||
return String(value)
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """);
|
||||
pushPlain(value.slice(cursor));
|
||||
return parts;
|
||||
}
|
||||
|
||||
export function extractTopologyBlocks(markdown) {
|
||||
const blocks = [];
|
||||
const pattern = /```(?:rca-topology|ops-topology|topology)\n([\s\S]*?)```/g;
|
||||
let match;
|
||||
while ((match = pattern.exec(markdown || ""))) {
|
||||
blocks.push(match[1].trim());
|
||||
}
|
||||
return blocks;
|
||||
return splitRichContent(markdown)
|
||||
.filter((part) => part.type === "topology")
|
||||
.map((part) => part.source);
|
||||
}
|
||||
|
||||
@ -142,6 +142,7 @@ export function effectiveWorkflowScheduleMode(schedule) {
|
||||
return "";
|
||||
}
|
||||
|
||||
/** @returns {import('../types').WorkflowSchedule} */
|
||||
export function normalizeWorkflowSchedule(schedule = {}) {
|
||||
const mode = effectiveWorkflowScheduleMode(schedule);
|
||||
const next = {
|
||||
@ -177,6 +178,7 @@ export function isWorkflowScheduleEnabled(schedule) {
|
||||
}
|
||||
}
|
||||
|
||||
/** @returns {import('../types').WorkflowSchedule} */
|
||||
export function buildScheduledWorkflowSchedule(existingSchedule = {}, mode = "") {
|
||||
const normalized = normalizeWorkflowSchedule(existingSchedule);
|
||||
const targetMode = mode || effectiveWorkflowScheduleMode(normalized) || "interval_seconds";
|
||||
|
||||
@ -25,7 +25,7 @@ import {
|
||||
summarizeStep,
|
||||
transcriptNeedsPolling,
|
||||
} from "../lib/assistant-commands.js";
|
||||
import { extractTopologyBlocks, layoutTopology, parseTopology, topologySvg } from "../lib/assistant-topology.js";
|
||||
import { AssistantRichText } from "../components/assistant/AssistantRichText";
|
||||
import { OPS_TIER_LABELS } from "../lib/ops-catalog.generated";
|
||||
import {
|
||||
assistantApi,
|
||||
@ -142,52 +142,6 @@ function StepCard({
|
||||
);
|
||||
}
|
||||
|
||||
function TopologyFigure({ source }: { source: string }) {
|
||||
const parsed = parseTopology(source);
|
||||
if (!parsed.ok) {
|
||||
return <p className="text-xs text-amber-300">拓扑无法显示:{parsed.reason}</p>;
|
||||
}
|
||||
const layout = layoutTopology(parsed.topology);
|
||||
return (
|
||||
<figure className="my-3 overflow-x-auto rounded-xl border border-[#2a2b2f] bg-[#0d0e10] p-3">
|
||||
{parsed.topology.title ? <figcaption className="mb-2 text-xs text-gray-400">{parsed.topology.title}</figcaption> : null}
|
||||
<div dangerouslySetInnerHTML={{ __html: topologySvg(layout, "") }} />
|
||||
</figure>
|
||||
);
|
||||
}
|
||||
|
||||
function AssistantRichText({ text }: { text: string }) {
|
||||
const parts = [];
|
||||
const pattern = /```(?:rca-topology|ops-topology|topology)\n([\s\S]*?)```/g;
|
||||
let last = 0;
|
||||
let match;
|
||||
let index = 0;
|
||||
while ((match = pattern.exec(text))) {
|
||||
if (match.index > last) {
|
||||
parts.push(
|
||||
<div key={`md-${index}`} className="whitespace-pre-wrap">
|
||||
{text.slice(last, match.index).trim()}
|
||||
</div>,
|
||||
);
|
||||
}
|
||||
parts.push(
|
||||
<React.Fragment key={`topo-${index}`}>
|
||||
<TopologyFigure source={match[1]} />
|
||||
</React.Fragment>,
|
||||
);
|
||||
last = match.index + match[0].length;
|
||||
index += 1;
|
||||
}
|
||||
if (last < text.length) {
|
||||
parts.push(
|
||||
<div key="md-tail" className="whitespace-pre-wrap">
|
||||
{text.slice(last).trim()}
|
||||
</div>,
|
||||
);
|
||||
}
|
||||
return <div className="space-y-2">{parts}</div>;
|
||||
}
|
||||
|
||||
function ThinkingBlock({ text }: { text: string }) {
|
||||
return (
|
||||
<details className="mb-2 rounded-lg border border-[#2a2b2f] bg-black/20 px-3 py-2 text-xs text-gray-400">
|
||||
@ -416,14 +370,14 @@ export default function Assistant() {
|
||||
const busy = Boolean(transcript?.session.busy);
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col space-y-4">
|
||||
<div className="flex shrink-0 items-center justify-between">
|
||||
<div>
|
||||
<h1 className="flex items-center gap-3 text-3xl font-bold tracking-tight text-white">
|
||||
<div className="flex h-full min-w-0 flex-col space-y-4">
|
||||
<div className="flex shrink-0 flex-wrap items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h1 className="flex items-center gap-3 text-2xl font-bold tracking-tight text-white sm:text-3xl">
|
||||
<Bot className="h-8 w-8 text-blue-500" />
|
||||
运维助手
|
||||
</h1>
|
||||
<p className="mt-1 text-gray-500">
|
||||
<p className="mt-1 hidden text-sm text-gray-500 sm:block">
|
||||
输入 <code className="text-gray-300">/</code>{" "}
|
||||
直接执行能力目录里的动作,或用自然语言描述问题。权限随你的角色分层,变更类动作默认
|
||||
dry-run,真正执行前需要确认。
|
||||
@ -444,8 +398,22 @@ export default function Assistant() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex min-h-0 flex-1 gap-4">
|
||||
<aside className="w-60 shrink-0 space-y-1 overflow-y-auto rounded-xl border border-[#2a2b2f] bg-[#151619] p-2">
|
||||
{sessions.length > 0 && (
|
||||
<select
|
||||
aria-label="选择对话"
|
||||
value={activeId || ""}
|
||||
onChange={(event) => setActiveId(event.target.value)}
|
||||
className="w-full shrink-0 rounded-lg border border-[#2a2b2f] bg-[#151619] px-3 py-2 text-sm text-gray-200 lg:hidden"
|
||||
>
|
||||
{sessions.map((session) => (
|
||||
<option key={session.id} value={session.id}>
|
||||
{session.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<div className="flex min-h-0 min-w-0 flex-1 gap-4">
|
||||
<aside className="hidden w-60 shrink-0 space-y-1 overflow-y-auto rounded-xl border border-[#2a2b2f] bg-[#151619] p-2 lg:block">
|
||||
{sessions.length === 0 && <p className="p-3 text-xs text-gray-500">还没有对话</p>}
|
||||
{sessions.map((session) => (
|
||||
<div
|
||||
@ -517,13 +485,19 @@ export default function Assistant() {
|
||||
<div key={item.key} className={cn("flex", isUser ? "justify-end" : "justify-start")}>
|
||||
<div
|
||||
className={cn(
|
||||
"max-w-[80%] whitespace-pre-wrap rounded-2xl px-4 py-2.5 text-sm leading-relaxed",
|
||||
isUser ? "bg-blue-600 text-white" : "border border-[#2a2b2f] bg-[#151619] text-gray-200",
|
||||
"min-w-0 rounded-2xl px-4 py-2.5 text-sm leading-relaxed",
|
||||
isUser
|
||||
? "max-w-[80%] whitespace-pre-wrap bg-blue-600 text-white"
|
||||
: "w-full max-w-[min(100%,960px)] border border-[#2a2b2f] bg-[#151619] text-gray-200",
|
||||
item.kind === "command" && "font-mono text-xs",
|
||||
)}
|
||||
>
|
||||
{message.reasoning?.trim() ? <ThinkingBlock text={message.reasoning} /> : null}
|
||||
{isUser ? message.content : <AssistantRichText text={message.content} />}
|
||||
{isUser ? (
|
||||
message.content
|
||||
) : (
|
||||
<AssistantRichText text={message.content} finishReason={message.finishReason} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -1333,17 +1333,17 @@ export default function Monitoring() {
|
||||
<div className="mt-1 text-[10px] font-mono text-gray-500 break-all">
|
||||
{node.nodeId}
|
||||
</div>
|
||||
{(node.operatorId || node.operatorImageID || node.operatorImage) && (
|
||||
{(node.operatorId || node.operatorImageId || node.operatorImage) && (
|
||||
<div className="mt-3 space-y-1 text-[11px] text-gray-400">
|
||||
{node.operatorId && (
|
||||
<div className="break-all">
|
||||
<span className="text-gray-600">operator</span> {node.operatorId}
|
||||
</div>
|
||||
)}
|
||||
{(node.operatorImageID || node.operatorImage) && (
|
||||
{(node.operatorImageId || node.operatorImage) && (
|
||||
<div className="break-all">
|
||||
<span className="text-gray-600">image</span>{" "}
|
||||
{node.operatorImageID || node.operatorImage}
|
||||
{node.operatorImageId || node.operatorImage}
|
||||
</div>
|
||||
)}
|
||||
{node.stageManifestPath && (
|
||||
|
||||
@ -236,6 +236,9 @@ interface OperatorNodeData {
|
||||
businessStage?: DataMetricStage;
|
||||
metricBoundary?: boolean;
|
||||
executionState?: OperatorExecutionState;
|
||||
shuffle?: boolean;
|
||||
distMode?: string;
|
||||
weights?: Record<string, string>;
|
||||
}
|
||||
|
||||
const nodeBusinessStageOptions: Array<{ value: DataMetricStage; label: string }> = [
|
||||
@ -2193,11 +2196,7 @@ export default function WorkflowEditor() {
|
||||
);
|
||||
|
||||
const updateWorkflowHyperparams = useCallback(
|
||||
(
|
||||
updater: (
|
||||
current: Array<{ key?: string; value?: string; [key: string]: any }>,
|
||||
) => Array<{ key?: string; value?: string; [key: string]: any }>,
|
||||
) => {
|
||||
(updater: (current: HyperParam[]) => HyperParam[]) => {
|
||||
if (workflowSettingsReadOnly) {
|
||||
return;
|
||||
}
|
||||
@ -5025,7 +5024,6 @@ export default function WorkflowEditor() {
|
||||
onPaneClick={onPaneClick}
|
||||
nodeTypes={nodeTypes}
|
||||
fitView
|
||||
theme="dark"
|
||||
deleteKeyCode={null}
|
||||
nodesDraggable={!isReadOnly && canManage}
|
||||
nodesConnectable={!isReadOnly && canManage}
|
||||
|
||||
@ -62,7 +62,7 @@ export interface GeneratedOperator {
|
||||
};
|
||||
inputs: { name: string; type: PortType; transmission: PortTransmission; description?: string }[];
|
||||
outputs: { name: string; type: PortType; transmission: PortTransmission; description?: string }[];
|
||||
hyperparams: { key: string; value: string; description?: string; type?: string }[];
|
||||
hyperparams: HyperParam[];
|
||||
skillDefinition: string;
|
||||
publicationStatus?: "draft" | "built" | "verified" | "published";
|
||||
generationSource?: "manual" | "ai";
|
||||
|
||||
@ -36,6 +36,7 @@ export interface AssistantMessage {
|
||||
role: "user" | "assistant" | "tool";
|
||||
content: string;
|
||||
reasoning?: string;
|
||||
finishReason?: string;
|
||||
toolCalls?: AssistantToolCall[];
|
||||
toolCallId?: string;
|
||||
stepId?: string;
|
||||
|
||||
@ -44,6 +44,7 @@ export interface DatabaseIndexSummary {
|
||||
name: string;
|
||||
keys: Record<string, any>;
|
||||
unique?: boolean;
|
||||
sparse?: boolean;
|
||||
}
|
||||
|
||||
export interface DatabaseOverview {
|
||||
@ -354,7 +355,7 @@ export interface OperatorPublicationEvidence {
|
||||
|
||||
export interface WorkflowSchedule {
|
||||
interval: number; // in seconds
|
||||
mode?: "interval_seconds" | "every_hours" | "every_days_at_time";
|
||||
mode?: "" | "interval_seconds" | "every_hours" | "every_days_at_time";
|
||||
intervalHours?: number;
|
||||
dayInterval?: number;
|
||||
timeOfDay?: string;
|
||||
|
||||
@ -81,17 +81,36 @@ test("summarizeStep talks like a reply instead of dumping HTTP status", () => {
|
||||
const action = { title: "项目列表", id: "platform.projects" };
|
||||
assert.equal(
|
||||
summarizeStep(
|
||||
{ actionId: "platform.projects", status: "succeeded", output: JSON.stringify([{ name: "训练A" }, { name: "采集B" }]) },
|
||||
{
|
||||
actionId: "platform.projects",
|
||||
status: "succeeded",
|
||||
output: JSON.stringify([{ name: "训练A" }, { name: "采集B" }]),
|
||||
},
|
||||
action,
|
||||
),
|
||||
"查到共 2 项:训练A、采集B。",
|
||||
);
|
||||
assert.match(
|
||||
summarizeStep({ actionId: "status.health", status: "succeeded", httpStatus: 200, output: JSON.stringify({ status: "ok", service: "droboticflow-api" }) }, { title: "API 健康" }),
|
||||
summarizeStep(
|
||||
{
|
||||
actionId: "status.health",
|
||||
status: "succeeded",
|
||||
httpStatus: 200,
|
||||
output: JSON.stringify({ status: "ok", service: "droboticflow-api" }),
|
||||
},
|
||||
{ title: "API 健康" },
|
||||
),
|
||||
/API 健康:状态 ok/,
|
||||
);
|
||||
});
|
||||
|
||||
test("an empty truncated answer still exposes its completion warning", () => {
|
||||
const message = { id: "limit", role: "assistant", content: "", finishReason: "length" };
|
||||
const timeline = buildTimeline({ session: { busy: false }, messages: [message], steps: [] });
|
||||
assert.equal(timeline.length, 1);
|
||||
assert.equal(timeline[0].message.finishReason, "length");
|
||||
});
|
||||
|
||||
test("stepStatusView labels every status", () => {
|
||||
assert.equal(stepStatusView("pending_confirmation").label, "待确认");
|
||||
assert.equal(stepStatusView("failed").tone, "red");
|
||||
|
||||
225
tests/frontend/assistant-rich-text-browser.mjs
Normal file
225
tests/frontend/assistant-rich-text-browser.mjs
Normal file
@ -0,0 +1,225 @@
|
||||
// Local browser regression with explicit synthetic API fixtures; no real login, model or cluster is contacted.
|
||||
// Start the Vite dev server, then: node tests/frontend/assistant-rich-text-browser.mjs http://127.0.0.1:5191
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { chromium } from "playwright";
|
||||
|
||||
const origin = new URL(process.argv[2] || "http://127.0.0.1:5191");
|
||||
assert.ok(["localhost", "127.0.0.1"].includes(origin.hostname), "Use a local Vite server, never a live deployment");
|
||||
const folder = new URL("../../output/assistant-rendering/", import.meta.url);
|
||||
await mkdir(folder, { recursive: true });
|
||||
const graph = {
|
||||
title: "项目与工作流(测试数据)",
|
||||
nodes: [
|
||||
{
|
||||
id: "project",
|
||||
label: "机器人数据采集项目",
|
||||
kind: "project",
|
||||
status: "ok",
|
||||
detail: "本地合成测试数据,不代表现网状态",
|
||||
},
|
||||
{ id: "collect", label: "视频采集", kind: "workflow", status: "ok" },
|
||||
{ id: "audit", label: "质量审核", kind: "workflow", status: "warning", detail: "等待人工审核" },
|
||||
],
|
||||
edges: [
|
||||
{ from: "project", to: "collect", relation: "contains" },
|
||||
{ from: "collect", to: "audit", relation: "supports", label: "提供数据" },
|
||||
],
|
||||
};
|
||||
const markdown = [
|
||||
"## 项目检查结果",
|
||||
"**采集已完成**,质量审核仍需关注。以下是*本地测试数据*,不是现网查询。",
|
||||
"- 采集:正常\n- 审核:等待确认",
|
||||
"| 工作流 | 状态 |\n| --- | --- |\n| 视频采集 | 正常 |\n| 质量审核 | 待确认 |",
|
||||
"```ops-topology\n" + JSON.stringify(graph) + "\n```",
|
||||
"> 下一步:查看审核任务,不会自动执行变更。",
|
||||
"1. 查看详情\n2. 人工确认",
|
||||
"[项目入口](/projects) · `platform.projects` · ~~旧状态~~",
|
||||
"- [x] 采集完成\n- [ ] 等待审核",
|
||||
'<img src="https://example.invalid/tracker" onerror="window.__injected=true">',
|
||||
"[危险链接](javascript:alert(1))\n\n",
|
||||
].join("\n\n");
|
||||
const now = "2026-11-04T12:00:00Z";
|
||||
const session = {
|
||||
id: "render-fixture",
|
||||
title: "Markdown 与拓扑验收(测试)",
|
||||
busy: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const makeMessage = (id, content, extra = {}) => ({
|
||||
id,
|
||||
role: "assistant",
|
||||
content,
|
||||
seq: Number(id.slice(1)),
|
||||
createdAt: now,
|
||||
...extra,
|
||||
});
|
||||
const responses = {
|
||||
rich: markdown,
|
||||
bare: JSON.stringify(graph),
|
||||
jsonFence: "```json\r\n" + JSON.stringify(graph) + "\r\n```",
|
||||
multiple: JSON.stringify(graph) + "\n\n" + "```ops-topology\n" + JSON.stringify(graph) + "\n```",
|
||||
array: JSON.stringify(graph.nodes),
|
||||
incomplete:
|
||||
'## 已确认的部分\n\n采集状态正常。\n\n```ops-topology\n{"nodes":[{"id":"a","label":"项目","kind":"project","status":"ok"},{"id":"b","label":"未完成',
|
||||
ordinary: '```json\n{"status":"ok","items":[]}\n```',
|
||||
escaped:
|
||||
"```ops-topology\n" +
|
||||
JSON.stringify({
|
||||
nodes: [{ id: 'x"><script>', label: "<script>alert(1)</script>", kind: "project", status: "unknown" }],
|
||||
edges: [],
|
||||
}) +
|
||||
"\n```",
|
||||
};
|
||||
let current = "rich";
|
||||
const errors = [];
|
||||
const requestsOutsideLocal = [];
|
||||
const browser = await chromium.launch({ headless: true, channel: process.env.PLAYWRIGHT_CHANNEL || "chrome" });
|
||||
try {
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1100 } });
|
||||
const page = await context.newPage();
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
await page.route("**/*", async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.origin !== origin.origin) {
|
||||
requestsOutsideLocal.push(url.origin);
|
||||
await route.abort();
|
||||
return;
|
||||
}
|
||||
const path = url.pathname;
|
||||
let payload;
|
||||
if (path === "/api/auth/me")
|
||||
payload = {
|
||||
user: {
|
||||
id: "fixture-user",
|
||||
name: "渲染验收",
|
||||
role: "pipeline_engineer",
|
||||
email: "fixture@example.test",
|
||||
status: "active",
|
||||
},
|
||||
organization: { id: "fixture-org", name: "本地测试", status: "active" },
|
||||
};
|
||||
else if (path === "/api/public/settings") payload = { timezone: "Asia/Shanghai" };
|
||||
else if (["/api/health", "/api/ready", "/worker-api/ready"].includes(path))
|
||||
payload = {
|
||||
ready: true,
|
||||
status: "ok",
|
||||
service: "fixture",
|
||||
buildCommit: "fixture",
|
||||
runnerBuildCommit: "fixture",
|
||||
runnerImage: "fixture",
|
||||
};
|
||||
else if (path === "/api/assistant/catalog")
|
||||
payload = { chatEnabled: true, role: "pipeline_engineer", actions: [], domains: [] };
|
||||
else if (path === "/api/assistant/sessions") payload = [session];
|
||||
else if (path === `/api/assistant/sessions/${session.id}`)
|
||||
payload = {
|
||||
session,
|
||||
messages: [makeMessage("m1", responses[current], current === "incomplete" ? { finishReason: "length" } : {})],
|
||||
steps: [],
|
||||
};
|
||||
else if (path.startsWith("/api/") || path.startsWith("/worker-api/"))
|
||||
throw new Error(`Unexpected API request: ${path}`);
|
||||
else return route.continue();
|
||||
await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(payload) });
|
||||
});
|
||||
const show = async (name) => {
|
||||
current = name;
|
||||
await page.goto(new URL("/assistant", origin).href);
|
||||
await page.locator(".assistant-rich-text").waitFor();
|
||||
};
|
||||
|
||||
await show("rich");
|
||||
const text = page.locator(".assistant-rich-text");
|
||||
assert.equal(await text.locator("h2").innerText(), "项目检查结果");
|
||||
assert.equal(await text.locator("strong").first().innerText(), "采集已完成");
|
||||
assert.equal(await text.locator("em").innerText(), "本地测试数据");
|
||||
const styles = await text.evaluate((root) => ({
|
||||
heading: parseFloat(getComputedStyle(root.querySelector("h2")).fontSize),
|
||||
paragraph: parseFloat(getComputedStyle(root.querySelector("p")).fontSize),
|
||||
bold: Number(getComputedStyle(root.querySelector("strong")).fontWeight),
|
||||
list: getComputedStyle(root.querySelector("ul")).listStyleType,
|
||||
}));
|
||||
assert.ok(styles.heading > styles.paragraph && styles.bold >= 600);
|
||||
assert.equal(styles.list, "disc");
|
||||
assert.equal(await text.locator("table").first().locator("tbody tr").count(), 2);
|
||||
assert.ok((await text.locator("ol li").count()) >= 2);
|
||||
assert.equal(await text.locator('input[type="checkbox"]').count(), 2);
|
||||
assert.equal(await text.locator("del").innerText(), "旧状态");
|
||||
assert.equal(await text.locator('a[href="/projects"]').count(), 1);
|
||||
assert.equal(await text.locator('a[href^="javascript:"]').count(), 0);
|
||||
assert.equal(await text.locator("img,script").count(), 0);
|
||||
assert.equal(await text.locator(".assistant-topology svg[role='img']").count(), 1);
|
||||
assert.equal(await text.locator(".assistant-topology-node").count(), 3);
|
||||
assert.equal(await text.locator(".assistant-topology-edge").count(), 2);
|
||||
const beforeWidth = await text.locator(".assistant-topology svg[role='img']").getAttribute("width");
|
||||
await text.getByRole("button", { name: "放大拓扑", exact: true }).click();
|
||||
assert.ok(
|
||||
Number(await text.locator(".assistant-topology svg[role='img']").getAttribute("width")) > Number(beforeWidth),
|
||||
);
|
||||
const zoomedWidth = await text.locator(".assistant-topology svg[role='img']").getAttribute("width");
|
||||
await page.locator("textarea").fill("继续询问,不应重建拓扑");
|
||||
assert.equal(await text.locator(".assistant-topology svg[role='img']").getAttribute("width"), zoomedWidth);
|
||||
await page.locator("textarea").fill("");
|
||||
await text.getByRole("button", { name: "适应宽度", exact: true }).click();
|
||||
await text.locator(".assistant-topology-node").last().focus();
|
||||
assert.match(await text.locator(".assistant-topology-detail").innerText(), /等待人工审核/);
|
||||
await text.locator(".assistant-topology-node").last().press("Enter");
|
||||
assert.equal(await text.locator('.assistant-topology-node[aria-pressed="true"]').count(), 1);
|
||||
await text.getByText("查看节点和连线数据", { exact: true }).click();
|
||||
assert.equal(await text.locator(".assistant-topology-data[open] tbody tr").count(), 5);
|
||||
await text.getByText("查看节点和连线数据", { exact: true }).click();
|
||||
// Keep the start of the reply visible for the screenshot; scroll is the real timeline, not the document.
|
||||
await text.evaluate((element) => {
|
||||
const timeline = element.closest("section")?.firstElementChild;
|
||||
if (timeline) timeline.scrollTop = 0;
|
||||
});
|
||||
await page.screenshot({ path: new URL("desktop.png", folder).pathname, fullPage: true });
|
||||
|
||||
for (const variant of ["bare", "jsonFence", "array"]) {
|
||||
await show(variant);
|
||||
assert.equal(await page.locator(".assistant-topology svg[role='img']").count(), 1, variant);
|
||||
}
|
||||
await show("array");
|
||||
assert.equal(await page.locator(".assistant-topology-edge").count(), 0);
|
||||
assert.match(await page.locator(".assistant-topology-detail").innerText(), /未推测/);
|
||||
await show("multiple");
|
||||
const markerIds = await page
|
||||
.locator(".assistant-topology marker")
|
||||
.evaluateAll((elements) => elements.map((element) => element.id));
|
||||
assert.equal(markerIds.length, 2);
|
||||
assert.equal(new Set(markerIds).size, 2);
|
||||
await show("incomplete");
|
||||
assert.equal(await page.locator(".assistant-topology svg[role='img']").count(), 0);
|
||||
assert.match(await page.locator(".assistant-diagram-error").innerText(), /不完整/);
|
||||
assert.match(await page.locator(".assistant-response-warning").innerText(), /输出上限/);
|
||||
assert.equal(await page.locator(".assistant-diagram-error details[open]").count(), 0);
|
||||
await page.getByText("查看原始拓扑数据", { exact: true }).click();
|
||||
assert.ok(await page.locator(".assistant-diagram-error pre").isVisible());
|
||||
await page.screenshot({ path: new URL("truncated.png", folder).pathname, fullPage: true });
|
||||
await show("ordinary");
|
||||
assert.equal(await page.locator(".assistant-topology svg[role='img']").count(), 0);
|
||||
assert.match(await page.locator(".assistant-rich-text pre code").innerText(), /"items":\[\]/);
|
||||
await show("escaped");
|
||||
assert.equal(await page.locator(".assistant-topology svg[role='img'] script").count(), 0);
|
||||
assert.equal(await page.evaluate(() => window.__injected), undefined);
|
||||
|
||||
await page.setViewportSize({ width: 375, height: 812 });
|
||||
await show("rich");
|
||||
assert.equal(await page.locator(".assistant-topology svg[role='img']").count(), 1);
|
||||
const overflow = await page.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1);
|
||||
assert.equal(overflow, false, "page must not overflow on mobile");
|
||||
await page.locator(".assistant-rich-text").evaluate((element) => {
|
||||
const timeline = element.closest("section")?.firstElementChild;
|
||||
if (timeline) timeline.scrollTop = 0;
|
||||
});
|
||||
await page.screenshot({ path: new URL("mobile.png", folder).pathname, fullPage: true });
|
||||
assert.deepEqual(errors, []);
|
||||
assert.deepEqual(requestsOutsideLocal, [], "Markdown must not automatically load model-selected URLs");
|
||||
console.log(
|
||||
"PASS: Markdown, graph formats, zoom, keyboard details, truncation, HTML safety, desktop and mobile. Synthetic API fixtures only.",
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@ -1,47 +1,179 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
extractTopologyBlocks,
|
||||
layoutTopology,
|
||||
parseTopology,
|
||||
splitRichContent,
|
||||
TOPOLOGY_LIMITS,
|
||||
} from "../../src/lib/assistant-topology.js";
|
||||
|
||||
import { extractTopologyBlocks, layoutTopology, parseTopology, topologySvg } from "../../src/lib/assistant-topology.js";
|
||||
const graph = {
|
||||
title: "项目与工作流",
|
||||
nodes: [
|
||||
{ id: "p", label: "训练项目", kind: "project", status: "ok" },
|
||||
{ id: "w", label: "采集工作流", kind: "workflow", status: "warning" },
|
||||
],
|
||||
edges: [{ from: "p", to: "w", relation: "contains" }],
|
||||
};
|
||||
const source = JSON.stringify(graph);
|
||||
const fence = (language = "ops-topology", body = source) => `\`\`\`${language}\n${body}\n\`\`\``;
|
||||
|
||||
test("parseTopology rejects untrusted or oversized graphs", () => {
|
||||
assert.equal(parseTopology("not-json").ok, false);
|
||||
assert.equal(parseTopology("{}").ok, false);
|
||||
const parsed = parseTopology(
|
||||
JSON.stringify({
|
||||
title: "项目",
|
||||
nodes: [
|
||||
{ id: "p1", label: "训练A", kind: "project", status: "ok" },
|
||||
{ id: "w1", label: "工作流1", kind: "workflow", status: "warning" },
|
||||
],
|
||||
edges: [{ from: "p1", to: "w1", relation: "contains" }],
|
||||
}),
|
||||
);
|
||||
assert.equal(parsed.ok, true);
|
||||
assert.equal(parsed.topology.nodes.length, 2);
|
||||
for (const language of ["ops-topology", "rca-topology", "topology", "diagnostic-topology", "json", ""]) {
|
||||
test(`recognizes topology in ${language || "unlabelled"} fences`, () => {
|
||||
const parts = splitRichContent(`## 关系\n\n${fence(language)}\n\n**结论**:需要关注采集。`);
|
||||
assert.deepEqual(
|
||||
parts.map((part) => part.type),
|
||||
["markdown", "topology", "markdown"],
|
||||
);
|
||||
assert.equal(parts[1].source, source);
|
||||
assert.equal(parseTopology(parts[1].source).ok, true);
|
||||
});
|
||||
}
|
||||
|
||||
test("handles CRLF, fence indentation, whitespace and tilde fences", () => {
|
||||
for (const block of [
|
||||
` \`\`\`ops-topology \r\n${source}\r\n \`\`\``,
|
||||
`~~~ops-topology\n${source}\n~~~`,
|
||||
`\`\`\`\`ops-topology\n${source}\n\`\`\`\``,
|
||||
]) {
|
||||
assert.deepEqual(extractTopologyBlocks(block), [source]);
|
||||
}
|
||||
});
|
||||
|
||||
test("layoutTopology places sources left of dependents", () => {
|
||||
test("accepts a complete JSON graph even if the closing fence is missing", () => {
|
||||
const parts = splitRichContent(`\`\`\`ops-topology\n${source}`);
|
||||
assert.equal(parts.length, 1);
|
||||
assert.equal(parseTopology(parts[0].source).ok, true);
|
||||
});
|
||||
|
||||
test("finds bare JSON before, between and after fenced graphs in order", () => {
|
||||
const parts = splitRichContent(`开头\n${source}\n中间\n${fence()}\n再次\n${source}\n尾部`);
|
||||
assert.deepEqual(
|
||||
parts.map((part) => part.type),
|
||||
["markdown", "topology", "markdown", "topology", "markdown", "topology", "markdown"],
|
||||
);
|
||||
assert.equal(parts[6].text.trim(), "尾部");
|
||||
});
|
||||
|
||||
test("supports a complete bare node array but invents no relationships", () => {
|
||||
const parts = splitRichContent(JSON.stringify(graph.nodes));
|
||||
assert.equal(parts[0].type, "topology");
|
||||
const parsed = parseTopology(parts[0].source);
|
||||
assert.equal(parsed.ok, true);
|
||||
assert.equal(parsed.topology.nodes.length, 2);
|
||||
assert.deepEqual(parsed.topology.edges, []);
|
||||
});
|
||||
|
||||
test("does not promote ordinary JSON, inline code, links or program examples", () => {
|
||||
const ordinary = [
|
||||
'[{"id":"p","name":"项目","status":"active"}]',
|
||||
'[{"id":"p","label":"这是表格记录"}]',
|
||||
'{"result":{"nodes":[{"id":"p","label":"嵌套业务数据"}]}}',
|
||||
`示例:\`${source}\``,
|
||||
`[链接](https://example.invalid)\n\n${fence("javascript")}`,
|
||||
fence("json", '{"status":"ok","items":[]}'),
|
||||
"# 标题\n\n- **列表**\n\n| A | B |\n|---|---|\n| 1 | 2 |",
|
||||
];
|
||||
for (const markdown of ordinary) {
|
||||
assert.deepEqual(splitRichContent(markdown), [{ type: "markdown", text: markdown }]);
|
||||
}
|
||||
});
|
||||
|
||||
test("preserves separation of adjacent ordinary code fences", () => {
|
||||
const markdown = `${fence("bash", "pwd")}\n\n${fence("js", "const x = 1;")}`;
|
||||
assert.deepEqual(splitRichContent(markdown), [{ type: "markdown", text: markdown }]);
|
||||
});
|
||||
|
||||
test("balanced scanning respects braces in labels and escaped quotes", () => {
|
||||
const raw = JSON.stringify({
|
||||
...graph,
|
||||
title: '带 {括号} 和 "引号" 的图',
|
||||
nodes: graph.nodes.map((node) => ({ ...node, detail: '路径 C:\\tmp\\"data"' })),
|
||||
});
|
||||
const parts = splitRichContent(`前言\n${raw}\n结束`);
|
||||
assert.equal(parts[1].source, raw);
|
||||
assert.equal(parseTopology(parts[1].source).ok, true);
|
||||
});
|
||||
|
||||
test("truncated graphs become visible errors rather than partial or fabricated diagrams", () => {
|
||||
const truncated =
|
||||
'{"title":"项目状态","nodes":[{"id":"p","label":"项目","kind":"project","status":"ok"},{"id":"w","label":"未完成';
|
||||
for (const raw of [truncated, fence("ops-topology", truncated), `\`\`\`ops-topology\n${truncated}`]) {
|
||||
const parts = splitRichContent(raw);
|
||||
assert.equal(parts.length, 1);
|
||||
assert.equal(parts[0].type, "topology");
|
||||
const parsed = parseTopology(parts[0].source);
|
||||
assert.equal(parsed.ok, false);
|
||||
assert.match(parsed.reason, /不完整/);
|
||||
}
|
||||
});
|
||||
|
||||
test("validates sizes, IDs, edges and field types", () => {
|
||||
const invalid = [
|
||||
"not-json",
|
||||
"{}",
|
||||
"null",
|
||||
JSON.stringify({ nodes: [null] }),
|
||||
JSON.stringify({ ...graph, nodes: [graph.nodes[0], graph.nodes[0]] }),
|
||||
JSON.stringify({ nodes: [{ id: "x".repeat(65), label: "超长 ID" }] }),
|
||||
JSON.stringify({ ...graph, edges: [{ from: "p", to: "missing" }] }),
|
||||
JSON.stringify({ ...graph, edges: {} }),
|
||||
JSON.stringify({ nodes: Array.from({ length: 61 }, (_, i) => ({ id: `n${i}`, label: `N${i}` })) }),
|
||||
JSON.stringify({ ...graph, edges: Array.from({ length: 121 }, () => graph.edges[0]) }),
|
||||
" ".repeat(TOPOLOGY_LIMITS.source + 1),
|
||||
];
|
||||
for (const raw of invalid) assert.equal(parseTopology(raw).ok, false);
|
||||
assert.equal(parseTopology(source).ok, true);
|
||||
});
|
||||
|
||||
test("layout handles cycles, self edges and disconnected nodes with finite coordinates", () => {
|
||||
const parsed = parseTopology(
|
||||
JSON.stringify({
|
||||
nodes: [
|
||||
{ id: "a", label: "A", kind: "project", status: "ok" },
|
||||
{ id: "b", label: "B", kind: "workflow", status: "ok" },
|
||||
nodes: [...graph.nodes, { id: "other", label: "独立节点" }],
|
||||
edges: [
|
||||
{ from: "p", to: "w" },
|
||||
{ from: "w", to: "p" },
|
||||
{ from: "p", to: "p" },
|
||||
],
|
||||
edges: [{ from: "a", to: "b" }],
|
||||
}),
|
||||
);
|
||||
const layout = layoutTopology(parsed.topology);
|
||||
const a = layout.nodes.find((node) => node.id === "a");
|
||||
const b = layout.nodes.find((node) => node.id === "b");
|
||||
assert.ok(a.x < b.x);
|
||||
const svg = topologySvg(layout, "demo");
|
||||
assert.match(svg, /<svg /);
|
||||
assert.match(svg, /训练A|A/);
|
||||
assert.equal(svg.includes("<script"), false);
|
||||
assert.equal(layout.nodes.length, 3);
|
||||
assert.ok(Number.isFinite(layout.width) && Number.isFinite(layout.height));
|
||||
assert.equal(new Set(layout.nodes.map((node) => `${node.x},${node.y}`)).size, 3);
|
||||
assert.ok(
|
||||
layout.edges.every((edge) => edge.points.every((point) => Number.isFinite(point.x) && Number.isFinite(point.y))),
|
||||
);
|
||||
});
|
||||
|
||||
test("extractTopologyBlocks finds ops-topology fences", () => {
|
||||
const blocks = extractTopologyBlocks("结论\n```ops-topology\n{\"nodes\":[{\"id\":\"a\",\"label\":\"A\"}]}\n```\n");
|
||||
assert.equal(blocks.length, 1);
|
||||
assert.match(blocks[0], /"id":"a"/);
|
||||
test("unmatched prose brackets do not hide a later standalone graph", () => {
|
||||
const parts = splitRichContent(`[说明未闭合\n下一行\n${source}`);
|
||||
assert.equal(parts[parts.length - 1].type, "topology");
|
||||
});
|
||||
|
||||
test("layout safely handles IDs that are JavaScript property names", () => {
|
||||
const parsed = parseTopology(
|
||||
JSON.stringify({
|
||||
nodes: [
|
||||
{ id: "__proto__", label: "A" },
|
||||
{ id: "constructor", label: "B" },
|
||||
],
|
||||
edges: [{ from: "__proto__", to: "constructor" }],
|
||||
}),
|
||||
);
|
||||
const layout = layoutTopology(parsed.topology);
|
||||
assert.equal(layout.nodes.length, 2);
|
||||
assert.ok(Number.isFinite(layout.width));
|
||||
assert.ok(layout.nodes[0].x < layout.nodes[1].x);
|
||||
});
|
||||
|
||||
test("lays out simple dependencies left to right and edge-free nodes as a readable grid", () => {
|
||||
const layout = layoutTopology(parseTopology(source).topology);
|
||||
assert.ok(layout.nodes[0].x < layout.nodes[1].x);
|
||||
const grid = layoutTopology(
|
||||
parseTopology(JSON.stringify({ nodes: Array.from({ length: 9 }, (_, i) => ({ id: `n${i}`, label: `节点 ${i}` })) }))
|
||||
.topology,
|
||||
);
|
||||
assert.equal(new Set(grid.nodes.map((node) => node.x)).size, 3);
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user