ai-agent-book 精选快照(<2MB 代码与文档,来自 github.com/bojieli/ai-agent-book)
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s
This commit is contained in:
@@ -0,0 +1 @@
|
||||
Front End Code Here
|
||||
+1
File diff suppressed because one or more lines are too long
+261
File diff suppressed because one or more lines are too long
BIN
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
+68
File diff suppressed because one or more lines are too long
+281
File diff suppressed because one or more lines are too long
+85
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
body{margin:0}
|
||||
+1
File diff suppressed because one or more lines are too long
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/aworld_logo.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Aworld</title>
|
||||
<script type="module" crossorigin src="/assets/index-C7nkBYbk.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-TZrNw7dA.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,526 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Trace Viewer V2</title>
|
||||
<link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
|
||||
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
|
||||
<script src="https://unpkg.com/element-plus"></script>
|
||||
<script src="https://unpkg.com/@element-plus/icons-vue"></script>
|
||||
<script src="https://d3js.org/d3.v7.min.js"></script>
|
||||
<style>
|
||||
.trace-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
font-family: 'Helvetica Neue', Arial, sans-serif;
|
||||
}
|
||||
|
||||
.trace-content {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.trace-list {
|
||||
width: 30%;
|
||||
overflow-y: auto;
|
||||
border-right: 1px solid #e6e6e6;
|
||||
}
|
||||
|
||||
.trace-detail {
|
||||
width: 70%;
|
||||
padding: 20px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.timeline {
|
||||
height: 120px;
|
||||
min-width: 100%;
|
||||
background: #f5f5f5;
|
||||
padding: 10px;
|
||||
border-bottom: 1px solid #e6e6e6;
|
||||
}
|
||||
|
||||
.span-node {
|
||||
cursor: pointer;
|
||||
padding: 5px 0;
|
||||
}
|
||||
|
||||
.span-node:hover {
|
||||
background-color: #f0f7ff;
|
||||
}
|
||||
|
||||
.span-duration {
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.timeline-bg {
|
||||
fill: #f8f8f8;
|
||||
}
|
||||
|
||||
.axis--x path {
|
||||
stroke: #333;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
|
||||
.axis--x line {
|
||||
stroke: #ddd;
|
||||
}
|
||||
|
||||
.axis--x text {
|
||||
font-size: 12px;
|
||||
fill: #333;
|
||||
}
|
||||
|
||||
.timeline-visualization {
|
||||
flex: 1;
|
||||
padding: 20px;
|
||||
background: #f8f8f8;
|
||||
border-left: 1px solid #e6e6e6;
|
||||
overflow-y: auto;
|
||||
position: relative;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.span-visualization-container {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
margin-top: 40px;
|
||||
}
|
||||
|
||||
.span-visualization {
|
||||
height: 20px;
|
||||
background: #409EFF;
|
||||
position: absolute;
|
||||
margin-top: 2px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.span-label {
|
||||
font-size: 8px;
|
||||
color: white;
|
||||
padding: 0 5px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.trace-timeline {
|
||||
background: #f5f5f5;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.trace-timeline svg {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.trace-timeline .axis path {
|
||||
stroke: #333;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
|
||||
.trace-timeline .axis line {
|
||||
stroke: #ddd;
|
||||
}
|
||||
|
||||
.trace-timeline .axis text {
|
||||
font-size: 12px;
|
||||
fill: #333;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app" class="trace-container">
|
||||
<!-- Top timeline -->
|
||||
<div class="timeline">
|
||||
<div id="timeline-chart"></div>
|
||||
</div>
|
||||
<div class="trace-content">
|
||||
<div class="trace-list">
|
||||
<div style="padding: 10px; border-bottom: 1px solid #e6e6e6;">
|
||||
<el-input v-model="searchTraceId" placeholder="输入Trace ID搜索" style="width: 100%;"
|
||||
@keyup.enter="searchByTraceId">
|
||||
<template #append>
|
||||
<el-button @click="searchByTraceId">
|
||||
<el-icon>
|
||||
<search />
|
||||
</el-icon>
|
||||
</el-button>
|
||||
</template>
|
||||
</el-input>
|
||||
</div>
|
||||
<el-tree :data="traceTree" node-key="span_id" :props="treeProps" :expand-on-click-node="false"
|
||||
@node-click="handleNodeClick" :default-expanded-keys="expandedNodes">
|
||||
<template #default="{ node, data }">
|
||||
<span class="span-node">
|
||||
{{ data.name }}
|
||||
<span class="span-duration">({{ data.duration_ms.toFixed(2) }}ms)</span>
|
||||
</span>
|
||||
</template>
|
||||
</el-tree>
|
||||
</div>
|
||||
|
||||
<div class="timeline-visualization" v-if="selectedSpan" v-html="renderTimelineVisualization()">
|
||||
</div>
|
||||
</div>
|
||||
<!-- Span detail -->
|
||||
<el-dialog v-model="dialogVisible" title="Span Details" width="70%">
|
||||
<el-descriptions :column="2" border>
|
||||
<el-descriptions-item label="Trace ID">{{ selectedSpan.trace_id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Span ID">{{ selectedSpan.span_id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Parent Span ID">{{ selectedSpan.parent_id || 'None'
|
||||
}}</el-descriptions-item>
|
||||
<el-descriptions-item label="Name">{{ selectedSpan.name }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Status">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<span :style="{color: selectedSpan.status.code === 'StatusCode.ERROR' ? '#F56C6C' : ''}">
|
||||
{{ selectedSpan.status.code }}
|
||||
</span>
|
||||
<el-button v-if="selectedSpan.status.code === 'StatusCode.ERROR'" type="text" size="small"
|
||||
@click="showStacktrace = true" icon="View" style="color: #F56C6C">
|
||||
View Stack
|
||||
</el-button>
|
||||
</div>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="Start Time">{{ selectedSpan.start_time}}</el-descriptions-item>
|
||||
<el-descriptions-item label="End Time">{{ selectedSpan.end_time }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Duration">{{ selectedSpan.duration_ms.toFixed(2) }}
|
||||
ms</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<el-card style="margin-top: 20px;">
|
||||
<template #header>
|
||||
<h4>Attributes</h4>
|
||||
</template>
|
||||
<pre style="
|
||||
max-height: 400px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
background: #f8f8f8;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
">{{ formatAttributes(selectedSpan.attributes) }}</pre>
|
||||
</el-card>
|
||||
</el-dialog>
|
||||
<el-dialog v-model="showStacktrace" title="Stacktrace Details" width="70%">
|
||||
<pre>{{ formatStacktrace(selectedSpan.attributes?.['exception.stacktrace'] || "No stacktrace available") }}</pre>
|
||||
</el-dialog>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const { createApp, ref, onMounted, nextTick } = Vue;
|
||||
const { Search } = ElementPlusIconsVue;
|
||||
createApp({
|
||||
setup() {
|
||||
const traces = ref([]);
|
||||
const traceTree = ref([]);
|
||||
const selectedSpan = ref(null);
|
||||
const expandedNodes = ref([]);
|
||||
const searchTraceId = ref('');
|
||||
const showStacktrace = ref(false);
|
||||
|
||||
const treeProps = {
|
||||
label: 'name',
|
||||
children: 'children'
|
||||
};
|
||||
const dialogVisible = ref(false);
|
||||
|
||||
function searchByTraceId() {
|
||||
if (!searchTraceId.value) {
|
||||
buildTraceTree();
|
||||
return;
|
||||
}
|
||||
const filtered = traces.value.filter(trace =>
|
||||
trace.trace_id.includes(searchTraceId.value)
|
||||
);
|
||||
|
||||
const tree = [];
|
||||
filtered.forEach(trace => {
|
||||
if (trace.root_span && trace.root_span.length > 0) {
|
||||
const root = buildSpanTree(trace.root_span[0]);
|
||||
tree.push(root);
|
||||
}
|
||||
});
|
||||
traceTree.value = tree;
|
||||
}
|
||||
|
||||
function initTimeline() {
|
||||
const timelineContainer = document.getElementById('timeline-chart');
|
||||
const width = timelineContainer.clientWidth;
|
||||
const height = 100;
|
||||
const margin = { top: 20, right: 20, bottom: 30, left: 20 };
|
||||
|
||||
const svg = d3.select(timelineContainer)
|
||||
.append('svg')
|
||||
.attr('width', width)
|
||||
.attr('height', height);
|
||||
|
||||
const now = new Date();
|
||||
const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
|
||||
const x = d3.scaleTime()
|
||||
.domain([oneDayAgo, now])
|
||||
.range([margin.left, width - margin.right]);
|
||||
|
||||
svg.append('g')
|
||||
.attr('transform', `translate(0,${height - margin.bottom})`)
|
||||
.call(d3.axisBottom(x)
|
||||
.ticks(d3.timeHour.every(2))
|
||||
.tickFormat(d3.timeFormat("%H:%M")));
|
||||
|
||||
svg.append('g')
|
||||
.attr('class', 'grid')
|
||||
.attr('transform', `translate(0,${height - margin.bottom})`)
|
||||
.call(d3.axisBottom(x)
|
||||
.ticks(d3.timeMinute.every(10))
|
||||
.tickSize(-5)
|
||||
.tickFormat(''));
|
||||
|
||||
if (traces.value && traces.value.length > 0) {
|
||||
const colorScale = d3.scaleOrdinal()
|
||||
.domain(traces.value.map((_, i) => i))
|
||||
.range(d3.schemeCategory10);
|
||||
traces.value.forEach((trace, index) => {
|
||||
if (trace.root_span && trace.root_span.length > 0) {
|
||||
const span = trace.root_span[0];
|
||||
const startTime = new Date(span.start_time);
|
||||
const endTime = new Date(span.end_time);
|
||||
const duration = endTime - startTime;
|
||||
|
||||
if (startTime >= oneDayAgo && startTime <= now) {
|
||||
svg.append('rect')
|
||||
.attr('x', x(startTime))
|
||||
.attr('y', margin.top + 30)
|
||||
.attr('width', Math.max(3, x(endTime) - x(startTime)))
|
||||
.attr('height', 20)
|
||||
.attr('fill', colorScale(index))
|
||||
.attr('rx', 2)
|
||||
.attr('opacity', 0.7)
|
||||
.on('mouseover', function () {
|
||||
d3.select(this).attr('opacity', 1);
|
||||
})
|
||||
.on('mouseout', function () {
|
||||
d3.select(this).attr('opacity', 0.7);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function renderTimelineVisualization() {
|
||||
if (!selectedSpan.value) return '';
|
||||
|
||||
const currentTrace = traceTree.value.find(t => t.trace_id === selectedSpan.value.trace_id);
|
||||
if (!currentTrace) return '';
|
||||
|
||||
const rootSpan = currentTrace.root_span?.[0] || currentTrace;
|
||||
let minTime = new Date(rootSpan.start_time).getTime();
|
||||
let maxTime = new Date(rootSpan.end_time).getTime();
|
||||
|
||||
const timelineContainer = document.createElement('div');
|
||||
timelineContainer.className = 'trace-timeline';
|
||||
timelineContainer.style.height = '60px';
|
||||
timelineContainer.style.marginBottom = '20px';
|
||||
timelineContainer.style.width = '100%';
|
||||
|
||||
const svg = d3.select(timelineContainer)
|
||||
.append('svg')
|
||||
.attr('width', '100%')
|
||||
.attr('height', '100%')
|
||||
.attr('viewBox', '0 0 1000 60');
|
||||
|
||||
const margin = { top: 10, right: 0, bottom: 30, left: 0 };
|
||||
const width = 1000 - margin.left - margin.right;
|
||||
const height = 60 - margin.top - margin.bottom;
|
||||
|
||||
const g = svg.append('g')
|
||||
.attr('transform', `translate(${margin.left},${margin.top})`);
|
||||
|
||||
|
||||
const x = d3.scaleTime()
|
||||
.domain([new Date(minTime), new Date(maxTime)])
|
||||
.range([0, width]);
|
||||
|
||||
g.append('g')
|
||||
.attr('class', 'axis axis--x')
|
||||
.attr('transform', `translate(0,${height})`)
|
||||
.call(d3.axisBottom(x)
|
||||
.ticks(5)
|
||||
.tickFormat(d3.timeFormat("%H:%M:%S.%L")));
|
||||
|
||||
g.selectAll(".grid-line")
|
||||
.data(x.ticks(5))
|
||||
.enter().append("line")
|
||||
.attr("class", "grid-line")
|
||||
.attr("x1", d => x(d))
|
||||
.attr("x2", d => x(d))
|
||||
.attr("y1", 0)
|
||||
.attr("y2", height)
|
||||
.attr("stroke", "#eee")
|
||||
.attr("stroke-width", 1);
|
||||
|
||||
const timelineHtml = timelineContainer.outerHTML;
|
||||
|
||||
function renderSpans(span, depth = 0, rowIndex = 0) {
|
||||
const spanStart = new Date(span.start_time).getTime();
|
||||
const spanEnd = new Date(span.end_time).getTime();
|
||||
const position = Math.min(13, Math.max(5, ((spanStart - minTime) / (maxTime - minTime)) * 10 * 0.9 + 5));
|
||||
const width = Math.min(92, Math.max(2, ((spanEnd - spanStart) / (maxTime - minTime)) * 100 * 0.9 + 2));
|
||||
//const position = ((spanStart - minTime) / (maxTime - minTime)) * 10 * 0.9 + 5;
|
||||
//const width = ((spanEnd - spanStart) / (maxTime - minTime)) * 100 * 0.9 + 2;
|
||||
|
||||
const minWidth = 0.5;
|
||||
const adjustedWidth = Math.max(width, minWidth);
|
||||
|
||||
const row = rowIndex * 24;
|
||||
|
||||
let childrenHtml = '';
|
||||
let nextRowIndex = rowIndex + 1;
|
||||
|
||||
if (span.children && span.children.length > 0) {
|
||||
childrenHtml = span.children.map(child => {
|
||||
const childHtml = renderSpans(child, depth + 1, nextRowIndex);
|
||||
nextRowIndex += countSpans(child);
|
||||
return childHtml;
|
||||
}).join('');
|
||||
}
|
||||
return `
|
||||
<div class="span-visualization"
|
||||
style="top: ${row}px;
|
||||
left: ${position}%;
|
||||
width: ${adjustedWidth}%;
|
||||
background: ${span.status.code === 'StatusCode.ERROR' ? '#F56C6C' : '#409EFF'};
|
||||
opacity: ${span.span_id === selectedSpan.value.span_id ? 1 : 0.6}"
|
||||
onclick="window.handleSpanClick.call(this, ${JSON.stringify(span).replace(/"/g, '"')})">
|
||||
<span class="span-label">${span.duration_ms} ${span.name}</span>
|
||||
</div>
|
||||
${childrenHtml}
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
<h3>Timeline Visualization</h3>
|
||||
${timelineHtml}
|
||||
<div class="span-visualization-container" style="height: ${traceTree.value.length * 24 + 100}px">
|
||||
${renderSpans(rootSpan)}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function countSpans(span) {
|
||||
let count = 1;
|
||||
if (span.children && span.children.length > 0) {
|
||||
span.children.forEach(child => {
|
||||
count += countSpans(child);
|
||||
});
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
async function fetchTraces() {
|
||||
try {
|
||||
const response = await fetch('/api/trace/list');
|
||||
const data = await response.json();
|
||||
traces.value = data.data;
|
||||
buildTraceTree();
|
||||
initTimeline();
|
||||
} catch (error) {
|
||||
console.error('Error loading traces:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function buildTraceTree() {
|
||||
const tree = [];
|
||||
traces.value.forEach(trace => {
|
||||
if (trace.root_span && trace.root_span.length > 0) {
|
||||
const root = buildSpanTree(trace.root_span[0]);
|
||||
tree.push(root);
|
||||
}
|
||||
});
|
||||
traceTree.value = tree;
|
||||
}
|
||||
|
||||
function buildSpanTree(span) {
|
||||
const node = {
|
||||
...span,
|
||||
children: []
|
||||
};
|
||||
|
||||
if (span.children && span.children.length > 0) {
|
||||
span.children.forEach(child => {
|
||||
node.children.push(buildSpanTree(child));
|
||||
});
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
function handleNodeClick(data) {
|
||||
selectedSpan.value = data;
|
||||
nextTick(() => {
|
||||
renderTimelineVisualization();
|
||||
});
|
||||
}
|
||||
|
||||
function handleSpanClick(data) {
|
||||
selectedSpan.value = data;
|
||||
dialogVisible.value = true;
|
||||
if (!expandedNodes.value.includes(data.span_id)) {
|
||||
expandedNodes.value.push(data.span_id);
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(timestamp) {
|
||||
return timestamp.split('.')[0];
|
||||
}
|
||||
|
||||
function formatAttributes(attrs) {
|
||||
return JSON.stringify(attrs, null, 2);
|
||||
}
|
||||
|
||||
function formatStacktrace(stacktrace) {
|
||||
if (!stacktrace) return 'No stacktrace available';
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(stacktrace), null, 2);
|
||||
} catch {
|
||||
return stacktrace;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchTraces();
|
||||
//setInterval(fetchTraces, 5000);
|
||||
window.handleSpanClick = handleSpanClick;
|
||||
});
|
||||
|
||||
return {
|
||||
traces,
|
||||
traceTree,
|
||||
selectedSpan,
|
||||
expandedNodes,
|
||||
treeProps,
|
||||
handleNodeClick,
|
||||
handleSpanClick,
|
||||
formatTime,
|
||||
formatAttributes,
|
||||
dialogVisible,
|
||||
renderTimelineVisualization,
|
||||
searchTraceId,
|
||||
searchByTraceId,
|
||||
showStacktrace,
|
||||
formatStacktrace
|
||||
};
|
||||
}
|
||||
}).use(ElementPlus).component('search', Search).mount('#app');
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,28 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist'] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
plugins: {
|
||||
'react-hooks': reactHooks,
|
||||
'react-refresh': reactRefresh,
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/aworld_logo.png" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Aworld</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "Aworld-UI",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ant-design/x": "^1.4.0",
|
||||
"@xyflow/react": "^12.8.1",
|
||||
"antd": "^5.26.0",
|
||||
"antd-style": "^3.7.1",
|
||||
"dagre": "^0.8.5",
|
||||
"mermaid": "^11.7.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router-dom": "^6.30.1",
|
||||
"uuid": "^11.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.25.0",
|
||||
"@types/dagre": "^0.7.53",
|
||||
"@types/node": "^24.0.4",
|
||||
"@types/react": "^18.2.0",
|
||||
"@types/react-dom": "^18.2.0",
|
||||
"@vitejs/plugin-react": "^4.4.1",
|
||||
"eslint": "^9.25.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.19",
|
||||
"globals": "^16.0.0",
|
||||
"less": "^4.3.0",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.30.1",
|
||||
"vite": "^6.3.5"
|
||||
},
|
||||
"repository": "git@github.com:inclusionAI/AWorld.git"
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1,526 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Trace Viewer V2</title>
|
||||
<link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
|
||||
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
|
||||
<script src="https://unpkg.com/element-plus"></script>
|
||||
<script src="https://unpkg.com/@element-plus/icons-vue"></script>
|
||||
<script src="https://d3js.org/d3.v7.min.js"></script>
|
||||
<style>
|
||||
.trace-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
font-family: 'Helvetica Neue', Arial, sans-serif;
|
||||
}
|
||||
|
||||
.trace-content {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.trace-list {
|
||||
width: 30%;
|
||||
overflow-y: auto;
|
||||
border-right: 1px solid #e6e6e6;
|
||||
}
|
||||
|
||||
.trace-detail {
|
||||
width: 70%;
|
||||
padding: 20px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.timeline {
|
||||
height: 120px;
|
||||
min-width: 100%;
|
||||
background: #f5f5f5;
|
||||
padding: 10px;
|
||||
border-bottom: 1px solid #e6e6e6;
|
||||
}
|
||||
|
||||
.span-node {
|
||||
cursor: pointer;
|
||||
padding: 5px 0;
|
||||
}
|
||||
|
||||
.span-node:hover {
|
||||
background-color: #f0f7ff;
|
||||
}
|
||||
|
||||
.span-duration {
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.timeline-bg {
|
||||
fill: #f8f8f8;
|
||||
}
|
||||
|
||||
.axis--x path {
|
||||
stroke: #333;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
|
||||
.axis--x line {
|
||||
stroke: #ddd;
|
||||
}
|
||||
|
||||
.axis--x text {
|
||||
font-size: 12px;
|
||||
fill: #333;
|
||||
}
|
||||
|
||||
.timeline-visualization {
|
||||
flex: 1;
|
||||
padding: 20px;
|
||||
background: #f8f8f8;
|
||||
border-left: 1px solid #e6e6e6;
|
||||
overflow-y: auto;
|
||||
position: relative;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.span-visualization-container {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
margin-top: 40px;
|
||||
}
|
||||
|
||||
.span-visualization {
|
||||
height: 20px;
|
||||
background: #409EFF;
|
||||
position: absolute;
|
||||
margin-top: 2px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
.span-label {
|
||||
font-size: 8px;
|
||||
color: white;
|
||||
padding: 0 5px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.trace-timeline {
|
||||
background: #f5f5f5;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.trace-timeline svg {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.trace-timeline .axis path {
|
||||
stroke: #333;
|
||||
stroke-width: 1px;
|
||||
}
|
||||
|
||||
.trace-timeline .axis line {
|
||||
stroke: #ddd;
|
||||
}
|
||||
|
||||
.trace-timeline .axis text {
|
||||
font-size: 12px;
|
||||
fill: #333;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="app" class="trace-container">
|
||||
<!-- Top timeline -->
|
||||
<div class="timeline">
|
||||
<div id="timeline-chart"></div>
|
||||
</div>
|
||||
<div class="trace-content">
|
||||
<div class="trace-list">
|
||||
<div style="padding: 10px; border-bottom: 1px solid #e6e6e6;">
|
||||
<el-input v-model="searchTraceId" placeholder="输入Trace ID搜索" style="width: 100%;"
|
||||
@keyup.enter="searchByTraceId">
|
||||
<template #append>
|
||||
<el-button @click="searchByTraceId">
|
||||
<el-icon>
|
||||
<search />
|
||||
</el-icon>
|
||||
</el-button>
|
||||
</template>
|
||||
</el-input>
|
||||
</div>
|
||||
<el-tree :data="traceTree" node-key="span_id" :props="treeProps" :expand-on-click-node="false"
|
||||
@node-click="handleNodeClick" :default-expanded-keys="expandedNodes">
|
||||
<template #default="{ node, data }">
|
||||
<span class="span-node">
|
||||
{{ data.name }}
|
||||
<span class="span-duration">({{ data.duration_ms.toFixed(2) }}ms)</span>
|
||||
</span>
|
||||
</template>
|
||||
</el-tree>
|
||||
</div>
|
||||
|
||||
<div class="timeline-visualization" v-if="selectedSpan" v-html="renderTimelineVisualization()">
|
||||
</div>
|
||||
</div>
|
||||
<!-- Span detail -->
|
||||
<el-dialog v-model="dialogVisible" title="Span Details" width="70%">
|
||||
<el-descriptions :column="2" border>
|
||||
<el-descriptions-item label="Trace ID">{{ selectedSpan.trace_id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Span ID">{{ selectedSpan.span_id }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Parent Span ID">{{ selectedSpan.parent_id || 'None'
|
||||
}}</el-descriptions-item>
|
||||
<el-descriptions-item label="Name">{{ selectedSpan.name }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Status">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center;">
|
||||
<span :style="{color: selectedSpan.status.code === 'StatusCode.ERROR' ? '#F56C6C' : ''}">
|
||||
{{ selectedSpan.status.code }}
|
||||
</span>
|
||||
<el-button v-if="selectedSpan.status.code === 'StatusCode.ERROR'" type="text" size="small"
|
||||
@click="showStacktrace = true" icon="View" style="color: #F56C6C">
|
||||
View Stack
|
||||
</el-button>
|
||||
</div>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="Start Time">{{ selectedSpan.start_time}}</el-descriptions-item>
|
||||
<el-descriptions-item label="End Time">{{ selectedSpan.end_time }}</el-descriptions-item>
|
||||
<el-descriptions-item label="Duration">{{ selectedSpan.duration_ms.toFixed(2) }}
|
||||
ms</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
<el-card style="margin-top: 20px;">
|
||||
<template #header>
|
||||
<h4>Attributes</h4>
|
||||
</template>
|
||||
<pre style="
|
||||
max-height: 400px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
background: #f8f8f8;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
">{{ formatAttributes(selectedSpan.attributes) }}</pre>
|
||||
</el-card>
|
||||
</el-dialog>
|
||||
<el-dialog v-model="showStacktrace" title="Stacktrace Details" width="70%">
|
||||
<pre>{{ formatStacktrace(selectedSpan.attributes?.['exception.stacktrace'] || "No stacktrace available") }}</pre>
|
||||
</el-dialog>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const { createApp, ref, onMounted, nextTick } = Vue;
|
||||
const { Search } = ElementPlusIconsVue;
|
||||
createApp({
|
||||
setup() {
|
||||
const traces = ref([]);
|
||||
const traceTree = ref([]);
|
||||
const selectedSpan = ref(null);
|
||||
const expandedNodes = ref([]);
|
||||
const searchTraceId = ref('');
|
||||
const showStacktrace = ref(false);
|
||||
|
||||
const treeProps = {
|
||||
label: 'name',
|
||||
children: 'children'
|
||||
};
|
||||
const dialogVisible = ref(false);
|
||||
|
||||
function searchByTraceId() {
|
||||
if (!searchTraceId.value) {
|
||||
buildTraceTree();
|
||||
return;
|
||||
}
|
||||
const filtered = traces.value.filter(trace =>
|
||||
trace.trace_id.includes(searchTraceId.value)
|
||||
);
|
||||
|
||||
const tree = [];
|
||||
filtered.forEach(trace => {
|
||||
if (trace.root_span && trace.root_span.length > 0) {
|
||||
const root = buildSpanTree(trace.root_span[0]);
|
||||
tree.push(root);
|
||||
}
|
||||
});
|
||||
traceTree.value = tree;
|
||||
}
|
||||
|
||||
function initTimeline() {
|
||||
const timelineContainer = document.getElementById('timeline-chart');
|
||||
const width = timelineContainer.clientWidth;
|
||||
const height = 100;
|
||||
const margin = { top: 20, right: 20, bottom: 30, left: 20 };
|
||||
|
||||
const svg = d3.select(timelineContainer)
|
||||
.append('svg')
|
||||
.attr('width', width)
|
||||
.attr('height', height);
|
||||
|
||||
const now = new Date();
|
||||
const oneDayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
|
||||
const x = d3.scaleTime()
|
||||
.domain([oneDayAgo, now])
|
||||
.range([margin.left, width - margin.right]);
|
||||
|
||||
svg.append('g')
|
||||
.attr('transform', `translate(0,${height - margin.bottom})`)
|
||||
.call(d3.axisBottom(x)
|
||||
.ticks(d3.timeHour.every(2))
|
||||
.tickFormat(d3.timeFormat("%H:%M")));
|
||||
|
||||
svg.append('g')
|
||||
.attr('class', 'grid')
|
||||
.attr('transform', `translate(0,${height - margin.bottom})`)
|
||||
.call(d3.axisBottom(x)
|
||||
.ticks(d3.timeMinute.every(10))
|
||||
.tickSize(-5)
|
||||
.tickFormat(''));
|
||||
|
||||
if (traces.value && traces.value.length > 0) {
|
||||
const colorScale = d3.scaleOrdinal()
|
||||
.domain(traces.value.map((_, i) => i))
|
||||
.range(d3.schemeCategory10);
|
||||
traces.value.forEach((trace, index) => {
|
||||
if (trace.root_span && trace.root_span.length > 0) {
|
||||
const span = trace.root_span[0];
|
||||
const startTime = new Date(span.start_time);
|
||||
const endTime = new Date(span.end_time);
|
||||
const duration = endTime - startTime;
|
||||
|
||||
if (startTime >= oneDayAgo && startTime <= now) {
|
||||
svg.append('rect')
|
||||
.attr('x', x(startTime))
|
||||
.attr('y', margin.top + 30)
|
||||
.attr('width', Math.max(3, x(endTime) - x(startTime)))
|
||||
.attr('height', 20)
|
||||
.attr('fill', colorScale(index))
|
||||
.attr('rx', 2)
|
||||
.attr('opacity', 0.7)
|
||||
.on('mouseover', function () {
|
||||
d3.select(this).attr('opacity', 1);
|
||||
})
|
||||
.on('mouseout', function () {
|
||||
d3.select(this).attr('opacity', 0.7);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function renderTimelineVisualization() {
|
||||
if (!selectedSpan.value) return '';
|
||||
|
||||
const currentTrace = traceTree.value.find(t => t.trace_id === selectedSpan.value.trace_id);
|
||||
if (!currentTrace) return '';
|
||||
|
||||
const rootSpan = currentTrace.root_span?.[0] || currentTrace;
|
||||
let minTime = new Date(rootSpan.start_time).getTime();
|
||||
let maxTime = new Date(rootSpan.end_time).getTime();
|
||||
|
||||
const timelineContainer = document.createElement('div');
|
||||
timelineContainer.className = 'trace-timeline';
|
||||
timelineContainer.style.height = '60px';
|
||||
timelineContainer.style.marginBottom = '20px';
|
||||
timelineContainer.style.width = '100%';
|
||||
|
||||
const svg = d3.select(timelineContainer)
|
||||
.append('svg')
|
||||
.attr('width', '100%')
|
||||
.attr('height', '100%')
|
||||
.attr('viewBox', '0 0 1000 60');
|
||||
|
||||
const margin = { top: 10, right: 0, bottom: 30, left: 0 };
|
||||
const width = 1000 - margin.left - margin.right;
|
||||
const height = 60 - margin.top - margin.bottom;
|
||||
|
||||
const g = svg.append('g')
|
||||
.attr('transform', `translate(${margin.left},${margin.top})`);
|
||||
|
||||
|
||||
const x = d3.scaleTime()
|
||||
.domain([new Date(minTime), new Date(maxTime)])
|
||||
.range([0, width]);
|
||||
|
||||
g.append('g')
|
||||
.attr('class', 'axis axis--x')
|
||||
.attr('transform', `translate(0,${height})`)
|
||||
.call(d3.axisBottom(x)
|
||||
.ticks(5)
|
||||
.tickFormat(d3.timeFormat("%H:%M:%S.%L")));
|
||||
|
||||
g.selectAll(".grid-line")
|
||||
.data(x.ticks(5))
|
||||
.enter().append("line")
|
||||
.attr("class", "grid-line")
|
||||
.attr("x1", d => x(d))
|
||||
.attr("x2", d => x(d))
|
||||
.attr("y1", 0)
|
||||
.attr("y2", height)
|
||||
.attr("stroke", "#eee")
|
||||
.attr("stroke-width", 1);
|
||||
|
||||
const timelineHtml = timelineContainer.outerHTML;
|
||||
|
||||
function renderSpans(span, depth = 0, rowIndex = 0) {
|
||||
const spanStart = new Date(span.start_time).getTime();
|
||||
const spanEnd = new Date(span.end_time).getTime();
|
||||
const position = Math.min(13, Math.max(5, ((spanStart - minTime) / (maxTime - minTime)) * 10 * 0.9 + 5));
|
||||
const width = Math.min(92, Math.max(2, ((spanEnd - spanStart) / (maxTime - minTime)) * 100 * 0.9 + 2));
|
||||
//const position = ((spanStart - minTime) / (maxTime - minTime)) * 10 * 0.9 + 5;
|
||||
//const width = ((spanEnd - spanStart) / (maxTime - minTime)) * 100 * 0.9 + 2;
|
||||
|
||||
const minWidth = 0.5;
|
||||
const adjustedWidth = Math.max(width, minWidth);
|
||||
|
||||
const row = rowIndex * 24;
|
||||
|
||||
let childrenHtml = '';
|
||||
let nextRowIndex = rowIndex + 1;
|
||||
|
||||
if (span.children && span.children.length > 0) {
|
||||
childrenHtml = span.children.map(child => {
|
||||
const childHtml = renderSpans(child, depth + 1, nextRowIndex);
|
||||
nextRowIndex += countSpans(child);
|
||||
return childHtml;
|
||||
}).join('');
|
||||
}
|
||||
return `
|
||||
<div class="span-visualization"
|
||||
style="top: ${row}px;
|
||||
left: ${position}%;
|
||||
width: ${adjustedWidth}%;
|
||||
background: ${span.status.code === 'StatusCode.ERROR' ? '#F56C6C' : '#409EFF'};
|
||||
opacity: ${span.span_id === selectedSpan.value.span_id ? 1 : 0.6}"
|
||||
onclick="window.handleSpanClick.call(this, ${JSON.stringify(span).replace(/"/g, '"')})">
|
||||
<span class="span-label">${span.duration_ms} ${span.name}</span>
|
||||
</div>
|
||||
${childrenHtml}
|
||||
`;
|
||||
}
|
||||
|
||||
return `
|
||||
<h3>Timeline Visualization</h3>
|
||||
${timelineHtml}
|
||||
<div class="span-visualization-container" style="height: ${traceTree.value.length * 24 + 100}px">
|
||||
${renderSpans(rootSpan)}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function countSpans(span) {
|
||||
let count = 1;
|
||||
if (span.children && span.children.length > 0) {
|
||||
span.children.forEach(child => {
|
||||
count += countSpans(child);
|
||||
});
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
async function fetchTraces() {
|
||||
try {
|
||||
const response = await fetch('/api/trace/list');
|
||||
const data = await response.json();
|
||||
traces.value = data.data;
|
||||
buildTraceTree();
|
||||
initTimeline();
|
||||
} catch (error) {
|
||||
console.error('Error loading traces:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function buildTraceTree() {
|
||||
const tree = [];
|
||||
traces.value.forEach(trace => {
|
||||
if (trace.root_span && trace.root_span.length > 0) {
|
||||
const root = buildSpanTree(trace.root_span[0]);
|
||||
tree.push(root);
|
||||
}
|
||||
});
|
||||
traceTree.value = tree;
|
||||
}
|
||||
|
||||
function buildSpanTree(span) {
|
||||
const node = {
|
||||
...span,
|
||||
children: []
|
||||
};
|
||||
|
||||
if (span.children && span.children.length > 0) {
|
||||
span.children.forEach(child => {
|
||||
node.children.push(buildSpanTree(child));
|
||||
});
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
function handleNodeClick(data) {
|
||||
selectedSpan.value = data;
|
||||
nextTick(() => {
|
||||
renderTimelineVisualization();
|
||||
});
|
||||
}
|
||||
|
||||
function handleSpanClick(data) {
|
||||
selectedSpan.value = data;
|
||||
dialogVisible.value = true;
|
||||
if (!expandedNodes.value.includes(data.span_id)) {
|
||||
expandedNodes.value.push(data.span_id);
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(timestamp) {
|
||||
return timestamp.split('.')[0];
|
||||
}
|
||||
|
||||
function formatAttributes(attrs) {
|
||||
return JSON.stringify(attrs, null, 2);
|
||||
}
|
||||
|
||||
function formatStacktrace(stacktrace) {
|
||||
if (!stacktrace) return 'No stacktrace available';
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(stacktrace), null, 2);
|
||||
} catch {
|
||||
return stacktrace;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchTraces();
|
||||
//setInterval(fetchTraces, 5000);
|
||||
window.handleSpanClick = handleSpanClick;
|
||||
});
|
||||
|
||||
return {
|
||||
traces,
|
||||
traceTree,
|
||||
selectedSpan,
|
||||
expandedNodes,
|
||||
treeProps,
|
||||
handleNodeClick,
|
||||
handleSpanClick,
|
||||
formatTime,
|
||||
formatAttributes,
|
||||
dialogVisible,
|
||||
renderTimelineVisualization,
|
||||
searchTraceId,
|
||||
searchByTraceId,
|
||||
showStacktrace,
|
||||
formatStacktrace
|
||||
};
|
||||
}
|
||||
}).use(ElementPlus).component('search', Search).mount('#app');
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,5 @@
|
||||
import { request } from '@/utils/http';
|
||||
|
||||
export const fetchTraceData = (traceId: string) => {
|
||||
return request(`/api/trace/agent?trace_id=${traceId}`);
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
import { request } from '../utils/http';
|
||||
|
||||
/**
|
||||
* 工作空间树节点数据结构
|
||||
*/
|
||||
export interface WorkspaceTreeResponse {
|
||||
id: string; // 节点ID
|
||||
name: string; // 节点名称
|
||||
type: string; // 节点类型 (dir/file)
|
||||
parentId: string | null; // 父节点ID
|
||||
depth: number; // 节点深度
|
||||
expanded: boolean; // 是否展开
|
||||
children: WorkspaceTreeResponse[]; // 子节点列表
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Artifact的请求参数
|
||||
*/
|
||||
export interface ArtifactQueryRequest {
|
||||
artifact_types: string[]; // Artifact类型
|
||||
artifact_ids: string[]; // Artifact ID
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建Artifact的请求参数
|
||||
*/
|
||||
export interface ArtifactCreateRequest {
|
||||
name: string; // Artifact名称
|
||||
type: string; // Artifact类型
|
||||
content: any; // Artifact内容
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建Artifact的响应数据
|
||||
*/
|
||||
export interface ArtifactCreateResponse {
|
||||
id: string; // 创建的Artifact ID
|
||||
status: 'success' | 'failed'; // 操作状态
|
||||
message?: string; // 可选的状态信息
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取工作空间树
|
||||
*/
|
||||
export const getWorkspaceTree = (sessionId: string) =>
|
||||
request(`api/workspaces/${sessionId}/tree`);
|
||||
|
||||
|
||||
/**
|
||||
* 获取工作空间Artifacts
|
||||
*/
|
||||
export const getWorkspaceArtifacts = (sessionId: string, body: ArtifactQueryRequest) =>
|
||||
request(`api/workspaces/${sessionId}/artifacts`, {
|
||||
method: 'POST',
|
||||
body
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* 创建工作空间Artifact
|
||||
*/
|
||||
export const createArtifact = (workspaceId: string, body: ArtifactCreateRequest) =>
|
||||
request(`api/workspaces/${workspaceId}/artifacts`, {
|
||||
method: 'POST',
|
||||
body
|
||||
});
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
@@ -0,0 +1 @@
|
||||
export const DEFAULT_NAME = '';
|
||||
@@ -0,0 +1,4 @@
|
||||
declare module '*.less' {
|
||||
const classes: { [key: string]: string };
|
||||
export default classes;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
body{
|
||||
margin: 0;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export const useAgentId = () => {
|
||||
const [agentId, setAgentId] = useState<string>('');
|
||||
|
||||
// 从URL参数中获取agent ID
|
||||
const getAgentIdFromURL = (): string => {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
return urlParams.get('agentid') || '';
|
||||
};
|
||||
|
||||
// 更新URL参数中的agent ID
|
||||
const updateURLAgentId = (id: string) => {
|
||||
const url = new URL(window.location.href);
|
||||
if (id) {
|
||||
url.searchParams.set('agentid', id);
|
||||
} else {
|
||||
url.searchParams.delete('agentid');
|
||||
}
|
||||
window.history.replaceState({}, '', url.toString());
|
||||
};
|
||||
|
||||
// 设置新的agent ID并更新URL
|
||||
const setAgentIdAndUpdateURL = (id: string) => {
|
||||
setAgentId(id);
|
||||
updateURLAgentId(id);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// 初始化时检查URL中是否有agent ID
|
||||
const urlAgentId = getAgentIdFromURL();
|
||||
|
||||
if (urlAgentId) {
|
||||
// 如果URL中有agent ID,使用它
|
||||
setAgentId(urlAgentId);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
agentId,
|
||||
setAgentIdAndUpdateURL,
|
||||
updateURLAgentId,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
export const useSessionId = () => {
|
||||
const [sessionId, setSessionId] = useState<string>('');
|
||||
|
||||
// 从URL参数中获取session ID
|
||||
const getSessionIdFromURL = (): string => {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
return urlParams.get('session_id') || '';
|
||||
};
|
||||
|
||||
// 更新URL参数中的session ID
|
||||
const updateURLSessionId = (id: string) => {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('session_id', id);
|
||||
window.history.replaceState({}, '', url.toString());
|
||||
};
|
||||
|
||||
// 生成新的session ID并更新URL
|
||||
const generateNewSessionId = (): string => {
|
||||
const newId = uuidv4();
|
||||
setSessionId(newId);
|
||||
updateURLSessionId(newId);
|
||||
console.log('generateNewSessionId', newId);
|
||||
return newId;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// 初始化时检查URL中是否有session ID
|
||||
const urlSessionId = getSessionIdFromURL();
|
||||
|
||||
if (urlSessionId) {
|
||||
// 如果URL中有session ID,使用它
|
||||
setSessionId(urlSessionId);
|
||||
} else {
|
||||
// 如果URL中没有session ID,生成一个新的
|
||||
generateNewSessionId();
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
sessionId,
|
||||
setSessionId,
|
||||
generateNewSessionId,
|
||||
updateURLSessionId,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { HashRouter } from 'react-router-dom'
|
||||
import './global.less'
|
||||
import Router from './router'
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<HashRouter>
|
||||
<Router />
|
||||
</HashRouter>
|
||||
</StrictMode>,
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
.ant-bubble-content .ant-bubble-content-filled{
|
||||
background-color: red;
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
.defaultbox{
|
||||
position: relative;
|
||||
.btn-workspace{
|
||||
position: absolute;
|
||||
top: -40px;
|
||||
right: 0;
|
||||
}
|
||||
.pre-wrap{
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.action-btn {
|
||||
color: #1890ff;
|
||||
cursor: pointer;
|
||||
transition: color 0.3s;
|
||||
padding: 0 4px;
|
||||
|
||||
&:hover {
|
||||
color: #40a9ff;
|
||||
}
|
||||
|
||||
&:active {
|
||||
color: #096dd9;
|
||||
}
|
||||
}
|
||||
.ant-collapse{
|
||||
// width: 668px;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import { MenuUnfoldOutlined } from '@ant-design/icons';
|
||||
import { Button, Collapse, Space, message } from 'antd';
|
||||
import React, { useCallback, useState } from 'react';
|
||||
import type { ToolCardData } from '../utils';
|
||||
import './index.less';
|
||||
|
||||
interface Props {
|
||||
sessionId: string;
|
||||
data: ToolCardData;
|
||||
onOpenWorkspace: (data: ToolCardData) => void;
|
||||
}
|
||||
|
||||
const CardDefault: React.FC<Props> = ({ sessionId, data, onOpenWorkspace }) => {
|
||||
// 当前展开的面板keys
|
||||
const [activeKeys, setActiveKeys] = useState<string[]>([]);
|
||||
|
||||
// 处理复制
|
||||
const handleCopy = useCallback(
|
||||
async (panelKey: string) => {
|
||||
try {
|
||||
const content = panelKey === '1' ? data.arguments : data.results;
|
||||
await navigator.clipboard.writeText(content);
|
||||
message.success('Copy Successful');
|
||||
} catch (error) {
|
||||
message.error('Copy Failed');
|
||||
}
|
||||
},
|
||||
[data]
|
||||
);
|
||||
// 打开workspace
|
||||
const handleOpenWorkspace = useCallback(() => {
|
||||
if (onOpenWorkspace) {
|
||||
onOpenWorkspace(data);
|
||||
}
|
||||
}, [onOpenWorkspace, sessionId, data]);
|
||||
|
||||
//操作按钮
|
||||
const renderExtra = useCallback(
|
||||
(panelKey: string) => (
|
||||
<Space size="small" onClick={(e) => e.stopPropagation()}>
|
||||
<span className="action-btn" onClick={() => handleCopy(panelKey)}>
|
||||
Copy
|
||||
</span>
|
||||
</Space>
|
||||
),
|
||||
[handleCopy]
|
||||
);
|
||||
|
||||
const items = [
|
||||
{
|
||||
key: '1',
|
||||
label: 'tool_call_arguments',
|
||||
extra: renderExtra('1'),
|
||||
children: (
|
||||
<pre className="pre-wrap">
|
||||
<code>{data.arguments}</code>
|
||||
</pre>
|
||||
)
|
||||
},
|
||||
{
|
||||
key: '2',
|
||||
label: 'tool_call_result',
|
||||
extra: renderExtra('2'),
|
||||
children: (
|
||||
<pre className="pre-wrap">
|
||||
<code>{data.results}</code>
|
||||
</pre>
|
||||
)
|
||||
}
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="defaultbox">
|
||||
{data?.artifacts?.length > 0 && (
|
||||
<Button type="link" className="btn-workspace" icon={<MenuUnfoldOutlined />} onClick={handleOpenWorkspace}>
|
||||
View Workspace
|
||||
</Button>
|
||||
)}
|
||||
<Collapse activeKey={activeKeys} onChange={(keys) => setActiveKeys(Array.isArray(keys) ? keys : [keys])} items={items} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default React.memo(CardDefault);
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
.cardwrap {
|
||||
background-color: #eee;
|
||||
border-radius: 10px;
|
||||
padding: 10px;
|
||||
position: relative;
|
||||
.btn-workspace {
|
||||
position: absolute;
|
||||
top: -38px;
|
||||
right: -6px;
|
||||
}
|
||||
.card-length {
|
||||
font-size: 14px;
|
||||
color: #333;
|
||||
.ant-tag {
|
||||
max-width: 480px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
padding: 0 10px;
|
||||
border-radius: 8px;
|
||||
line-height: 24px;
|
||||
}
|
||||
.check-icon {
|
||||
color: #1890ff;
|
||||
margin-right: 8px;
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.cardbox {
|
||||
// width: 668px;
|
||||
// width: 648px;
|
||||
overflow-x: auto;
|
||||
margin-top: 10px;
|
||||
.card-item {
|
||||
width: 175px;
|
||||
min-width: 175px;
|
||||
// margin-bottom: 16px;
|
||||
.ant-card-head {
|
||||
padding: 0 14px;
|
||||
min-height: 50px;
|
||||
}
|
||||
.ant-card-body {
|
||||
padding: 10px 14px 12px;
|
||||
.desc {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
& + .card-item {
|
||||
margin-left: 6px;
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import { CheckOutlined, MenuUnfoldOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { Button, Card, Flex, Tag, Typography } from 'antd';
|
||||
import React, { useCallback } from 'react';
|
||||
import type { ToolCardData } from '../utils';
|
||||
import './index.less';
|
||||
|
||||
interface Props {
|
||||
sessionId: string;
|
||||
data: ToolCardData;
|
||||
onOpenWorkspace?: (data: ToolCardData) => void;
|
||||
}
|
||||
|
||||
interface ItemInterface {
|
||||
title: string;
|
||||
snippet: string;
|
||||
link?: string;
|
||||
}
|
||||
|
||||
const cardLinkList: React.FC<Props> = ({ sessionId, data, onOpenWorkspace }) => {
|
||||
const items = data?.card_data?.search_items;
|
||||
|
||||
const cardItems = Array.isArray(items) ? items.filter((item) => item?.title && item?.link) : [];
|
||||
// 打开workspace
|
||||
const handleOpenWorkspace = useCallback(() => {
|
||||
if (onOpenWorkspace) {
|
||||
onOpenWorkspace(data);
|
||||
}
|
||||
}, [onOpenWorkspace, sessionId, data]);
|
||||
|
||||
return (
|
||||
<div className="cardwrap bg">
|
||||
<Button type="link" className="btn-workspace" icon={<MenuUnfoldOutlined />} onClick={handleOpenWorkspace}>
|
||||
View Workspace
|
||||
</Button>
|
||||
<Flex justify="space-between" align="center" className="card-length">
|
||||
<Tag icon={<SearchOutlined />}>{`search keywords: ${data?.card_data?.query || ''}`}</Tag>
|
||||
<Flex align="center">
|
||||
<CheckOutlined className="check-icon" />
|
||||
{cardItems.length} results
|
||||
</Flex>
|
||||
</Flex>
|
||||
<div className="border-box">
|
||||
<Flex className="cardbox">
|
||||
{cardItems?.map((item: ItemInterface, index: number) => (
|
||||
<Card title={item?.title} key={index} className="card-item" onClick={() => item?.link && window.open(item?.link, '_blank', 'noopener,noreferrer')}>
|
||||
<Typography.Paragraph className="desc" ellipsis={{ rows: 3, tooltip: typeof item?.snippet === 'string' ? item?.snippet : '' }}>
|
||||
{item?.snippet}
|
||||
</Typography.Paragraph>
|
||||
<Typography.Text ellipsis={{ tooltip: typeof item?.link === 'string' ? item?.link : '' }}>{item?.link}</Typography.Text>
|
||||
</Card>
|
||||
))}
|
||||
</Flex>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default cardLinkList;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
.markdownbox{
|
||||
p>strong{
|
||||
padding-left: 5px;
|
||||
}
|
||||
pre{
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import ReactMarkdown from 'react-markdown';
|
||||
import CardDefault from './cardDefault';
|
||||
import CardLinkList from './cardLinkList';
|
||||
import './index.less';
|
||||
import type { ToolCardData } from './utils';
|
||||
import { extractToolCards } from './utils';
|
||||
|
||||
interface BubbleItemProps {
|
||||
sessionId: string;
|
||||
data: string;
|
||||
trace_id: string;
|
||||
onOpenWorkspace?: (data: ToolCardData) => void;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
const BubbleItem: React.FC<BubbleItemProps> = ({ sessionId, data, onOpenWorkspace, isLoading = false }) => {
|
||||
// 用于记录上次打开的workspace数据,避免重复调用
|
||||
const lastWorkspaceDataRef = useRef<ToolCardData | null>(null);
|
||||
|
||||
// 修改openWorkspace函数,直接调用外部回调
|
||||
const openWorkspace = (data: ToolCardData) => {
|
||||
if (onOpenWorkspace) {
|
||||
onOpenWorkspace(data);
|
||||
}
|
||||
};
|
||||
|
||||
const { segments } = extractToolCards(data);
|
||||
|
||||
// 比较两个workspace数据是否相同
|
||||
const isWorkspaceDataEqual = (data1: ToolCardData | null, data2: ToolCardData | null): boolean => {
|
||||
if (!data1 && !data2) return true;
|
||||
if (!data1 || !data2) return false;
|
||||
|
||||
// 比较关键字段来判断是否为同一个workspace
|
||||
return (
|
||||
data1.tool_call_id === data2.tool_call_id &&
|
||||
data1.artifacts?.length === data2.artifacts?.length &&
|
||||
JSON.stringify(data1.artifacts) === JSON.stringify(data2.artifacts)
|
||||
);
|
||||
};
|
||||
|
||||
// 自动打开workspace的逻辑 - 只在流式输出过程中自动打开
|
||||
useEffect(() => {
|
||||
// 只有在流式输出过程中才自动打开workspace
|
||||
if (!isLoading) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 查找最新的具有workspace功能的tool_card(不区分card类型)
|
||||
const toolCardSegments = segments.filter(segment => segment.type === 'tool_card');
|
||||
|
||||
// 从最后一个开始查找,找到第一个有artifacts的tool_card
|
||||
const latestWorkspaceCard = toolCardSegments
|
||||
.slice()
|
||||
.reverse()
|
||||
.find(segment => {
|
||||
return segment.type === 'tool_card' &&
|
||||
segment.data?.artifacts?.length > 0;
|
||||
});
|
||||
|
||||
if (latestWorkspaceCard && latestWorkspaceCard.type === 'tool_card' && onOpenWorkspace) {
|
||||
const currentWorkspaceData = latestWorkspaceCard.data;
|
||||
|
||||
// 检查当前workspace数据是否与上次相同
|
||||
if (!isWorkspaceDataEqual(lastWorkspaceDataRef.current, currentWorkspaceData)) {
|
||||
// 更新记录的workspace数据
|
||||
lastWorkspaceDataRef.current = currentWorkspaceData;
|
||||
|
||||
// 使用requestAnimationFrame确保在下一帧渲染后打开workspace
|
||||
const frameId = requestAnimationFrame(() => {
|
||||
openWorkspace(currentWorkspaceData);
|
||||
});
|
||||
|
||||
return () => cancelAnimationFrame(frameId);
|
||||
} else {
|
||||
console.log("latest workspace opened!", currentWorkspaceData, lastWorkspaceDataRef.current)
|
||||
}
|
||||
}
|
||||
}, [segments, onOpenWorkspace, openWorkspace, isLoading]);
|
||||
|
||||
// console.log('segments:', segments);
|
||||
return (
|
||||
<div className="card">
|
||||
{segments.map((segment, index) => {
|
||||
if (segment.type === 'text') {
|
||||
return (
|
||||
<div className="markdownbox" key={`text-${index}`}>
|
||||
<ReactMarkdown>{segment.content}</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
} else if (segment.type === 'tool_card') {
|
||||
const cardType = segment.data?.card_type;
|
||||
if (cardType === 'tool_call_card_link_list') {
|
||||
return <CardLinkList key={`tool-${index}`} sessionId={sessionId} data={segment.data} onOpenWorkspace={openWorkspace} />;
|
||||
} else {
|
||||
return <CardDefault key={`tool-${index}`} sessionId={sessionId} data={segment.data} onOpenWorkspace={openWorkspace} />;
|
||||
}
|
||||
}
|
||||
})}
|
||||
{/* 移除内部的Drawer */}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BubbleItem;
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
export interface ToolCardData {
|
||||
tool_type: string;
|
||||
tool_name: string;
|
||||
function_name: string;
|
||||
tool_call_id: string;
|
||||
arguments: string;
|
||||
results: string;
|
||||
card_type: string;
|
||||
card_data: any;
|
||||
artifacts: any[];
|
||||
}
|
||||
|
||||
type ContentSegment =
|
||||
| { type: 'text'; content: string }
|
||||
| { type: 'tool_card'; data: ToolCardData; raw: string };
|
||||
|
||||
export interface ParsedContent {
|
||||
segments: ContentSegment[];
|
||||
}
|
||||
|
||||
export const extractToolCards = (content: string): ParsedContent => {
|
||||
const toolCardRegex = /(.*?)(```tool_card\s*({[\s\S]*?})\s*```)/gs;
|
||||
const segments: ContentSegment[] = [];
|
||||
let lastIndex = 0;
|
||||
|
||||
let match;
|
||||
while ((match = toolCardRegex.exec(content)) !== null) {
|
||||
const [, textBefore, fullToolCard, toolCardJson] = match;
|
||||
|
||||
// 添加文本内容
|
||||
if (textBefore) {
|
||||
segments.push({
|
||||
type: 'text',
|
||||
content: textBefore.trim()
|
||||
});
|
||||
}
|
||||
|
||||
// 添加工具卡片
|
||||
try {
|
||||
segments.push({
|
||||
type: 'tool_card',
|
||||
data: JSON.parse(toolCardJson),
|
||||
raw: fullToolCard.trim()
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Failed to parse tool_card JSON:', e);
|
||||
// 如果解析失败,仍保留原始文本
|
||||
segments.push({
|
||||
type: 'text',
|
||||
content: fullToolCard.trim()
|
||||
});
|
||||
}
|
||||
|
||||
lastIndex = toolCardRegex.lastIndex;
|
||||
}
|
||||
|
||||
// 添加最后剩余的文本内容
|
||||
const remainingText = content.slice(lastIndex);
|
||||
if (remainingText.trim()) {
|
||||
segments.push({
|
||||
type: 'text',
|
||||
content: remainingText.trim()
|
||||
});
|
||||
}
|
||||
|
||||
return { segments };
|
||||
};
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
.tracebox {
|
||||
padding: 16px;
|
||||
|
||||
.mermaid {
|
||||
width: 80%;
|
||||
max-width: 700px;
|
||||
margin: 0 auto;
|
||||
text-align: center;
|
||||
}
|
||||
.trace-id{
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
import React, { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import mermaid from 'mermaid';
|
||||
import { fetchTraceData } from '@/api/trace';
|
||||
import { treeToMermaid } from './mermaidUtils';
|
||||
import './index.less';
|
||||
|
||||
interface TraceProps {
|
||||
traceId?: string;
|
||||
drawerVisible?: boolean;
|
||||
}
|
||||
|
||||
const Trace: React.FC<TraceProps> = ({ traceId, drawerVisible }) => {
|
||||
const diagramRef = useRef<HTMLDivElement>(null);
|
||||
const [mermaidCode, setMermaidCode] = useState<string>('');
|
||||
const isFetching = useRef(false);
|
||||
|
||||
const renderError = (message: string) => {
|
||||
return `graph TD\n A[${message}]`;
|
||||
};
|
||||
|
||||
const handleFetchTrace = useCallback(async () => {
|
||||
if (!traceId || isFetching.current) return;
|
||||
isFetching.current = true;
|
||||
try {
|
||||
const result = await fetchTraceData(traceId);
|
||||
if (!result?.data) throw new Error('Invalid trace data format');
|
||||
|
||||
const mermaidData = treeToMermaid(result.data);
|
||||
if (!mermaidData.includes('graph') && !mermaidData.includes('flowchart')) {
|
||||
throw new Error(`Invalid mermaid data format`);
|
||||
}
|
||||
setMermaidCode(mermaidData);
|
||||
} catch (error) {
|
||||
console.error('Trace processing error:', error);
|
||||
setMermaidCode(renderError(error instanceof Error ? error.message : 'Data Processing Error'));
|
||||
} finally {
|
||||
isFetching.current = false;
|
||||
}
|
||||
}, [traceId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (traceId && drawerVisible) {
|
||||
handleFetchTrace();
|
||||
}
|
||||
return () => {
|
||||
// Cleanup if component unmounts during fetch
|
||||
};
|
||||
}, [traceId, drawerVisible, handleFetchTrace]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mermaidCode) return;
|
||||
|
||||
const renderMermaid = async () => {
|
||||
try {
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: 'loose'
|
||||
});
|
||||
|
||||
if (diagramRef.current) {
|
||||
diagramRef.current.innerHTML = mermaidCode;
|
||||
await mermaid.run({
|
||||
nodes: [diagramRef.current],
|
||||
suppressErrors: true
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Mermaid error:', error);
|
||||
setMermaidCode(renderError(error instanceof Error ? error.message : 'Rendering Error'));
|
||||
}
|
||||
};
|
||||
|
||||
renderMermaid();
|
||||
}, [mermaidCode]);
|
||||
|
||||
return (
|
||||
<div className="tracebox">
|
||||
<div ref={diagramRef} className="mermaid">
|
||||
{mermaidCode ||
|
||||
`graph TD
|
||||
A[loading...]`}
|
||||
</div>
|
||||
<p className='trace-id'>traceId: {traceId}</p>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Trace;
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
interface TraceNode {
|
||||
show_name: string;
|
||||
span_id?: string;
|
||||
duration_ms?: number;
|
||||
children?: TraceNode[];
|
||||
}
|
||||
|
||||
export function treeToMermaid(input: any): string {
|
||||
let output = 'flowchart TD\n';
|
||||
const processedNodes = new Set<string>();
|
||||
|
||||
function processNode(node: TraceNode, parentId?: string) {
|
||||
if (!node?.show_name) return;
|
||||
|
||||
const rawNodeId = `${node.show_name}_${node.span_id || ''}`.replace(/\s+/g, '_');
|
||||
const cleanNodeId = rawNodeId.replace(/[^a-zA-Z0-9_]/g, '_');
|
||||
|
||||
if (!processedNodes.has(cleanNodeId)) {
|
||||
const cleanName = node.show_name
|
||||
.replace(/[^a-zA-Z0-9-\s\-_.,]/g, '')
|
||||
.trim();
|
||||
|
||||
output += ` ${cleanNodeId}["${cleanName}"]\n`;
|
||||
processedNodes.add(cleanNodeId);
|
||||
}
|
||||
|
||||
if (parentId) {
|
||||
const cleanParentId = parentId.replace(/[^a-zA-Z0-9_]/g, '_');
|
||||
const duration = node.duration_ms ? `${node.duration_ms.toFixed(2)}ms` : '';
|
||||
output += ` ${cleanParentId} -->|${duration}| ${cleanNodeId}\n`;
|
||||
}
|
||||
|
||||
if (node.children && node.children.length > 0) {
|
||||
node.children.forEach((child: TraceNode) => processNode(child, cleanNodeId));
|
||||
}
|
||||
}
|
||||
|
||||
if (!input) return output;
|
||||
|
||||
const rootNode: TraceNode = {
|
||||
show_name: 'Trace Root',
|
||||
span_id: 'root',
|
||||
children: [] as TraceNode[]
|
||||
};
|
||||
|
||||
if (input.data && Array.isArray(input.data)) {
|
||||
rootNode.children = input.data;
|
||||
} else if (Array.isArray(input)) {
|
||||
rootNode.children = input;
|
||||
} else {
|
||||
rootNode.children = [input];
|
||||
}
|
||||
|
||||
processNode(rootNode);
|
||||
|
||||
return output;
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
import React, { useState, useMemo, useEffect, useCallback } from 'react';
|
||||
import { ThoughtChain } from '@ant-design/x';
|
||||
import type { ThoughtChainProps, ThoughtChainItem } from '@ant-design/x';
|
||||
import { Card, Typography, message } from 'antd';
|
||||
import { fetchTraceData } from '@/api/trace';
|
||||
|
||||
const { Paragraph } = Typography;
|
||||
|
||||
interface TraceProps {
|
||||
traceId?: string;
|
||||
drawerVisible?: boolean;
|
||||
}
|
||||
|
||||
type TraceNodeStatus = 'success' | 'pending' | 'error';
|
||||
|
||||
interface TraceNode {
|
||||
id: string;
|
||||
status?: TraceNodeStatus;
|
||||
show_name: string;
|
||||
children?: TraceNode[];
|
||||
description?: string;
|
||||
event_id: string;
|
||||
summary?: string;
|
||||
token_usage?: number;
|
||||
input_tokens?: number;
|
||||
output_tokens?: number;
|
||||
use_tools?: string[];
|
||||
}
|
||||
|
||||
const Trace: React.FC<TraceProps> = ({ traceId, drawerVisible }) => {
|
||||
const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
|
||||
const [traceData, setTraceData] = useState<TraceNode[]>([]);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
if (!traceId || !drawerVisible) return;
|
||||
try {
|
||||
const res = await fetchTraceData(traceId);
|
||||
|
||||
const validateStatus = (status?: string): TraceNodeStatus | undefined => {
|
||||
return status === 'success' || status === 'pending' || status === 'error' ? (status as TraceNodeStatus) : undefined;
|
||||
};
|
||||
|
||||
const validatedData = (res.data || []).map((item: TraceNode) => ({
|
||||
...item,
|
||||
status: validateStatus(item.status)
|
||||
}));
|
||||
setTraceData(validatedData);
|
||||
// Expand the first node by default
|
||||
if (validatedData?.[0]?.event_id) {
|
||||
setExpandedKeys([validatedData[0].event_id]);
|
||||
}
|
||||
} catch (err) {
|
||||
message.error('Failed to fetch trace data');
|
||||
console.error(err);
|
||||
}
|
||||
}, [traceId, drawerVisible]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
const renderNodeContent = useCallback(
|
||||
(node: TraceNode) => (
|
||||
<>
|
||||
{node.token_usage && <p>token_usage: {node.token_usage}</p>}
|
||||
{node.input_tokens && <p>input_tokens: {node.input_tokens}</p>}
|
||||
{node.output_tokens && <p>output_tokens: {node.output_tokens}</p>}
|
||||
{node.use_tools?.length && <p>use_tools: {node.use_tools.join(', ')}</p>}
|
||||
{node.summary && (
|
||||
<Typography>
|
||||
<Paragraph>
|
||||
<pre>{JSON.stringify(JSON.parse(node.summary), null, 2)}</pre>
|
||||
</Paragraph>
|
||||
</Typography>
|
||||
)}
|
||||
{node.children?.length ? <ThoughtChain items={convertToItems(node.children)} /> : null}
|
||||
</>
|
||||
),
|
||||
[]
|
||||
);
|
||||
|
||||
const convertToItems = useCallback(
|
||||
(nodes: TraceNode[]): ThoughtChainItem[] => {
|
||||
return nodes.map((node) => ({
|
||||
key: node.event_id,
|
||||
title: node.show_name,
|
||||
description: node.event_id,
|
||||
content: renderNodeContent(node),
|
||||
status: node.status || 'pending'
|
||||
}));
|
||||
},
|
||||
[renderNodeContent]
|
||||
);
|
||||
|
||||
const items = useMemo(() => convertToItems(traceData), [traceData, convertToItems]);
|
||||
|
||||
const collapsible: ThoughtChainProps['collapsible'] = useMemo(() => {
|
||||
return {
|
||||
expandedKeys,
|
||||
onExpand: (keys: string[]) => setExpandedKeys(keys)
|
||||
};
|
||||
}, [expandedKeys]);
|
||||
|
||||
return (
|
||||
<Card style={{ width: 650 }}>
|
||||
<ThoughtChain items={items} collapsible={collapsible} />
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default Trace;
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import React from 'react';
|
||||
import { Tooltip, Typography } from 'antd';
|
||||
import { Position, Handle } from '@xyflow/react';
|
||||
import type { CustomNodeData } from './TraceXY.types';
|
||||
|
||||
interface CustomNodeProps {
|
||||
data: {
|
||||
data: CustomNodeData;
|
||||
};
|
||||
isFirst?: boolean;
|
||||
isLast?: boolean;
|
||||
}
|
||||
|
||||
const CustomNode: React.FC<CustomNodeProps> = ({ data, isFirst, isLast }) => {
|
||||
const nodeData: CustomNodeData = data || {};
|
||||
const summary = nodeData.summary
|
||||
? (typeof nodeData.summary === 'string'
|
||||
? JSON.parse(nodeData.summary).summary
|
||||
: nodeData.summary?.summary) || ''
|
||||
: '';
|
||||
const tooltipContent = nodeData.event_id ? (
|
||||
<div className="Tooltipbox">
|
||||
{summary.length > 100 ? summary : ''}
|
||||
<div>{nodeData.event_id}</div>
|
||||
</div>
|
||||
) : null;
|
||||
return (
|
||||
<Tooltip title={tooltipContent} placement="bottom" className="Tooltipbox">
|
||||
<div className="custom-node">
|
||||
<Typography.Paragraph className="summary" ellipsis={{ rows: 4 }}>
|
||||
{summary}
|
||||
</Typography.Paragraph>
|
||||
<div className="name">{nodeData.show_name || 'Unnamed Node'}</div>
|
||||
{!isFirst && (
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
/>
|
||||
)}
|
||||
{!isLast && (
|
||||
<Handle
|
||||
type="source"
|
||||
position={Position.Bottom}
|
||||
id="bottom"
|
||||
/>
|
||||
)}
|
||||
{nodeData.sourceHandle?.includes('right') && (
|
||||
<Handle type="source" position={Position.Right} id="right" />
|
||||
)}
|
||||
{nodeData.sourceHandle?.includes('left') && (
|
||||
<Handle type="source" position={Position.Left} id="left" />
|
||||
)}
|
||||
</div>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
export default CustomNode;
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import type { Node, Edge } from '@xyflow/react';
|
||||
|
||||
export interface CustomNodeData {
|
||||
show_name?: string;
|
||||
event_id?: string;
|
||||
summary?: string | { summary: string };
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface NodeData extends Node {
|
||||
data: CustomNodeData;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface EdgeData extends Edge {
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface TraceXYProps {
|
||||
traceId?: string;
|
||||
traceQuery?: string;
|
||||
drawerVisible?: boolean;
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
.traceXYbox {
|
||||
@box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
@border-radius: 8px;
|
||||
@transition: all 0.3s ease;
|
||||
@text-color: #222;
|
||||
@border-color: #d9d9d9;
|
||||
@light-bg: #f8f9fa;
|
||||
@node-bg: linear-gradient(135deg, #fff, #f8f8f8);
|
||||
@primary-color: #1890ff;
|
||||
|
||||
width: 80%;
|
||||
max-width: 700px;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
top: -20px;
|
||||
background: @light-bg;
|
||||
border-radius: @border-radius;
|
||||
box-shadow: @box-shadow;
|
||||
overflow: hidden;
|
||||
|
||||
|
||||
.react-flow__node {
|
||||
width: 300px;
|
||||
min-width: 14.5%;
|
||||
text-align: center;
|
||||
max-width: 30%;
|
||||
@node-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
|
||||
@node-hover-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
@node-selected-shadow: 0 0 0 2px fade(@primary-color, 20%);
|
||||
border: 1px solid @border-color;
|
||||
border-radius: @border-radius;
|
||||
// padding: 12px;
|
||||
background: @node-bg;
|
||||
box-shadow: @node-shadow;
|
||||
font-size: 10px;
|
||||
// transition: @transition;
|
||||
margin-bottom: 25px;
|
||||
|
||||
&:hover {
|
||||
box-shadow: @node-hover-shadow;
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
&-selected {
|
||||
border-color: @primary-color;
|
||||
box-shadow: @node-selected-shadow;
|
||||
}
|
||||
.desc {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
.react-flow__handle{
|
||||
background-color: #ccc;
|
||||
}
|
||||
.react-flow__edge-path {
|
||||
stroke: #ddd;
|
||||
stroke-width: 2;
|
||||
animation: dashdraw 0.5s linear;
|
||||
}
|
||||
|
||||
|
||||
.react-flow__controls {
|
||||
box-shadow: @box-shadow;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.trace-id {
|
||||
position: absolute;
|
||||
bottom: 15px;
|
||||
right: 15px;
|
||||
background: rgba(255, 255, 255, 0.9);
|
||||
padding: 6px 12px;
|
||||
border-radius: 20px;
|
||||
font-size: 10px;
|
||||
color: #666;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
|
||||
border: 1px solid #eee;
|
||||
}
|
||||
|
||||
@keyframes dashdraw {
|
||||
from {
|
||||
stroke-dashoffset: 100;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// .ant-tooltip-content {
|
||||
// width: 420px;
|
||||
// }
|
||||
.Tooltipbox {
|
||||
padding: 5px 8px;
|
||||
.summary {
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
font-size: 12px;
|
||||
text-align: left;
|
||||
}
|
||||
pre {
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
color: #888;
|
||||
}
|
||||
|
||||
//edge click no changes
|
||||
.virtual-node-edge,
|
||||
.node-edge {
|
||||
&:hover,
|
||||
&-selected {
|
||||
box-shadow: none !important;
|
||||
transform: none !important;
|
||||
border-color: transparent !important;
|
||||
}
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
//virtual-node hidden handle
|
||||
// .react-flow__handle {
|
||||
// background-color: #999;
|
||||
// &.virtual-handle-target {
|
||||
// width: 0px;
|
||||
// height: 0px;
|
||||
// min-width: 0;
|
||||
// min-height: 0;
|
||||
// border: none;
|
||||
// }
|
||||
// }
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import {
|
||||
ReactFlow,
|
||||
Background,
|
||||
Controls,
|
||||
ReactFlowProvider,
|
||||
applyNodeChanges
|
||||
} from '@xyflow/react';
|
||||
import type { NodeChange } from '@xyflow/react';
|
||||
import CustomNode from './CustomNode';
|
||||
import '@xyflow/react/dist/style.css';
|
||||
import { fetchTraceData } from '@/api/trace';
|
||||
import { getLayoutedElements } from './layoutUtils';
|
||||
import './index.less';
|
||||
import type { TraceXYProps, NodeData, EdgeData } from './TraceXY.types';
|
||||
|
||||
const nodeTypes = {
|
||||
customNode: CustomNode
|
||||
};
|
||||
const TraceXY: React.FC<TraceXYProps> = ({ traceId, drawerVisible }) => {
|
||||
const [nodes, setNodes] = useState<NodeData[]>([]);
|
||||
const [edges, setEdges] = useState<EdgeData[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const onNodesChange = useCallback((changes: NodeChange[]) => {
|
||||
setNodes((nds) => {
|
||||
const updatedNodes = applyNodeChanges(changes, nds);
|
||||
return updatedNodes.map((node) => ({
|
||||
...node,
|
||||
type: node.type || 'customNode',
|
||||
data: (node as NodeData).data
|
||||
})) as NodeData[];
|
||||
});
|
||||
}, []);
|
||||
|
||||
const processNodes = useCallback((rawNodes: any[] = []): NodeData[] => {
|
||||
return rawNodes.map((node) => ({
|
||||
id: node.span_id || node.id || '',
|
||||
type: 'customNode',
|
||||
position: node.position || { x: 0, y: 0 },
|
||||
data: {
|
||||
...node.data,
|
||||
label: node.show_name,
|
||||
summary: node.summary || '',
|
||||
show_name: node.show_name,
|
||||
event_id: node.event_id
|
||||
}
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const processEdges = useCallback((rawEdges: any[] = []): EdgeData[] => {
|
||||
return rawEdges.map((edge) => ({
|
||||
id: `${edge.source}-${edge.target}`,
|
||||
source: edge.source,
|
||||
target: edge.target,
|
||||
className: 'node-edge',
|
||||
type: 'smoothstep'
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const loadAndLayoutElements = useCallback(async () => {
|
||||
if (!traceId || !drawerVisible) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await fetchTraceData(traceId);
|
||||
const nodesWithPosition = processNodes(result?.nodes || []);
|
||||
const edgesWithId = processEdges(result?.edges || []);
|
||||
|
||||
const { nodes: layoutedNodes, edges: layoutedEdges } = await getLayoutedElements(
|
||||
nodesWithPosition,
|
||||
edgesWithId
|
||||
);
|
||||
|
||||
setNodes(layoutedNodes);
|
||||
setEdges(layoutedEdges);
|
||||
} catch (err) {
|
||||
setError('Failed to load trace data, please try again later.');
|
||||
console.error('Failed to fetch and build trace elements:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [traceId, drawerVisible, processNodes, processEdges]);
|
||||
|
||||
useEffect(() => {
|
||||
loadAndLayoutElements();
|
||||
}, [loadAndLayoutElements]);
|
||||
|
||||
return (
|
||||
<div className="traceXYbox" style={{ height: '100%', width: '100%' }}>
|
||||
{loading && <div className="loading-indicator">Loading...</div>}
|
||||
{error && <div className="error-message">{error}</div>}
|
||||
{!loading && !error && nodes.length === 0 && (
|
||||
<div className="empty-state">No trace data available</div>
|
||||
)}
|
||||
{nodes.length > 0 && (
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
nodeTypes={nodeTypes}
|
||||
nodesDraggable
|
||||
onNodesChange={onNodesChange}
|
||||
snapToGrid={true}
|
||||
snapGrid={[15, 15]}
|
||||
fitView
|
||||
minZoom={0.1}
|
||||
maxZoom={2}
|
||||
>
|
||||
<Background gap={16} />
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const TraceXYWithProvider: React.FC<TraceXYProps> = (props) => (
|
||||
<ReactFlowProvider>
|
||||
<TraceXY {...props} />
|
||||
</ReactFlowProvider>
|
||||
);
|
||||
|
||||
export default TraceXYWithProvider;
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import dagre from 'dagre';
|
||||
|
||||
const calculateEdgeLength = (
|
||||
sourcePos: { x: number; y: number },
|
||||
targetPos: { x: number; y: number }
|
||||
): number => Math.hypot(targetPos.x - sourcePos.x, targetPos.y - sourcePos.y);
|
||||
|
||||
export const getLayoutedElements = (nodes: any[], edges: any[]) => {
|
||||
const dagreGraph = new dagre.graphlib.Graph();
|
||||
dagreGraph.setDefaultEdgeLabel(() => ({}));
|
||||
dagreGraph.setGraph({
|
||||
rankdir: 'TB',
|
||||
nodesep: 50,
|
||||
ranksep: 50
|
||||
});
|
||||
|
||||
nodes.forEach((node) => {
|
||||
dagreGraph.setNode(node.id, { width: 200, height: 100 });
|
||||
});
|
||||
|
||||
edges.forEach((edge) => {
|
||||
dagreGraph.setEdge(edge.source, edge.target);
|
||||
});
|
||||
|
||||
dagre.layout(dagreGraph);
|
||||
|
||||
edges.forEach((edge) => {
|
||||
const sourceNode = nodes.find((n) => n.id === edge.source);
|
||||
const targetNode = nodes.find((n) => n.id === edge.target);
|
||||
if (!sourceNode || !targetNode) return;
|
||||
|
||||
const sourcePos = dagreGraph.node(edge.source);
|
||||
const targetPos = dagreGraph.node(edge.target);
|
||||
const length = calculateEdgeLength(sourcePos, targetPos);
|
||||
|
||||
if (length > 300) {
|
||||
const direction = targetPos.x > sourcePos.x ? 'right' : 'left';
|
||||
|
||||
sourceNode.data = sourceNode.data || {};
|
||||
sourceNode.data.sourceHandle = sourceNode.data.sourceHandle || [];
|
||||
|
||||
sourceNode.data.sourceHandle.push(direction);
|
||||
edge.sourceHandle = direction;
|
||||
}
|
||||
});
|
||||
|
||||
const updatedNodes = nodes.map((node) => {
|
||||
const position = dagreGraph.node(node.id);
|
||||
return {
|
||||
...node,
|
||||
position: {
|
||||
x: position.x - 100,
|
||||
y: position.y - 50
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
nodes: updatedNodes,
|
||||
edges: edges
|
||||
};
|
||||
};
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
.workspacebox {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
.btn {
|
||||
color: #555;
|
||||
height: 28px;
|
||||
background-color: #daffd5;
|
||||
border-radius: 10px;
|
||||
position: fixed;
|
||||
top: 14px;
|
||||
right: 380px;
|
||||
&:hover {
|
||||
color: #555 !important;
|
||||
border: 1px solid #daffd5 !important;
|
||||
background-color: #f6ffed !important;
|
||||
}
|
||||
}
|
||||
&.border,
|
||||
.border {
|
||||
border: 1px solid #c1c1c1;
|
||||
border-radius: 10px;
|
||||
}
|
||||
.tabbox {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
margin-bottom: 12px;
|
||||
.num {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
text-align: center;
|
||||
line-height: 30px;
|
||||
border-radius: 50%;
|
||||
margin-right: 10px;
|
||||
background-color: #efefef;
|
||||
}
|
||||
.tab {
|
||||
width: 29%;
|
||||
padding: 5px 10px;
|
||||
cursor: pointer;
|
||||
&.active {
|
||||
.num {
|
||||
background-color: #c4efa6;
|
||||
color: #555;
|
||||
}
|
||||
}
|
||||
|
||||
.name {
|
||||
font-size: 14px;
|
||||
}
|
||||
.desc {
|
||||
font-size: 12px;
|
||||
color: #999;
|
||||
}
|
||||
}
|
||||
}
|
||||
.listwrap {
|
||||
background-color: #fafafa;
|
||||
.title {
|
||||
text-align: center;
|
||||
line-height: 40px;
|
||||
border-bottom: 1px solid #a7a7a7;
|
||||
}
|
||||
.listbox {
|
||||
.list {
|
||||
padding: 10px 14px;
|
||||
.name {
|
||||
font-size: 14px;
|
||||
margin-bottom: 3px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
&::before {
|
||||
display: inline-block;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
margin-right: 5px;
|
||||
border-radius: 50%;
|
||||
border: 1px solid #999;
|
||||
background-color: #d8d8d8;
|
||||
}
|
||||
}
|
||||
.desc,
|
||||
.link {
|
||||
color: #999;
|
||||
font-size: 12px;
|
||||
}
|
||||
.desc {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
&:not(:last-child) {
|
||||
border-bottom: 1px solid #a7a7a7;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import { getWorkspaceArtifacts } from '@/api/workspace';
|
||||
import { Image, Typography } from 'antd';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import type { ToolCardData } from '../../BubbleItem/utils';
|
||||
import './index.less';
|
||||
|
||||
interface ArtifactItem {
|
||||
snippet: string;
|
||||
link: string;
|
||||
key: string;
|
||||
title: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface WorkspaceProps {
|
||||
sessionId: string;
|
||||
toolCardData: ToolCardData;
|
||||
}
|
||||
|
||||
const Workspace: React.FC<WorkspaceProps> = ({ sessionId, toolCardData }) => {
|
||||
const [artifacts, setArtifacts] = useState<ArtifactItem[]>([]);
|
||||
const [imgUrl, setImgUrl] = useState<string | undefined>();
|
||||
const isLinkListCard = toolCardData?.card_type === 'tool_call_card_link_list';
|
||||
|
||||
// 用于缓存上次的请求参数,避免重复调用
|
||||
const lastRequestRef = useRef<{
|
||||
sessionId: string;
|
||||
artifactType: string;
|
||||
artifactId: string;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!toolCardData) return; // 如果没有 toolCardData,直接退出
|
||||
|
||||
const fetchWorkspaceArtifacts = async () => {
|
||||
try {
|
||||
const artifactType = toolCardData.artifacts?.[0]?.artifact_type;
|
||||
const artifactId = toolCardData.artifacts?.[0]?.artifact_id;
|
||||
|
||||
if (!artifactType || !artifactId) {
|
||||
console.warn('Invalid artifact data');
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否与上次请求参数相同
|
||||
const currentRequest = {
|
||||
sessionId,
|
||||
artifactType,
|
||||
artifactId
|
||||
};
|
||||
|
||||
if (lastRequestRef.current &&
|
||||
lastRequestRef.current.sessionId === currentRequest.sessionId &&
|
||||
lastRequestRef.current.artifactType === currentRequest.artifactType &&
|
||||
lastRequestRef.current.artifactId === currentRequest.artifactId) {
|
||||
// 参数相同,跳过重复请求
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新缓存的请求参数
|
||||
lastRequestRef.current = currentRequest;
|
||||
|
||||
const data = await getWorkspaceArtifacts(sessionId, {
|
||||
artifact_types: [artifactType],
|
||||
artifact_ids: [artifactId]
|
||||
});
|
||||
|
||||
const content = data?.data?.[0]?.content;
|
||||
|
||||
if (isLinkListCard) {
|
||||
setArtifacts(Array.isArray(content) ? content : []);
|
||||
} else {
|
||||
setImgUrl(content);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch workspace artifacts:', error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchWorkspaceArtifacts();
|
||||
}, [sessionId, toolCardData, isLinkListCard]);
|
||||
|
||||
const renderArtifactsList = () => (
|
||||
<div className="listbox">
|
||||
{artifacts.map((item, index) => (
|
||||
<div className="list" key={index}>
|
||||
<Typography.Link href={item?.link} target="_blank">
|
||||
<Typography.Paragraph className="name" ellipsis={{ rows: 1 }}>
|
||||
{item?.title}
|
||||
</Typography.Paragraph>
|
||||
<Typography.Paragraph className="desc" ellipsis={{ rows: 3 }}>
|
||||
{item?.snippet}
|
||||
</Typography.Paragraph>
|
||||
<Typography.Paragraph className="link" ellipsis={{ rows: 1 }}>
|
||||
{item?.link}
|
||||
</Typography.Paragraph>
|
||||
</Typography.Link>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
const renderImage = () => <Image preview={false} src={imgUrl} alt="Workspace Artifact" />;
|
||||
|
||||
return (
|
||||
<div className="workspacebox">
|
||||
<div className="border listwrap">
|
||||
{isLinkListCard ? renderArtifactsList() : renderImage()}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Workspace;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
.chatPrompt{
|
||||
.ant-prompts-label {
|
||||
color: #000000e0 !important;
|
||||
}
|
||||
.ant-prompts-desc {
|
||||
color: #000000a6 !important;
|
||||
width: 100%;
|
||||
}
|
||||
.ant-prompts-icon {
|
||||
color: #000000a6 !important;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import {
|
||||
Prompts as AntDesignPrompts,
|
||||
} from '@ant-design/x';
|
||||
|
||||
import './index.less';
|
||||
|
||||
interface IPromptsProps {
|
||||
items: any[];
|
||||
onItemClick: (item: any) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const Prompts = (props: IPromptsProps) => {
|
||||
const { items, onItemClick, className } = props;
|
||||
return (
|
||||
<AntDesignPrompts
|
||||
items={items}
|
||||
styles={{
|
||||
item: {
|
||||
flex: 1,
|
||||
backgroundImage: 'linear-gradient(123deg, #e5f4ff 0%, #efe7ff 100%)',
|
||||
borderRadius: 12,
|
||||
border: 'none',
|
||||
},
|
||||
subItem: { background: '#ffffffa6' },
|
||||
}}
|
||||
onItemClick={(info) => {
|
||||
onItemClick(info.data.description as string )
|
||||
}}
|
||||
className={className || "chatPrompt"}
|
||||
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default Prompts;
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
.welcome-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
background-color: #ffffff;
|
||||
align-items: center;
|
||||
position: relative;
|
||||
bottom: 50px;
|
||||
}
|
||||
|
||||
.content {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.logo-title-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 8px;
|
||||
|
||||
img {
|
||||
transition: transform 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
transform: scale(1.1);
|
||||
}
|
||||
}
|
||||
|
||||
.aworld-link {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
transition: color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
color: #1677ff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.input-area {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
margin-top: 24px;
|
||||
}
|
||||
|
||||
.text-input {
|
||||
border-radius: 20px;
|
||||
padding: 12px 50px 50px 20px;
|
||||
border: 1px solid #d9d9d9;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.submit-button {
|
||||
position: absolute;
|
||||
right: 12px;
|
||||
bottom: 12px;
|
||||
width: 40px !important;
|
||||
height: 40px !important;
|
||||
background-color: #000000;
|
||||
border: none;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.submit-button:hover,
|
||||
.submit-button:focus {
|
||||
background-color: rgba(0, 0, 0, 0.7) !important;
|
||||
}
|
||||
|
||||
.submit-button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
background-color: rgba(0, 0, 0, 0.1) !important;
|
||||
}
|
||||
|
||||
.submit-button:disabled:hover,
|
||||
.submit-button:disabled:focus {
|
||||
opacity: 0.5;
|
||||
background-color: rgba(0, 0, 0, 0.1) !important;
|
||||
}
|
||||
|
||||
.controls-area {
|
||||
width: 100%;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
|
||||
.model-select {
|
||||
width: 100%;
|
||||
// width: fit-content;
|
||||
height: 44px;
|
||||
border-radius: 50px;
|
||||
|
||||
.ant-select-selector {
|
||||
border-radius: 12px !important;
|
||||
padding-left: 12px !important;
|
||||
border: 1px solid #d9d9d9 !important;
|
||||
}
|
||||
|
||||
.ant-select-selection-item {
|
||||
padding-right: 24px !important;
|
||||
}
|
||||
|
||||
.ant-select-arrow {
|
||||
right: 15px;
|
||||
}
|
||||
}
|
||||
|
||||
.select-item {
|
||||
line-height: 30px;
|
||||
|
||||
small {
|
||||
margin-left: 10px;
|
||||
color: #b8b8b8;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.icon-right {
|
||||
color: #d9d9d9;
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { ArrowUpOutlined, RightOutlined } from '@ant-design/icons';
|
||||
import { Button, Col, Flex, Input, Row, Select, Typography } from 'antd';
|
||||
import React, { useState } from 'react';
|
||||
import logo from '../../../assets/aworld_logo.png';
|
||||
import './index.less';
|
||||
|
||||
const { Title } = Typography;
|
||||
|
||||
interface WelcomeProps {
|
||||
onSubmit: (value: string) => void;
|
||||
models: Array<{ label: string; value: string }>;
|
||||
selectedModel: string;
|
||||
onModelChange: (value: string) => void;
|
||||
modelsLoading: boolean;
|
||||
}
|
||||
|
||||
const Welcome: React.FC<WelcomeProps> = ({
|
||||
onSubmit,
|
||||
models,
|
||||
selectedModel,
|
||||
onModelChange,
|
||||
modelsLoading,
|
||||
}) => {
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
if (inputValue.trim()) onSubmit(inputValue);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="welcome-container">
|
||||
<div className="content">
|
||||
<Row justify="center">
|
||||
<Col>
|
||||
<div className="logo-title-container">
|
||||
<img src={logo} alt="AWorld Logo" width="46" height="46" />
|
||||
<Title level={1} style={{ margin: 0 }}>
|
||||
<a
|
||||
href="https://github.com/inclusionAI/AWorld"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="aworld-link"
|
||||
>
|
||||
Hello{' '}AWorld
|
||||
</a>
|
||||
</Title>
|
||||
</div>
|
||||
</Col>
|
||||
</Row>
|
||||
<div className="input-area">
|
||||
<Input.TextArea
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Ask or input / use skills"
|
||||
autoSize={{ minRows: 3, maxRows: 5 }}
|
||||
className="text-input"
|
||||
/>
|
||||
<Button
|
||||
type="primary"
|
||||
shape="circle"
|
||||
onClick={() => {
|
||||
if (inputValue.trim()) onSubmit(inputValue);
|
||||
}}
|
||||
icon={<ArrowUpOutlined />}
|
||||
className="submit-button"
|
||||
disabled={inputValue.trim() === ''}
|
||||
/>
|
||||
</div>
|
||||
<div className="controls-area">
|
||||
<Select
|
||||
value={selectedModel}
|
||||
onChange={onModelChange}
|
||||
options={models}
|
||||
loading={modelsLoading}
|
||||
placeholder="Select a model"
|
||||
className="model-select"
|
||||
showSearch
|
||||
filterOption={(input, option) =>
|
||||
(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
|
||||
}
|
||||
optionRender={(option) => (
|
||||
<div className="select-item">
|
||||
<Flex justify="space-between">
|
||||
<div>
|
||||
<strong>{option.label}</strong>
|
||||
<small>{option.value}</small>
|
||||
</div>
|
||||
<RightOutlined className="icon-right" />
|
||||
</Flex>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Welcome;
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
.react-flow__node-customNode {
|
||||
border-radius: 6px;
|
||||
|
||||
.custom-node {
|
||||
// background: #fadddb;
|
||||
// border: 2px solid #E6A5AD;
|
||||
border-radius: 4px;
|
||||
padding: 10px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
min-width: 200px;
|
||||
max-width: 360px;
|
||||
&-header {
|
||||
font-weight: bold;
|
||||
// color: #d58690;
|
||||
border-bottom: 1px solid #eee;
|
||||
padding-bottom: 5px;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
&-content {
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
.custom-node-io {
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Handle, Position, useNodes, useReactFlow } from '@xyflow/react';
|
||||
import type { Node, NodeProps } from '@xyflow/react';
|
||||
import { deleteNode } from '@/pages/xyflow/utils/nodeUtils';
|
||||
import { Tag, Drawer, Dropdown } from 'antd';
|
||||
import { EllipsisOutlined, DeleteOutlined, CopyOutlined } from '@ant-design/icons';
|
||||
import { NodeEditor } from '../NodeEditor';
|
||||
|
||||
interface NodeIOItem {
|
||||
id: string;
|
||||
label: string;
|
||||
type: 'string' | 'number' | 'boolean';
|
||||
defaultValue?: string;
|
||||
}
|
||||
|
||||
interface CustomNodeData
|
||||
extends Node<{
|
||||
id: string;
|
||||
label: string;
|
||||
content?: React.ReactNode;
|
||||
input?: NodeIOItem[];
|
||||
output?: NodeIOItem[];
|
||||
nodeType?: 'start' | 'end' | 'default';
|
||||
}> {}
|
||||
|
||||
interface CustomNodeProps extends NodeProps<CustomNodeData> {}
|
||||
|
||||
export const CustomNode: React.FC<CustomNodeProps> = ({ id, data }) => {
|
||||
const { label, content, input, output } = data;
|
||||
const nodes = useNodes();
|
||||
const reactFlowInstance = useReactFlow();
|
||||
const { setNodes } = reactFlowInstance;
|
||||
|
||||
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
|
||||
const [pendingData, setPendingData] = useState<Partial<CustomNodeData['data']>>({});
|
||||
const [editingData, setEditingData] = useState({
|
||||
content: typeof content === 'string' ? content : '',
|
||||
input: input || []
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
setEditingData({
|
||||
content: typeof content === 'string' ? content : '',
|
||||
input: input || []
|
||||
});
|
||||
}, [content, input]);
|
||||
|
||||
const handleNodeClick = (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
setIsDrawerOpen(true);
|
||||
};
|
||||
const handleDrawerClose = (e: React.MouseEvent | React.KeyboardEvent) => {
|
||||
if ('stopPropagation' in e) {
|
||||
e.stopPropagation();
|
||||
}
|
||||
if (Object.keys(pendingData).length > 0) {
|
||||
setNodes((nds) =>
|
||||
nds.map((node) => {
|
||||
if (node.id === id) {
|
||||
return {
|
||||
...node,
|
||||
data: {
|
||||
...node.data,
|
||||
...pendingData
|
||||
}
|
||||
};
|
||||
}
|
||||
return node;
|
||||
})
|
||||
);
|
||||
}
|
||||
setIsDrawerOpen(false);
|
||||
};
|
||||
const renderIO = (title: string, items?: NodeIOItem[]) => {
|
||||
return (
|
||||
<div className="custom-node-io">
|
||||
<span>{title}:</span>
|
||||
{items?.map((item) => (
|
||||
<Tag key={item.label}>
|
||||
{item.type}.<strong>{item.label}</strong>
|
||||
</Tag>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="custom-node" onClick={handleNodeClick}>
|
||||
<div className="custom-node-header">
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
|
||||
<span>{label}</span>
|
||||
{data.nodeType !== 'start' && data.nodeType !== 'end' && (
|
||||
<Dropdown
|
||||
menu={{
|
||||
items: [
|
||||
{
|
||||
key: 'delete',
|
||||
label: '删除',
|
||||
icon: <DeleteOutlined />,
|
||||
onClick: (e) => {
|
||||
e.domEvent.stopPropagation();
|
||||
deleteNode(nodes, setNodes, id);
|
||||
}
|
||||
},
|
||||
{
|
||||
key: 'duplicate',
|
||||
label: '创建副本',
|
||||
icon: <CopyOutlined />,
|
||||
onClick: (e) => {
|
||||
e.domEvent.stopPropagation();
|
||||
alert('暂不支持');
|
||||
}
|
||||
}
|
||||
]
|
||||
}}
|
||||
trigger={['click']}
|
||||
>
|
||||
<EllipsisOutlined
|
||||
style={{ cursor: 'pointer' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
</Dropdown>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="custom-node-body">
|
||||
<div className="custom-node-content">
|
||||
<div>{editingData.content || 'Custom Node Content'}</div>
|
||||
{data.nodeType !== 'end' && renderIO('输入', input)}
|
||||
{data.nodeType !== 'start' && renderIO('输出', output)}
|
||||
</div>
|
||||
</div>
|
||||
{data.nodeType !== 'start' && <Handle type="target" position={Position.Left} />}
|
||||
{data.nodeType !== 'end' && <Handle type="source" position={Position.Right} />}
|
||||
<Drawer
|
||||
title={label}
|
||||
placement="right"
|
||||
closable={true}
|
||||
maskClosable={true}
|
||||
onClose={handleDrawerClose}
|
||||
open={isDrawerOpen}
|
||||
width={500}
|
||||
keyboard={true}
|
||||
>
|
||||
<NodeEditor
|
||||
node={{
|
||||
id,
|
||||
position: { x: 0, y: 0 },
|
||||
data: { ...data, ...editingData }
|
||||
}}
|
||||
onUpdate={(updatedNode) => {
|
||||
setPendingData((prev) => ({
|
||||
...prev,
|
||||
...updatedNode.data
|
||||
}));
|
||||
}}
|
||||
onClose={() => handleDrawerClose({ stopPropagation: () => {} } as React.MouseEvent)}
|
||||
/>
|
||||
</Drawer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import { Controls, ControlButton } from '@xyflow/react';
|
||||
import { PlusOutlined, SaveOutlined, FolderOutlined, ReloadOutlined, GlobalOutlined, UndoOutlined, RedoOutlined } from '@ant-design/icons';
|
||||
import type { FC } from 'react';
|
||||
interface FlowControlsProps {
|
||||
isStraightLine: boolean;
|
||||
showMinimap: boolean;
|
||||
onToggleLine: () => void;
|
||||
onSave: () => void;
|
||||
onLoad: () => void;
|
||||
onAutoLayout: () => void;
|
||||
onToggleMinimap: () => void;
|
||||
onAddNode: () => void;
|
||||
onUndo: () => void;
|
||||
onRedo: () => void;
|
||||
}
|
||||
|
||||
export const FlowControls: FC<FlowControlsProps> = ({
|
||||
isStraightLine,
|
||||
showMinimap,
|
||||
onToggleLine,
|
||||
onSave,
|
||||
onLoad,
|
||||
onAutoLayout,
|
||||
onToggleMinimap,
|
||||
onAddNode,
|
||||
onUndo,
|
||||
onRedo
|
||||
}) => {
|
||||
return (
|
||||
<Controls style={{ left: '50%', transform: 'translateX(-50%)' }}>
|
||||
<ControlButton onClick={onToggleLine} title={isStraightLine ? 'Switch to curved line' : 'Switch to straight line'}>
|
||||
{isStraightLine ? '—' : '~'}
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onSave} title="Save flowchart">
|
||||
<SaveOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onLoad} title="Load flowchart">
|
||||
<FolderOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onAutoLayout} title="Auto Layout">
|
||||
<ReloadOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onUndo} title="Undo">
|
||||
<UndoOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onRedo} title="Redo">
|
||||
<RedoOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onToggleMinimap} title={showMinimap ? 'Hide minimap' : 'Show minimap'}>
|
||||
<GlobalOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={onAddNode} title="Add Node">
|
||||
<PlusOutlined />
|
||||
</ControlButton>
|
||||
</Controls>
|
||||
);
|
||||
};
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
.node-editor {
|
||||
&-content {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
&-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
&-collapse {
|
||||
margin-top: 16px;
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
import React, { useCallback, useMemo } from 'react';
|
||||
import { Button, Input, Table, Select, Collapse } from 'antd';
|
||||
import type { ColumnType } from 'antd/es/table';
|
||||
import './index.less';
|
||||
import { PlusOutlined } from '@ant-design/icons';
|
||||
import type { Node } from '@xyflow/react';
|
||||
|
||||
const { Option } = Select;
|
||||
|
||||
interface NodeIOItem {
|
||||
id: string;
|
||||
label: string;
|
||||
type: 'string' | 'number' | 'boolean';
|
||||
defaultValue?: string;
|
||||
}
|
||||
|
||||
interface NodeEditorProps {
|
||||
node: Node<{
|
||||
id: string;
|
||||
label: string;
|
||||
content?: React.ReactNode;
|
||||
input?: NodeIOItem[];
|
||||
output?: NodeIOItem[];
|
||||
}>;
|
||||
onUpdate: (node: Node) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export const NodeEditor: React.FC<NodeEditorProps> = ({ node, onUpdate }) => {
|
||||
const [editingContent, setEditingContent] = React.useState(
|
||||
typeof node.data.content === 'string' ? node.data.content : ''
|
||||
);
|
||||
const [editingInputs, setEditingInputs] = React.useState<NodeIOItem[]>(node.data.input || []);
|
||||
|
||||
React.useEffect(() => {
|
||||
setEditingContent(typeof node.data.content === 'string' ? node.data.content : '');
|
||||
setEditingInputs(node.data.input || []);
|
||||
}, [node.data.content, node.data.input]);
|
||||
|
||||
const handleUpdate = useCallback(
|
||||
(newData: Partial<typeof node.data>) => {
|
||||
onUpdate({
|
||||
...node,
|
||||
data: {
|
||||
...node.data,
|
||||
...newData
|
||||
}
|
||||
});
|
||||
},
|
||||
[node, onUpdate]
|
||||
);
|
||||
|
||||
const handleInputChange = useCallback(
|
||||
<K extends keyof NodeIOItem>(index: number, field: K, value: NodeIOItem[K]) => {
|
||||
const newInputs = [...editingInputs];
|
||||
newInputs[index][field] = value;
|
||||
setEditingInputs(newInputs);
|
||||
handleUpdate({ input: newInputs });
|
||||
},
|
||||
[editingInputs, handleUpdate]
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>{editingContent}</div>
|
||||
|
||||
<Collapse defaultActiveKey={['input']} bordered={false} className="node-editor-collapse">
|
||||
<Collapse.Panel
|
||||
header="输入"
|
||||
key="input"
|
||||
extra={
|
||||
<Button
|
||||
className="node-editor-collapse-btn"
|
||||
icon={<PlusOutlined />}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
const newInputs: NodeIOItem[] = [
|
||||
...editingInputs,
|
||||
{
|
||||
id: `input-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
|
||||
label: '',
|
||||
type: 'string' as const,
|
||||
defaultValue: ''
|
||||
}
|
||||
];
|
||||
setEditingInputs(newInputs);
|
||||
handleUpdate({ input: newInputs });
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<Table
|
||||
dataSource={editingInputs}
|
||||
rowKey={(record) => record.id}
|
||||
pagination={false}
|
||||
columns={useMemo<Array<ColumnType<NodeIOItem>>>(
|
||||
() => [
|
||||
{
|
||||
title: '变量名',
|
||||
dataIndex: 'label',
|
||||
render: (text: string, _: NodeIOItem, index: number) => (
|
||||
<Input
|
||||
key={index}
|
||||
value={text as 'string' | 'number' | 'boolean'}
|
||||
onChange={(e) => handleInputChange(index, 'label', e.target.value)}
|
||||
placeholder="Variable name"
|
||||
/>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: '变量值',
|
||||
dataIndex: 'type',
|
||||
render: (text: string, _: NodeIOItem, index: number) => (
|
||||
<Select
|
||||
value={text as 'string' | 'number' | 'boolean'}
|
||||
style={{ width: '100%' }}
|
||||
onChange={(value: 'string' | 'number' | 'boolean') =>
|
||||
handleInputChange(index, 'type', value)
|
||||
}
|
||||
>
|
||||
<Option value="string">String</Option>
|
||||
<Option value="number">Number</Option>
|
||||
<Option value="boolean">Boolean</Option>
|
||||
</Select>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
dataIndex: 'defaultValue',
|
||||
render: (text: string | undefined, _record: NodeIOItem, index: number) => (
|
||||
<Input
|
||||
value={text}
|
||||
onChange={(e) => handleInputChange(index, 'defaultValue', e.target.value)}
|
||||
placeholder="Default value"
|
||||
/>
|
||||
)
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
render: (_text, _record: NodeIOItem, index: number) => (
|
||||
<Button
|
||||
danger
|
||||
onClick={() => {
|
||||
const newInputs = editingInputs.filter((_, i) => i !== index);
|
||||
setEditingInputs(newInputs);
|
||||
handleUpdate({ input: newInputs });
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
],
|
||||
[handleInputChange, editingInputs, handleUpdate]
|
||||
)}
|
||||
/>
|
||||
</Collapse.Panel>
|
||||
</Collapse>
|
||||
<Collapse defaultActiveKey={['output']} bordered={false} className="node-editor-collapse">
|
||||
<Collapse.Panel header="输出" key="output">
|
||||
<Input.TextArea
|
||||
value={editingContent || ''}
|
||||
onChange={(e) => {
|
||||
const newValue = e.target.value;
|
||||
setEditingContent(newValue);
|
||||
handleUpdate({ content: newValue });
|
||||
}}
|
||||
placeholder="Enter node content"
|
||||
autoSize={{ minRows: 3, maxRows: 10 }}
|
||||
/>
|
||||
</Collapse.Panel>
|
||||
</Collapse>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Position } from '@xyflow/react';
|
||||
|
||||
export const initialNodes = [
|
||||
{
|
||||
id: '1',
|
||||
type: 'customNode',
|
||||
data: {
|
||||
label: 'Start Node',
|
||||
nodeType: 'start',
|
||||
content: '开始节点,用于设定工作流启动变量',
|
||||
input: [
|
||||
// { label: 'name', type: 'int' },
|
||||
// { label: 'age', type: 'Boolean' }
|
||||
]
|
||||
},
|
||||
position: { x: 0, y: 0 },
|
||||
style: { background: '#E8F8F5', border: '2px solid #1ABC9C', color: '#16A085' },
|
||||
sourcePosition: Position.Right,
|
||||
targetPosition: Position.Left
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
type: 'customNode',
|
||||
data: {
|
||||
label: 'End Node',
|
||||
nodeType: 'end',
|
||||
content: '结束节点,用于返回工作流运行结果',
|
||||
output: [
|
||||
// { label: 'name', type: 'int' },
|
||||
// { label: 'age', type: 'Boolean' }
|
||||
]
|
||||
},
|
||||
position: { x: 400, y: 0 },
|
||||
style: { background: '#FEF9E7', border: '2px solid #F7DC6F', color: '#D4AC0D' },
|
||||
sourcePosition: Position.Right,
|
||||
targetPosition: Position.Left
|
||||
}
|
||||
];
|
||||
export const initialEdges = [];
|
||||
@@ -0,0 +1,18 @@
|
||||
@import '@xyflow/react/dist/style.css';
|
||||
@import './components/CustomNode/index.less';
|
||||
|
||||
.react-flow__controls {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 8px;
|
||||
padding: 8px;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.react-flow__controls-button {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 6px;
|
||||
font-size: 16px;
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import React, { useCallback, useState, useEffect, useRef } from 'react';
|
||||
import {
|
||||
ReactFlow,
|
||||
Background,
|
||||
MiniMap,
|
||||
useReactFlow,
|
||||
ReactFlowProvider,
|
||||
useNodesState,
|
||||
useEdgesState,
|
||||
} from '@xyflow/react';
|
||||
import type { Connection, Node, Edge } from '@xyflow/react';
|
||||
import { FlowControls } from './components/FlowControls';
|
||||
import { CustomNode } from './components/CustomNode/index';
|
||||
import { saveFlow, loadFlow } from './utils/flowStorageUtils';
|
||||
|
||||
import { initialNodes, initialEdges } from './constants';
|
||||
import { addNode } from './utils/nodeUtils';
|
||||
import { addEdge, deleteEdge, updateEdgeStyles } from './utils/edgeUtils';
|
||||
import { autoLayout } from './utils/layoutUtils';
|
||||
import { addHistory, onUndo, onRedo, initHistory, getCurrentHistory } from './utils/historyUtils';
|
||||
import '@xyflow/react/dist/style.css';
|
||||
import './index.less';
|
||||
|
||||
const nodeTypes = {
|
||||
customNode: CustomNode,
|
||||
};
|
||||
|
||||
function FlowChart() {
|
||||
const [nodes, setNodes, onNodesChange] = useNodesState<Node>(initialNodes);
|
||||
const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>(initialEdges);
|
||||
const [showMinimap, setShowMinimap] = useState(false);
|
||||
const [isStraightLine, setIsStraightLine] = useState(false);
|
||||
|
||||
// 初始化历史记录
|
||||
useEffect(() => {
|
||||
initHistory(nodes, edges);
|
||||
}, []);
|
||||
|
||||
const reactFlowInstance = useReactFlow();
|
||||
|
||||
const handleAddNode = useCallback(() => {
|
||||
addNode(nodes, (newNodes) => {
|
||||
setNodes(newNodes);
|
||||
});
|
||||
}, [nodes]);
|
||||
|
||||
const handleConnect = useCallback(
|
||||
(params: Connection) => {
|
||||
setEdges(addEdge(edges, params.source, params.target));
|
||||
},
|
||||
[edges]
|
||||
);
|
||||
|
||||
const handleAutoLayout = useCallback(() => {
|
||||
autoLayout(nodes, edges, setNodes, reactFlowInstance);
|
||||
}, [nodes, edges, setNodes, reactFlowInstance]);
|
||||
|
||||
const handleSave = useCallback(() => {
|
||||
saveFlow(nodes, edges);
|
||||
}, [nodes, edges]);
|
||||
|
||||
const handleLoad = useCallback(() => {
|
||||
loadFlow(setNodes, setEdges);
|
||||
// 加载后重置历史记录
|
||||
setTimeout(() => {
|
||||
initHistory(nodes, edges);
|
||||
}, 0);
|
||||
}, [setNodes, setEdges, nodes, edges]);
|
||||
|
||||
const handleDeleteEdge = useCallback(
|
||||
(edgeId: string) => {
|
||||
setEdges(deleteEdge(edges, edgeId));
|
||||
},
|
||||
[edges, setEdges]
|
||||
);
|
||||
|
||||
// 自动保存历史记录(带严格防抖)
|
||||
const prevNodesRef = useRef<Node[]>([]);
|
||||
const prevEdgesRef = useRef<Edge[]>([]);
|
||||
useEffect(() => {
|
||||
const nodesChanged = JSON.stringify(prevNodesRef.current) !== JSON.stringify(nodes);
|
||||
const edgesChanged = JSON.stringify(prevEdgesRef.current) !== JSON.stringify(edges);
|
||||
|
||||
if (nodesChanged || edgesChanged) {
|
||||
const currentHistory = getCurrentHistory();
|
||||
if (
|
||||
(nodes.length > 0 || edges.length > 0) &&
|
||||
(!currentHistory ||
|
||||
JSON.stringify(currentHistory.nodes) !== JSON.stringify(nodes) ||
|
||||
JSON.stringify(currentHistory.edges) !== JSON.stringify(edges))
|
||||
) {
|
||||
addHistory(nodes, edges);
|
||||
}
|
||||
prevNodesRef.current = nodes;
|
||||
prevEdgesRef.current = edges;
|
||||
}
|
||||
}, [nodes, edges]);
|
||||
|
||||
const updatedEdges = updateEdgeStyles(edges, isStraightLine).map((edge) => ({
|
||||
...edge,
|
||||
label:
|
||||
edge.label &&
|
||||
React.cloneElement(edge.label as React.ReactElement, {
|
||||
onClick: (e: React.MouseEvent) => {
|
||||
(edge.label as React.ReactElement)?.props?.onClick?.(e);
|
||||
handleDeleteEdge(edge.id);
|
||||
},
|
||||
}),
|
||||
}));
|
||||
return (
|
||||
<div style={{ width: '100%', height: '100vh' }}>
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={updatedEdges}
|
||||
onNodesChange={onNodesChange}
|
||||
onEdgesChange={onEdgesChange}
|
||||
onConnect={handleConnect}
|
||||
fitView
|
||||
nodesDraggable
|
||||
edgesFocusable
|
||||
panOnScroll
|
||||
nodeTypes={nodeTypes}
|
||||
>
|
||||
<Background />
|
||||
{showMinimap && <MiniMap />}
|
||||
<FlowControls
|
||||
isStraightLine={isStraightLine}
|
||||
showMinimap={showMinimap}
|
||||
onToggleLine={() => setIsStraightLine(!isStraightLine)}
|
||||
onSave={handleSave}
|
||||
onLoad={handleLoad}
|
||||
onAutoLayout={handleAutoLayout}
|
||||
onToggleMinimap={() => setShowMinimap(!showMinimap)}
|
||||
onAddNode={handleAddNode}
|
||||
onUndo={() => {
|
||||
const state = onUndo();
|
||||
if (state) {
|
||||
// 使用函数式更新确保立即应用状态
|
||||
setNodes(() => state.nodes);
|
||||
setEdges(() => state.edges);
|
||||
}
|
||||
}}
|
||||
onRedo={() => {
|
||||
const state = onRedo();
|
||||
if (state) {
|
||||
setNodes(state.nodes);
|
||||
setEdges(state.edges);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</ReactFlow>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function () {
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<FlowChart />
|
||||
</ReactFlowProvider>
|
||||
);
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import type { Edge } from '@xyflow/react';
|
||||
import { MarkerType } from '@xyflow/react';
|
||||
/**
|
||||
* Edge operation functions
|
||||
* adding、deleting
|
||||
*/
|
||||
export const addEdge = (edges: Edge[], source: string, target: string): Edge[] => {
|
||||
const newEdge = {
|
||||
id: `${source}-${target}-${Date.now()}`,
|
||||
source,
|
||||
target
|
||||
};
|
||||
|
||||
return [...edges, newEdge];
|
||||
};
|
||||
|
||||
export const deleteEdge = (edges: Edge[], edgeId: string): Edge[] => {
|
||||
return edges.filter((edge) => edge.id !== edgeId);
|
||||
};
|
||||
|
||||
export const updateEdgeStyles = (edges: Edge[], isStraightLine: boolean): Edge[] => {
|
||||
return edges.map((edge) => ({
|
||||
...edge,
|
||||
type: isStraightLine ? 'straight' : 'default',
|
||||
markerEnd: { type: MarkerType.ArrowClosed },
|
||||
style: {
|
||||
...edge.style,
|
||||
strokeWidth: 2,
|
||||
...(isStraightLine ? { stroke: '#b1b1b7', strokeDasharray: '0' } : {})
|
||||
}
|
||||
}));
|
||||
};
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import type { Node, Edge } from '@xyflow/react';
|
||||
import { message } from 'antd';
|
||||
|
||||
export const saveFlow = (nodes: Node[], edges: Edge[]) => {
|
||||
const flowData = JSON.stringify({ nodes, edges });
|
||||
localStorage.setItem('flow-data', flowData);
|
||||
message.success('The flowchart layout has been saved!');
|
||||
};
|
||||
|
||||
export const loadFlow = (setNodes: (nodes: Node[]) => void, setEdges: (edges: Edge[]) => void) => {
|
||||
const flowData = localStorage.getItem('flow-data');
|
||||
if (flowData) {
|
||||
const { nodes, edges } = JSON.parse(flowData);
|
||||
setNodes(nodes);
|
||||
setEdges(edges);
|
||||
message.success('The flowchart layout has been loaded!');
|
||||
} else {
|
||||
message.info('No saved flowchart layout!');
|
||||
}
|
||||
};
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
import type { Node, Edge } from '@xyflow/react';
|
||||
|
||||
// 流程图状态类型
|
||||
type FlowState = {
|
||||
nodes: Node[];
|
||||
edges: Edge[];
|
||||
};
|
||||
|
||||
// 操作历史栈
|
||||
let historyStack: FlowState[] = [];
|
||||
let currentIndex = -1;
|
||||
let isUndoRedoInProgress = false;
|
||||
|
||||
// 初始化历史记录
|
||||
export const initHistory = (nodes: Node[], edges: Edge[]) => {
|
||||
historyStack = [
|
||||
{
|
||||
nodes: JSON.parse(JSON.stringify(nodes)),
|
||||
edges: JSON.parse(JSON.stringify(edges))
|
||||
}
|
||||
];
|
||||
currentIndex = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* 添加新操作到历史记录
|
||||
*/
|
||||
export const addHistory = (nodes: Node[], edges: Edge[]) => {
|
||||
console.log('addHistory添加记录')
|
||||
if (isUndoRedoInProgress) {
|
||||
isUndoRedoInProgress = false;
|
||||
return;
|
||||
}
|
||||
const newState = {
|
||||
nodes: JSON.parse(JSON.stringify(nodes)),
|
||||
edges: JSON.parse(JSON.stringify(edges))
|
||||
};
|
||||
|
||||
// 更严格的状态变化检测
|
||||
const prevState = currentIndex >= 0 ? historyStack[currentIndex] : null;
|
||||
if (prevState && prevState.nodes.length === newState.nodes.length && prevState.edges.length === newState.edges.length && JSON.stringify(prevState.nodes) === JSON.stringify(newState.nodes) && JSON.stringify(prevState.edges) === JSON.stringify(newState.edges)) {
|
||||
console.log('[History] 状态未变化,跳过保存');
|
||||
return;
|
||||
}
|
||||
|
||||
// 清除当前索引之后的操作(如果有重做操作未执行)
|
||||
const removedCount = historyStack.length - (currentIndex + 1);
|
||||
historyStack.splice(currentIndex + 1);
|
||||
historyStack.push(newState);
|
||||
currentIndex = historyStack.length - 1;
|
||||
|
||||
console.log(`[History] 新增,currentIndex=${currentIndex}, 节点数=${nodes.length}, 边数=${edges.length}, 移除记录=${removedCount}, 调用栈:`);
|
||||
};
|
||||
|
||||
/**
|
||||
* 撤销操作
|
||||
*/
|
||||
export const onUndo = (): FlowState | null => {
|
||||
if (currentIndex <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
isUndoRedoInProgress = true;
|
||||
const prevIndex = currentIndex - 1;
|
||||
const prevState = historyStack[prevIndex];
|
||||
|
||||
currentIndex = prevIndex;
|
||||
return {
|
||||
nodes: [...prevState.nodes],
|
||||
edges: [...prevState.edges]
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 重做操作
|
||||
*/
|
||||
export const onRedo = (): FlowState | null => {
|
||||
if (currentIndex >= historyStack.length - 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
isUndoRedoInProgress = true;
|
||||
currentIndex++;
|
||||
const nextState = historyStack[currentIndex];
|
||||
|
||||
return nextState;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取当前历史状态
|
||||
*/
|
||||
export const getCurrentHistory = (): FlowState | null => {
|
||||
if (currentIndex < 0) return null;
|
||||
return historyStack[currentIndex];
|
||||
};
|
||||
|
||||
/**
|
||||
* 清除历史记录
|
||||
*/
|
||||
export const clearHistory = () => {
|
||||
historyStack.length = 0;
|
||||
currentIndex = -1;
|
||||
};
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* Auto layout
|
||||
* use dagre library
|
||||
*/
|
||||
import type { Node, Edge } from '@xyflow/react';
|
||||
import type { useReactFlow } from '@xyflow/react';
|
||||
import dagre from 'dagre';
|
||||
|
||||
export const autoLayout = (
|
||||
nodes: Node[],
|
||||
edges: Edge[],
|
||||
setNodes: (nodes: Node[]) => void,
|
||||
reactFlowInstance: ReturnType<typeof useReactFlow>
|
||||
): void => {
|
||||
const dagreGraph = new dagre.graphlib.Graph();
|
||||
dagreGraph.setDefaultEdgeLabel(() => ({}));
|
||||
const nodeWidth = 200;
|
||||
const nodeHeight = 100;
|
||||
|
||||
dagreGraph.setGraph({
|
||||
rankdir: 'LR',
|
||||
nodesep: 50,
|
||||
ranksep: 100
|
||||
});
|
||||
|
||||
nodes.forEach((node) => {
|
||||
dagreGraph.setNode(node.id, {
|
||||
width: nodeWidth,
|
||||
height: nodeHeight
|
||||
});
|
||||
});
|
||||
|
||||
edges.forEach((edge) => {
|
||||
dagreGraph.setEdge(edge.source, edge.target);
|
||||
});
|
||||
|
||||
dagre.layout(dagreGraph);
|
||||
|
||||
const updatedNodes = nodes.map((node) => {
|
||||
const layoutNode = dagreGraph.node(node.id);
|
||||
return {
|
||||
...node,
|
||||
position: {
|
||||
x: layoutNode.x,
|
||||
y: layoutNode.y
|
||||
}
|
||||
};
|
||||
});
|
||||
setNodes(updatedNodes);
|
||||
console.log('auto:', updatedNodes);
|
||||
console.log('edges:', edges);
|
||||
setTimeout(() => {
|
||||
reactFlowInstance.fitView();
|
||||
}, 0);
|
||||
};
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Node operation
|
||||
* adding、deleting
|
||||
*/
|
||||
import type { Node } from '@xyflow/react';
|
||||
import { Position } from '@xyflow/react';
|
||||
|
||||
/**
|
||||
* addNode
|
||||
* @param nodes
|
||||
* @param setNodes
|
||||
*/
|
||||
export const addNode = (nodes: Node[], setNodes: (nodes: Node[]) => void): void => {
|
||||
const randomOffset = () => Math.random() * 50 - 25;
|
||||
|
||||
const startNode = nodes.find((node) => node.data.nodeType === 'start');
|
||||
const endNode = nodes.find((node) => node.data.nodeType === 'end');
|
||||
|
||||
if (!startNode || !endNode) {
|
||||
console.error('Start node or end node not found, unable to add a new node');
|
||||
return;
|
||||
}
|
||||
|
||||
const newXPosition = endNode.position.x - randomOffset();
|
||||
const newYPosition = startNode.position.y + 150 + randomOffset();
|
||||
|
||||
const newNode = {
|
||||
id: Date.now().toString(),
|
||||
type: 'customNode',
|
||||
data: {
|
||||
label: `Custom Node ${nodes.length + 1}`,
|
||||
content: `This is custom node #${nodes.length + 1}`,
|
||||
input: [],
|
||||
ouput: []
|
||||
},
|
||||
position: {
|
||||
x: newXPosition,
|
||||
y: newYPosition
|
||||
},
|
||||
|
||||
style: { background: '#FADDDB', border: '2px solid #E6A5AD', color: '#d58690' },
|
||||
sourcePosition: Position.Right,
|
||||
targetPosition: Position.Left
|
||||
};
|
||||
|
||||
setNodes([...nodes.filter((node: Node) => node.id !== endNode.id), newNode, endNode]);
|
||||
};
|
||||
|
||||
/**
|
||||
* deleteNode
|
||||
* @param nodes
|
||||
* @param setNodes
|
||||
* @param nodeId
|
||||
*/
|
||||
export const deleteNode = (
|
||||
nodes: Node[],
|
||||
setNodes: (nodes: Node[]) => void,
|
||||
nodeId: string
|
||||
): void => {
|
||||
setNodes(nodes.filter((node) => node.id !== nodeId));
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
|
||||
.react-flow__controls {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
gap: 8px;
|
||||
padding: 8px;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.react-flow__controls-button {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 6px;
|
||||
font-size: 16px;
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
import { ReactFlow, Background, Controls, MiniMap, MarkerType, useNodesState, useEdgesState, addEdge, ControlButton, Position, useReactFlow, ReactFlowProvider } from '@xyflow/react';
|
||||
import { PlusOutlined, SaveOutlined, FolderOutlined, ReloadOutlined, GlobalOutlined } from '@ant-design/icons';
|
||||
import type { Node, Edge, Connection } from '@xyflow/react';
|
||||
import dagre from 'dagre';
|
||||
import { message } from 'antd';
|
||||
|
||||
import '@xyflow/react/dist/style.css';
|
||||
import './index.less';
|
||||
|
||||
// init Nodes
|
||||
const initialNodes: Node[] = [
|
||||
{
|
||||
id: '1',
|
||||
type: 'input',
|
||||
data: { label: 'Strat Node' },
|
||||
position: { x: 0, y: 0 },
|
||||
style: { background: '#E8F8F5', border: '2px solid #1ABC9C', color: '#16A085' },
|
||||
sourcePosition: Position.Right,
|
||||
targetPosition: Position.Left
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
type: 'output',
|
||||
data: { label: 'End Node' },
|
||||
position: { x: 400, y: 0 },
|
||||
style: { background: '#FEF9E7', border: '2px solid #F7DC6F', color: '#D4AC0D' },
|
||||
sourcePosition: Position.Right,
|
||||
targetPosition: Position.Left
|
||||
}
|
||||
];
|
||||
|
||||
const initialEdges: Edge[] = [];
|
||||
|
||||
function FlowChart() {
|
||||
const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes);
|
||||
const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges);
|
||||
const [showMinimap, setShowMinimap] = useState(false);
|
||||
const [isStraightLine, setIsStraightLine] = useState(false);
|
||||
|
||||
const reactFlowInstance = useReactFlow();
|
||||
|
||||
// add nodes
|
||||
const addNode = useCallback(() => {
|
||||
const randomOffset = () => Math.random() * 50 - 25;
|
||||
|
||||
const startNode = nodes.find((node) => node.type === 'input');
|
||||
const endNode = nodes.find((node) => node.type === 'output');
|
||||
if (!startNode || !endNode) {
|
||||
console.error('Start node or end node not found, unable to add a new node');
|
||||
return;
|
||||
}
|
||||
|
||||
const newXPosition = endNode.position.x - randomOffset();
|
||||
const newYPosition = startNode.position.y + 150 + randomOffset();
|
||||
|
||||
const newNode = {
|
||||
id: Date.now().toString(),
|
||||
data: { label: `Node ${nodes.length + 1}` },
|
||||
position: {
|
||||
x: newXPosition,
|
||||
y: newYPosition
|
||||
},
|
||||
style: { background: '#FADDDB', border: '2px solid #E6A5AD', color: '#d58690' },
|
||||
sourcePosition: Position.Right,
|
||||
targetPosition: Position.Left
|
||||
};
|
||||
|
||||
setNodes((prevNodes) => [...prevNodes.filter((node) => node.id !== endNode.id), newNode, endNode]);
|
||||
}, [nodes, setNodes]);
|
||||
|
||||
const handleConnect = useCallback(
|
||||
(params: Connection) => {
|
||||
setEdges((eds) =>
|
||||
addEdge(
|
||||
{
|
||||
...params,
|
||||
markerEnd: { type: MarkerType.ArrowClosed },
|
||||
style: { strokeWidth: 2 }
|
||||
},
|
||||
eds
|
||||
)
|
||||
);
|
||||
},
|
||||
[setEdges]
|
||||
);
|
||||
|
||||
// const deleteEdge = useCallback(
|
||||
// (edgeId: string) => {
|
||||
// setEdges((eds) => eds.filter((edge) => edge.id !== edgeId));
|
||||
// },
|
||||
// [setEdges]
|
||||
// );
|
||||
|
||||
const autoLayout = useCallback(() => {
|
||||
const dagreGraph = new dagre.graphlib.Graph();
|
||||
dagreGraph.setDefaultEdgeLabel(() => ({}));
|
||||
const nodeWidth = 150;
|
||||
const nodeHeight = 50;
|
||||
|
||||
dagreGraph.setGraph({ rankdir: 'LR', nodesep: 50, ranksep: 100 });
|
||||
|
||||
nodes.forEach((node) => {
|
||||
dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
|
||||
});
|
||||
|
||||
edges.forEach((edge) => {
|
||||
dagreGraph.setEdge(edge.source, edge.target);
|
||||
});
|
||||
|
||||
dagre.layout(dagreGraph);
|
||||
|
||||
const updatedNodes = nodes.map((node) => {
|
||||
const layoutNode = dagreGraph.node(node.id);
|
||||
return {
|
||||
...node,
|
||||
position: {
|
||||
x: layoutNode.x,
|
||||
y: layoutNode.y
|
||||
}
|
||||
};
|
||||
});
|
||||
setNodes(updatedNodes);
|
||||
|
||||
setTimeout(() => {
|
||||
reactFlowInstance.fitView();
|
||||
}, 0);
|
||||
}, [nodes, edges, setNodes, reactFlowInstance]);
|
||||
|
||||
const saveFlow = useCallback(() => {
|
||||
const flowData = JSON.stringify({ nodes, edges });
|
||||
localStorage.setItem('flow-data', flowData);
|
||||
message.success('The flowchart layout has been saved!');
|
||||
}, [nodes, edges]);
|
||||
|
||||
const loadFlow = useCallback(() => {
|
||||
const flowData = localStorage.getItem('flow-data');
|
||||
if (flowData) {
|
||||
const { nodes, edges } = JSON.parse(flowData);
|
||||
setNodes(nodes);
|
||||
setEdges(edges);
|
||||
message.success('The flowchart layout has been loaded!');
|
||||
} else {
|
||||
message.info('No saved flowchart layout!');
|
||||
}
|
||||
}, [setNodes, setEdges]);
|
||||
|
||||
const updatedEdges = edges.map((edge) => ({
|
||||
...edge,
|
||||
type: isStraightLine ? 'straight' : 'default',
|
||||
style: {
|
||||
...edge.style,
|
||||
strokeWidth: 2,
|
||||
...(isStraightLine ? { stroke: '#b1b1b7', strokeDasharray: '0' } : {})
|
||||
}
|
||||
}));
|
||||
return (
|
||||
<div style={{ width: '100%', height: '100vh' }}>
|
||||
<ReactFlow nodes={nodes} edges={updatedEdges} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onConnect={handleConnect} fitView nodesDraggable edgesFocusable panOnScroll>
|
||||
<Background />
|
||||
{showMinimap && <MiniMap />}
|
||||
<Controls style={{ left: '50%', transform: 'translateX(-50%)' }}>
|
||||
<ControlButton onClick={() => setIsStraightLine(!isStraightLine)} title={isStraightLine ? 'Switch to curved line' : 'Switch to straight line'}>
|
||||
{isStraightLine ? '—' : '~'}
|
||||
</ControlButton>
|
||||
<ControlButton onClick={saveFlow} title="Save flowchart">
|
||||
<SaveOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={loadFlow} title="Load flowchart">
|
||||
<FolderOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={autoLayout} title="Auto Layout">
|
||||
<ReloadOutlined />
|
||||
</ControlButton>
|
||||
<ControlButton onClick={() => setShowMinimap(!showMinimap)} title={showMinimap ? 'Hide minimap' : 'Show minimap'}>
|
||||
<GlobalOutlined />
|
||||
</ControlButton>
|
||||
|
||||
<ControlButton onClick={addNode} title="Add Node">
|
||||
<PlusOutlined />
|
||||
</ControlButton>
|
||||
</Controls>
|
||||
</ReactFlow>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export default function () {
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<FlowChart />
|
||||
</ReactFlowProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import React, { lazy, Suspense } from 'react';
|
||||
import { Routes, Route, Navigate } from 'react-router-dom';
|
||||
|
||||
const App = lazy(() => import('./pages/App'));
|
||||
const XyFlowPage = lazy(() => import('./pages/xyflow'));
|
||||
|
||||
const routes = [
|
||||
{
|
||||
path: '/index.html',
|
||||
element: <Navigate to="/" replace />
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
element: <App />
|
||||
},
|
||||
{
|
||||
path: '/xyflow',
|
||||
element: <XyFlowPage />
|
||||
}
|
||||
];
|
||||
|
||||
const FallbackComponent: React.FC = () => <div style={{ opacity: 0 }}>Loading...</div>;
|
||||
|
||||
const AppRouter: React.FC = () => {
|
||||
return (
|
||||
<Suspense fallback={<FallbackComponent />}>
|
||||
<Routes>
|
||||
{routes.map((route, index) => (
|
||||
<Route key={index} path={route.path} element={route.element} />
|
||||
))}
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
};
|
||||
|
||||
export default AppRouter;
|
||||
@@ -0,0 +1,35 @@
|
||||
import { message } from 'antd';
|
||||
|
||||
interface RequestOptions {
|
||||
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
||||
headers?: Record<string, string>;
|
||||
body?: any;
|
||||
}
|
||||
|
||||
export async function request(url: string, options: RequestOptions = {}) {
|
||||
const { method = 'GET', headers = {}, body } = options;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...headers
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
message.error(`Request failed: ${error.message}`);
|
||||
} else {
|
||||
message.error('Request failed: Unknown error');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": "./src",
|
||||
"paths": {
|
||||
"@/*": ["*"]
|
||||
},
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true,
|
||||
},
|
||||
"include": ["src"],
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import path from 'path';
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src')
|
||||
}
|
||||
},
|
||||
plugins: [react()],
|
||||
server: {
|
||||
proxy: {
|
||||
'^/api': {
|
||||
target: 'http://0.0.0.0:8000',
|
||||
changeOrigin: true,
|
||||
secure: false,
|
||||
ws: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user