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,2 @@
|
||||
# coding: utf-8
|
||||
# Copyright (c) 2025 inclusionAI.
|
||||
@@ -0,0 +1,38 @@
|
||||
import click
|
||||
|
||||
|
||||
@click.group()
|
||||
def main(*args, **kwargs):
|
||||
print(
|
||||
"""\
|
||||
AWorld CLI Help:
|
||||
aworld web: run aworld web ui server
|
||||
aworld api: run aworld api server
|
||||
aworld help: show help"""
|
||||
)
|
||||
|
||||
|
||||
@main.command("web")
|
||||
@click.option(
|
||||
"--port", type=int, default=8000, help="Port to run the AWorld api server"
|
||||
)
|
||||
@click.argument("args", nargs=-1)
|
||||
def main_web(port, args=None, **kwargs):
|
||||
from .web import web_server
|
||||
|
||||
web_server.run_server(port, args, **kwargs)
|
||||
|
||||
|
||||
@main.command("api")
|
||||
@click.option(
|
||||
"--port", type=int, default=8000, help="Port to run the AWorld api server"
|
||||
)
|
||||
@click.argument("args", nargs=-1)
|
||||
def main_api(port, args=None, **kwargs):
|
||||
from .web import api_server
|
||||
|
||||
api_server.run_server(port, args, **kwargs)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,78 @@
|
||||
import datetime
|
||||
import uuid
|
||||
from abc import abstractmethod
|
||||
from typing import Any, AsyncGenerator, List, Optional
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from aworld.output.base import Output
|
||||
|
||||
|
||||
class ChatCompletionMessage(BaseModel):
|
||||
role: str = Field(..., description="The role of the message")
|
||||
content: str = Field(..., description="The content of the message")
|
||||
trace_id: Optional[str] = Field(None, description="The trace id")
|
||||
|
||||
|
||||
class ChatCompletionRequest(BaseModel):
|
||||
user_id: Optional[str] = Field(None, description="The user id")
|
||||
session_id: str = Field(
|
||||
None,
|
||||
description="The session id, if not provided, a new session will be created",
|
||||
)
|
||||
query_id: Optional[str] = Field(None, description="The query id")
|
||||
trace_id: Optional[str] = Field(None, description="The trace id")
|
||||
model: str = Field(..., description="The model to use")
|
||||
messages: List[ChatCompletionMessage] = Field(
|
||||
..., description="The messages to send to the agent"
|
||||
)
|
||||
|
||||
|
||||
class ChatCompletionChoice(BaseModel):
|
||||
index: int = 0
|
||||
delta: ChatCompletionMessage = Field(
|
||||
..., description="The delta message from the agent"
|
||||
)
|
||||
|
||||
|
||||
class ChatCompletionResponse(BaseModel):
|
||||
object: str = "chat.completion.chunk"
|
||||
id: str = uuid.uuid4().hex
|
||||
choices: List[ChatCompletionChoice] = Field(
|
||||
..., description="The choices from the agent"
|
||||
)
|
||||
|
||||
|
||||
class AgentModel(BaseModel):
|
||||
id: str = Field(..., description="The agent id")
|
||||
name: Optional[str] = Field(None, description="The agent name")
|
||||
description: Optional[str] = Field(None, description="The agent description")
|
||||
path: str = Field(..., description="The agent path")
|
||||
instance: Any = Field(..., description="The agent module instance", exclude=True)
|
||||
|
||||
|
||||
class BaseAWorldAgent:
|
||||
@abstractmethod
|
||||
def name(self) -> str:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def description(self) -> str:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def run(
|
||||
self, prompt: str = None, request: ChatCompletionRequest = None
|
||||
) -> AsyncGenerator[Output, None]:
|
||||
pass
|
||||
|
||||
|
||||
class SessionModel(BaseModel):
|
||||
user_id: str = Field(..., description="The user id")
|
||||
session_id: str = Field(..., description="The session id")
|
||||
name: str = Field(None, description="The session name")
|
||||
description: str = Field(None, description="The session description")
|
||||
created_at: datetime.datetime = Field(None, description="The session created at")
|
||||
updated_at: datetime.datetime = Field(None, description="The session updated at")
|
||||
messages: List[ChatCompletionMessage] = Field(
|
||||
None, description="The messages in the session"
|
||||
)
|
||||
@@ -0,0 +1,87 @@
|
||||
from typing import AsyncGenerator
|
||||
from aworld.cmd.utils.agent_server import AgentServer
|
||||
from aworld.output.ui.base import AworldUI
|
||||
from aworld.output.workspace import WorkSpace
|
||||
from aworld.cmd.data_model import (
|
||||
BaseAWorldAgent,
|
||||
ChatCompletionChoice,
|
||||
ChatCompletionMessage,
|
||||
ChatCompletionRequest,
|
||||
ChatCompletionResponse,
|
||||
)
|
||||
from .agent_ui_parser import AWorldWebAgentUI
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
from dotenv import load_dotenv
|
||||
import traceback
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def stream_run(request: ChatCompletionRequest, agent_server: AgentServer):
|
||||
if not request.session_id:
|
||||
request.session_id = str(uuid.uuid4())
|
||||
if not request.query_id:
|
||||
request.query_id = str(uuid.uuid4())
|
||||
if request.messages and request.messages[-1].trace_id is None:
|
||||
request.messages[-1].trace_id = request.trace_id
|
||||
|
||||
logger.info(f"Stream run agent: request={request.model_dump_json()}")
|
||||
agent = agent_server.get_agent(request.model)
|
||||
instance: BaseAWorldAgent = agent.instance
|
||||
env_file = os.path.join(agent.path, ".env")
|
||||
if os.path.exists(env_file):
|
||||
logger.info(f"Loading environment variables from {env_file}")
|
||||
load_dotenv(env_file, override=True, verbose=True)
|
||||
|
||||
final_response: str = ""
|
||||
|
||||
def build_response(delta_content: str):
|
||||
nonlocal final_response
|
||||
final_response += delta_content
|
||||
logger.info(f"Agent {agent.name} response: {delta_content}")
|
||||
return ChatCompletionResponse(
|
||||
choices=[
|
||||
ChatCompletionChoice(
|
||||
index=0,
|
||||
delta=ChatCompletionMessage(
|
||||
role="assistant",
|
||||
content=delta_content,
|
||||
trace_id=request.trace_id,
|
||||
),
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
rich_ui = AWorldWebAgentUI(
|
||||
session_id=request.session_id,
|
||||
workspace=WorkSpace.from_local_storages(
|
||||
workspace_id=request.session_id,
|
||||
),
|
||||
)
|
||||
|
||||
await agent_server.on_chat_completion_request(request)
|
||||
try:
|
||||
async for output in instance.run(request=request):
|
||||
try:
|
||||
logger.info(f"Agent {agent.name} output: {output}")
|
||||
|
||||
if isinstance(output, str):
|
||||
yield build_response(output)
|
||||
else:
|
||||
res = await AworldUI.parse_output(output, rich_ui)
|
||||
for item in res if isinstance(res, list) else [res]:
|
||||
if isinstance(item, AsyncGenerator):
|
||||
async for sub_item in item:
|
||||
yield build_response(sub_item)
|
||||
else:
|
||||
yield build_response(item)
|
||||
except:
|
||||
logger.error(
|
||||
f"Agent {agent.name} output error! output={output}, error={traceback.format_exc()}"
|
||||
)
|
||||
except:
|
||||
logger.error(f"Agent {agent.name} error: {traceback.format_exc()}")
|
||||
finally:
|
||||
await agent_server.on_chat_completion_end(request, final_response)
|
||||
@@ -0,0 +1,112 @@
|
||||
import os
|
||||
import importlib
|
||||
import subprocess
|
||||
import sys
|
||||
import traceback
|
||||
import logging
|
||||
from typing import List, Dict
|
||||
from aworld.cmd.data_model import AgentModel
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_agent_cache: Dict[str, AgentModel] = {}
|
||||
|
||||
|
||||
def list_agents(server_dir: str) -> Dict[str, AgentModel]:
|
||||
"""
|
||||
List all cached agents
|
||||
|
||||
Returns:
|
||||
Dict[str, AgentModel]: The map of agent models
|
||||
"""
|
||||
if len(_agent_cache) == 0:
|
||||
for m in _list_agents(server_dir):
|
||||
_agent_cache[m.id] = m
|
||||
return _agent_cache
|
||||
|
||||
|
||||
def _list_agents(server_dir: str) -> List[AgentModel]:
|
||||
agents_dir = os.path.join(server_dir, "agent_deploy")
|
||||
|
||||
if not os.path.exists(agents_dir):
|
||||
logger.warning(f"Agents directory {agents_dir} does not exist")
|
||||
return []
|
||||
|
||||
if agents_dir not in sys.path:
|
||||
sys.path.append(agents_dir)
|
||||
|
||||
agents = []
|
||||
for agent_id in os.listdir(agents_dir):
|
||||
if agent_id.startswith("_"):
|
||||
continue
|
||||
try:
|
||||
agent_path = os.path.join(agents_dir, agent_id)
|
||||
if os.path.isdir(agent_path):
|
||||
requirements_file = os.path.join(agent_path, "requirements.txt")
|
||||
if os.path.exists(requirements_file):
|
||||
p = subprocess.Popen(
|
||||
["pip", "install", "-U", "-r", requirements_file],
|
||||
cwd=agent_path,
|
||||
)
|
||||
p.wait()
|
||||
if p.returncode != 0:
|
||||
logger.error(
|
||||
f"Error installing requirements for agent {agent_id}, path {agent_path}"
|
||||
)
|
||||
continue
|
||||
|
||||
agent_file = os.path.join(agent_path, "agent.py")
|
||||
if os.path.exists(agent_file):
|
||||
try:
|
||||
instance = _get_agent_instance(agent_id)
|
||||
if hasattr(instance, "name"):
|
||||
name = instance.name()
|
||||
else:
|
||||
name = agent_id
|
||||
if hasattr(instance, "description"):
|
||||
description = instance.description()
|
||||
else:
|
||||
description = ""
|
||||
agent_model = AgentModel(
|
||||
id=agent_id,
|
||||
name=name,
|
||||
description=description,
|
||||
path=agent_path,
|
||||
instance=instance,
|
||||
)
|
||||
|
||||
agents.append(agent_model)
|
||||
logger.info(
|
||||
f"Loaded agent {agent_id} successfully, path {agent_path}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error loading agent {agent_id}: {traceback.format_exc()}"
|
||||
)
|
||||
continue
|
||||
else:
|
||||
logger.warning(f"Agent {agent_id} does not have agent.py file")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Error loading agent {agent_id}, path {agent_path} : {traceback.format_exc()}"
|
||||
)
|
||||
continue
|
||||
|
||||
return agents
|
||||
|
||||
|
||||
def _get_agent_instance(agent_name):
|
||||
try:
|
||||
agent_module = importlib.import_module(
|
||||
name=f"{agent_name}.agent",
|
||||
)
|
||||
except Exception as e:
|
||||
msg = f"Error loading agent {agent_name}, cwd:{os.getcwd()}, sys.path:{sys.path}: {traceback.format_exc()}"
|
||||
logger.error(msg)
|
||||
raise Exception(msg)
|
||||
|
||||
if hasattr(agent_module, "AWorldAgent"):
|
||||
agent = agent_module.AWorldAgent()
|
||||
return agent
|
||||
else:
|
||||
raise Exception(f"Agent {agent_name} does not have AWorldAgent class")
|
||||
@@ -0,0 +1,116 @@
|
||||
from abc import abstractmethod
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from typing import Dict, List
|
||||
import os
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from aworld import trace
|
||||
from aworld.cmd.data_model import (
|
||||
AgentModel,
|
||||
ChatCompletionMessage,
|
||||
ChatCompletionRequest,
|
||||
)
|
||||
from aworld.session.base_session_service import BaseSessionService
|
||||
from aworld.session.simple_session_service import SimpleSessionService
|
||||
from . import agent_loader
|
||||
from aworld.trace.config import ObservabilityConfig
|
||||
from aworld.trace.opentelemetry.memory_storage import InMemoryWithPersistStorage
|
||||
|
||||
|
||||
# bugfix for tracer exception
|
||||
trace.configure(ObservabilityConfig(trace_storage=(InMemoryWithPersistStorage())))
|
||||
|
||||
|
||||
class ChatCallBack:
|
||||
@abstractmethod
|
||||
async def on_chat_completion_request(
|
||||
self, server: "AgentServer", request: ChatCompletionRequest
|
||||
):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def on_chat_completion_end(
|
||||
self, server: "AgentServer", request: ChatCompletionRequest, final_response: str
|
||||
):
|
||||
pass
|
||||
|
||||
|
||||
class SessionChatCallBack(ChatCallBack):
|
||||
|
||||
async def on_chat_completion_request(
|
||||
self, server: "AgentServer", request: ChatCompletionRequest
|
||||
):
|
||||
await server.get_session_service().append_messages(
|
||||
request.user_id,
|
||||
request.session_id,
|
||||
request.messages[-1:],
|
||||
)
|
||||
|
||||
async def on_chat_completion_end(
|
||||
self, server: "AgentServer", request: ChatCompletionRequest, final_response: str
|
||||
):
|
||||
await server.get_session_service().append_messages(
|
||||
request.user_id,
|
||||
request.session_id,
|
||||
[
|
||||
ChatCompletionMessage(
|
||||
role="assistant",
|
||||
content=final_response,
|
||||
trace_id=request.trace_id,
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class AgentServer:
|
||||
server_id: str
|
||||
server_name: str
|
||||
server_dir: str
|
||||
session_service: BaseSessionService = None
|
||||
agent_instances: Dict[str, AgentModel] = {}
|
||||
chat_call_backs: List[ChatCallBack] = [SessionChatCallBack()]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
server_id: str,
|
||||
server_name: str,
|
||||
server_dir: str = os.getcwd(),
|
||||
session_service: BaseSessionService = SimpleSessionService(),
|
||||
):
|
||||
"""
|
||||
Initialize AgentServer
|
||||
"""
|
||||
self.server_id = server_id
|
||||
self.server_name = server_name
|
||||
self.server_dir = server_dir
|
||||
self.session_service = session_service
|
||||
# Load server global env
|
||||
load_dotenv(Path(self.server_dir) / ".env", override=True, verbose=True)
|
||||
# Load agent instances
|
||||
self.agent_instances = agent_loader.list_agents(self.server_dir)
|
||||
|
||||
def list_agents(self) -> Dict[str, AgentModel]:
|
||||
return self.agent_instances
|
||||
|
||||
def get_agent(self, agent_id: str) -> AgentModel:
|
||||
return self.agent_instances.get(agent_id)
|
||||
|
||||
def get_session_service(self) -> BaseSessionService:
|
||||
return self.session_service
|
||||
|
||||
async def on_chat_completion_request(self, request: ChatCompletionRequest):
|
||||
tasks = []
|
||||
for chat_call_back in self.chat_call_backs:
|
||||
tasks.append(chat_call_back.on_chat_completion_request(self, request))
|
||||
await asyncio.gather(*tasks)
|
||||
|
||||
async def on_chat_completion_end(
|
||||
self, request: ChatCompletionRequest, final_response: str
|
||||
):
|
||||
tasks = []
|
||||
for chat_call_back in self.chat_call_backs:
|
||||
tasks.append(
|
||||
chat_call_back.on_chat_completion_end(self, request, final_response)
|
||||
)
|
||||
await asyncio.gather(*tasks)
|
||||
@@ -0,0 +1,253 @@
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
import uuid
|
||||
|
||||
from pydantic import Field, BaseModel, ConfigDict
|
||||
|
||||
from aworld.output import (
|
||||
MessageOutput,
|
||||
AworldUI,
|
||||
Output,
|
||||
WorkSpace,
|
||||
)
|
||||
from aworld.output.artifact import Artifact, ArtifactType
|
||||
from aworld.output.base import StepOutput, ToolResultOutput
|
||||
from aworld.output.utils import consume_content
|
||||
from abc import ABC, abstractmethod
|
||||
from typing_extensions import override
|
||||
|
||||
|
||||
class ToolCard(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
tool_type: str = Field(None, description="tool type")
|
||||
tool_name: str = Field(None, description="tool name")
|
||||
function_name: str = Field(None, description="function name")
|
||||
tool_call_id: str = Field(None, description="tool call id")
|
||||
arguments: str = Field(None, description="arguments")
|
||||
results: str = Field(None, description="results")
|
||||
card_type: str = Field(None, description="card type")
|
||||
card_data: dict = Field(None, description="card data")
|
||||
artifacts: list = Field(default_factory=list, description="artifacts")
|
||||
|
||||
@staticmethod
|
||||
def from_tool_result(output: ToolResultOutput) -> "ToolCard":
|
||||
return ToolCard(
|
||||
tool_type=output.tool_type,
|
||||
tool_name=output.tool_name,
|
||||
function_name=output.origin_tool_call.function.name,
|
||||
tool_call_id=output.origin_tool_call.id,
|
||||
arguments=output.origin_tool_call.function.arguments,
|
||||
results=output.data,
|
||||
artifacts=[],
|
||||
)
|
||||
|
||||
|
||||
class BaseToolResultParser(ABC):
|
||||
|
||||
def __init__(self, tool_name: str = None):
|
||||
self.tool_name = tool_name or self.__class__.__name__
|
||||
|
||||
@abstractmethod
|
||||
async def parse(self, output: ToolResultOutput, workspace: WorkSpace):
|
||||
pass
|
||||
|
||||
|
||||
class DefaultToolResultParser(BaseToolResultParser):
|
||||
|
||||
@override
|
||||
async def parse(self, output: ToolResultOutput, workspace: WorkSpace):
|
||||
tool_card = ToolCard.from_tool_result(output)
|
||||
|
||||
tool_card.card_type = "tool_call_card_default"
|
||||
|
||||
# screenshots
|
||||
if (
|
||||
output.metadata.get("screenshots")
|
||||
and isinstance(output.metadata.get("screenshots"), list)
|
||||
and len(output.metadata.get("screenshots")) > 0
|
||||
):
|
||||
for _, screenshot in enumerate(output.metadata.get("screenshots")):
|
||||
image_artifact = Artifact(
|
||||
artifact_id=str(uuid.uuid4()),
|
||||
artifact_type=ArtifactType.IMAGE,
|
||||
content=screenshot.get("ossPath"),
|
||||
)
|
||||
await workspace.add_artifact(image_artifact)
|
||||
tool_card.artifacts.append(
|
||||
{
|
||||
"artifact_type": image_artifact.artifact_type.value,
|
||||
"artifact_id": image_artifact.artifact_id,
|
||||
}
|
||||
)
|
||||
|
||||
return f"""\
|
||||
\n\n**🔧 Tool: {tool_card.tool_name}#{tool_card.function_name}**\n\n
|
||||
```tool_card
|
||||
{json.dumps(tool_card.model_dump(), ensure_ascii=False, indent=2)}
|
||||
```\n
|
||||
"""
|
||||
|
||||
|
||||
class SearchToolResultParser(BaseToolResultParser):
|
||||
|
||||
@override
|
||||
async def parse(self, output: ToolResultOutput, workspace: WorkSpace):
|
||||
tool_card = ToolCard.from_tool_result(output)
|
||||
|
||||
query = ""
|
||||
try:
|
||||
args = json.loads(tool_card.arguments)
|
||||
query = args.get("query")
|
||||
# aworld search server
|
||||
if not query:
|
||||
query = args.get("query_list")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
result_items = []
|
||||
try:
|
||||
result_items = json.loads(tool_card.results)
|
||||
# aworld search server return url, not link
|
||||
if result_items and isinstance(result_items, list):
|
||||
for item in result_items:
|
||||
if not item.get("link", None) and item.get("url", None):
|
||||
item["link"] = item.get("url")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if len(result_items) > 0:
|
||||
tool_card.results = ""
|
||||
|
||||
tool_card.card_type = "tool_call_card_link_list"
|
||||
tool_card.card_data = {
|
||||
"title": "🔎 Google Search",
|
||||
"query": query,
|
||||
"search_items": result_items,
|
||||
}
|
||||
|
||||
artifact_id = str(uuid.uuid4())
|
||||
await workspace.create_artifact(
|
||||
artifact_type=ArtifactType.WEB_PAGES,
|
||||
artifact_id=artifact_id,
|
||||
content=result_items,
|
||||
metadata={
|
||||
"query": query,
|
||||
},
|
||||
)
|
||||
tool_card.artifacts.append(
|
||||
{
|
||||
"artifact_type": ArtifactType.WEB_PAGES.value,
|
||||
"artifact_id": artifact_id,
|
||||
}
|
||||
)
|
||||
|
||||
return f"""\
|
||||
\n\n**🔎 Search Results**\n\n
|
||||
```tool_card
|
||||
{json.dumps(tool_card.model_dump(), ensure_ascii=False, indent=2)}
|
||||
```\n
|
||||
"""
|
||||
|
||||
|
||||
class ToolResultParserFactory:
|
||||
def get_parser(self, tool_type: str, tool_name: str):
|
||||
if "search" in tool_name and ("search" in tool_name or tool_name == None):
|
||||
return SearchToolResultParser()
|
||||
else:
|
||||
return DefaultToolResultParser()
|
||||
|
||||
|
||||
@dataclass
|
||||
class AWorldWebAgentUI(AworldUI):
|
||||
session_id: str = Field(default="", description="session id")
|
||||
workspace: WorkSpace = Field(default=None, description="workspace")
|
||||
tool_result_parser_factory: ToolResultParserFactory = Field(
|
||||
default=ToolResultParserFactory, description="tool result parser factory"
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
session_id: str = None,
|
||||
workspace: WorkSpace = None,
|
||||
tool_result_parser_factory: ToolResultParserFactory = None,
|
||||
**kwargs,
|
||||
):
|
||||
"""
|
||||
Initialize MarkdownAworldUI
|
||||
Args:"""
|
||||
super().__init__(**kwargs)
|
||||
self.session_id = session_id
|
||||
self.workspace = workspace
|
||||
self.tool_result_parser_factory = (
|
||||
tool_result_parser_factory or ToolResultParserFactory()
|
||||
)
|
||||
|
||||
@override
|
||||
async def message_output(self, __output__: MessageOutput):
|
||||
"""
|
||||
Returns an async generator that yields each message item.
|
||||
"""
|
||||
# Sentinel object for queue completion
|
||||
_SENTINEL = object()
|
||||
|
||||
async def async_generator():
|
||||
async def __log_item(item):
|
||||
await queue.put(item)
|
||||
|
||||
from asyncio import Queue
|
||||
|
||||
queue = Queue()
|
||||
|
||||
async def consume_all():
|
||||
# Consume all relevant generators
|
||||
if __output__.reason_generator or __output__.response_generator:
|
||||
if __output__.reason_generator:
|
||||
await consume_content(__output__.reason_generator, __log_item)
|
||||
if __output__.response_generator:
|
||||
await consume_content(__output__.response_generator, __log_item)
|
||||
else:
|
||||
await consume_content(__output__.reasoning, __log_item)
|
||||
await consume_content(__output__.response, __log_item)
|
||||
# Only after all are done, put the sentinel
|
||||
await queue.put(_SENTINEL)
|
||||
|
||||
# Start the consumer in the background
|
||||
import asyncio
|
||||
|
||||
consumer_task = asyncio.create_task(consume_all())
|
||||
|
||||
while True:
|
||||
item = await queue.get()
|
||||
if item is _SENTINEL:
|
||||
break
|
||||
yield item
|
||||
await consumer_task # Ensure background task is finished
|
||||
|
||||
return async_generator()
|
||||
|
||||
@override
|
||||
async def tool_result(self, output: ToolResultOutput):
|
||||
"""
|
||||
tool_result
|
||||
"""
|
||||
parser = self.tool_result_parser_factory.get_parser(
|
||||
output.tool_type, output.tool_name
|
||||
)
|
||||
return await parser.parse(output, workspace=self.workspace)
|
||||
|
||||
@override
|
||||
async def step(self, output: StepOutput):
|
||||
emptyLine = "\n\n"
|
||||
if output.status == "START":
|
||||
return f"\n\n # {output.show_name} \n\n"
|
||||
elif output.status == "FINISHED":
|
||||
return f"{emptyLine}"
|
||||
elif output.status == "FAILED":
|
||||
return f"\n\n{output.name} 💥FAILED: reason is {output.data} {emptyLine}"
|
||||
else:
|
||||
return f"\n\n{output.name} ❓❓❓UNKNOWN#{output.status} {emptyLine}"
|
||||
|
||||
@override
|
||||
async def custom_output(self, output: Output):
|
||||
return output.data
|
||||
@@ -0,0 +1,175 @@
|
||||
import os
|
||||
import logging
|
||||
import traceback
|
||||
import asyncio
|
||||
import re
|
||||
import json
|
||||
import pickle
|
||||
from asyncio.tasks import Task
|
||||
from aworld.config.conf import AgentConfig
|
||||
from aworld.agents.llm_agent import Agent
|
||||
from typing import Dict, Union
|
||||
|
||||
from aworld.core.context.base import Context
|
||||
from aworld.utils.run_util import exec_agent
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SimpleSummaryCache:
|
||||
def __init__(self) -> None:
|
||||
self._cache_file = os.path.join(os.curdir, "data", "trace_summary_cache.pkl")
|
||||
self._cache: Dict[str, str] = {}
|
||||
self._load_cache()
|
||||
|
||||
def _load_cache(self):
|
||||
if os.path.exists(self._cache_file):
|
||||
try:
|
||||
with open(self._cache_file, "rb") as f:
|
||||
self._cache = pickle.load(f)
|
||||
except (pickle.PickleError, EOFError):
|
||||
logger.warning("Cache file is corrupted, creating new cache")
|
||||
if self._cache_file.exists():
|
||||
self._cache_file.unlink()
|
||||
|
||||
def _save_cache(self):
|
||||
serializable_cache = {
|
||||
k: v for k, v in self._cache.items() if not isinstance(v, Task)
|
||||
}
|
||||
try:
|
||||
with open(self._cache_file, "wb") as f:
|
||||
pickle.dump(serializable_cache, f)
|
||||
except pickle.PickleError:
|
||||
logger.error("Failed to save cache")
|
||||
|
||||
def add_to_cache(self, trace_id: str, value: Union[str, Task]):
|
||||
self._cache[trace_id] = value
|
||||
if not isinstance(value, Task):
|
||||
self._save_cache()
|
||||
|
||||
def get_value(self, trace_id: str) -> Union[str, Task]:
|
||||
return self._cache.get(trace_id)
|
||||
|
||||
def trace_exists(self, trace_id: str) -> bool:
|
||||
return trace_id in self._cache
|
||||
|
||||
|
||||
# _trace_summary_cache: Dict[str, Union[str, Task]] = {}
|
||||
_trace_summary_cache = SimpleSummaryCache()
|
||||
|
||||
trace_sys_prompt = "You are a helpful tracking summary agent."
|
||||
|
||||
trace_prompt = """
|
||||
you can use tracking tools to obtain tracking data and then summarize the main tasks completed by each agent and their token usage.
|
||||
You can identify which spans are agents, which spans are tool calls, and which spans are large model calls based on the following criteria:
|
||||
1 Agent span: the prefix for 'name' is 'event.agent.'
|
||||
2 LLM span: The prefix for 'name' is 'llm.'
|
||||
3 Tool span: The prefix for 'name' is 'event.tool.'
|
||||
|
||||
requirement:
|
||||
1. Please summarize and output separately for agents with different event.id.
|
||||
2. Agent Span with the same name but different event.id are also considered as different agents.
|
||||
3. There may be a parent-child relationship between agents. Please select the LLM span and Tool span from the nearest child span to the current agent for summarizing.
|
||||
4. Ensure that all agent spans have their own independent summaries, and the number of summaries is exactly the same as the number of agent spans. For example: {{"name":"event.agent.a","attributes":{{"event.id":"111"}},"children":[{{"name":"llm.gpt-4o"}},{{"name":"event.tool.1","children":[{{"name":"event.agent.a","attributes":{{"event.id":"222"}},"children":[{{"name":"llm.gpt-4o"}}]}}]}}]}}, both of the above two agent names are event.agent.a, but event.id is different and needs to be summarized separately for 111 and 222. So you need to identify all agent spans without any omissions, which is very important.
|
||||
5. Please output in the following standard JSON format without any additional explanatory text:
|
||||
[{{"agent":"947cc4c1b7ed406ab7fbf38b9d2b1f5a",,"summary":"xxx"}},{{}}]
|
||||
6. Pay attention to controlling the length of the summary, so that the overall output does not exceed your output length limit.
|
||||
Here are the trace_id: {task}
|
||||
"""
|
||||
|
||||
agent_config = None
|
||||
|
||||
|
||||
async def _do_summarize_trace(trace_id: str):
|
||||
logger.info(f"_do_summarize_trace trace_id: {trace_id}")
|
||||
global agent_config
|
||||
trace_agent = Agent(
|
||||
conf=agent_config,
|
||||
name="trace_agent",
|
||||
system_prompt=trace_sys_prompt,
|
||||
agent_prompt=trace_prompt,
|
||||
tool_names=["trace"],
|
||||
feedback_tool_result=True,
|
||||
)
|
||||
|
||||
if trace_agent.conf.llm_config.llm_api_key is None:
|
||||
logger.warning(
|
||||
"LLM_API_KEY_TRACE is not set, trace summarize will not be executed."
|
||||
)
|
||||
return ""
|
||||
try:
|
||||
res = await exec_agent(trace_id, trace_agent, Context())
|
||||
summary = _fetch_json_from_result(res.answer)
|
||||
_trace_summary_cache.add_to_cache(trace_id, summary)
|
||||
return summary
|
||||
except Exception as e:
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def summarize_trace(trace_id: str):
|
||||
global agent_config
|
||||
if agent_config is None:
|
||||
llm_provider = os.getenv("LLM_PROVIDER_TRACE", "openai")
|
||||
llm_model_name = os.getenv("LLM_MODEL_NAME_TRACE", None)
|
||||
llm_base_url = os.getenv("LLM_BASE_URL_TRACE", None)
|
||||
llm_api_key = os.getenv("LLM_API_KEY_TRACE", None)
|
||||
|
||||
if (
|
||||
not llm_provider
|
||||
or not llm_model_name
|
||||
or not llm_base_url
|
||||
or not llm_api_key
|
||||
):
|
||||
logger.warning(
|
||||
"LLM_MODEL_NAME_TRACE, LLM_BASE_URL_TRACE, LLM_API_KEY_TRACE is not set, trace summarize will not be executed."
|
||||
)
|
||||
return
|
||||
|
||||
agent_config = AgentConfig(
|
||||
llm_provider=os.getenv("LLM_PROVIDER_TRACE", "openai"),
|
||||
llm_model_name=os.getenv("LLM_MODEL_NAME_TRACE", None),
|
||||
llm_base_url=os.getenv("LLM_BASE_URL_TRACE", None),
|
||||
llm_api_key=os.getenv("LLM_API_KEY_TRACE", None),
|
||||
)
|
||||
llm_config = agent_config.llm_config
|
||||
if not _trace_summary_cache.trace_exists(trace_id):
|
||||
if (
|
||||
llm_config.llm_api_key is None
|
||||
or not llm_config.llm_base_url
|
||||
or not llm_config.llm_model_name
|
||||
):
|
||||
logger.warning(
|
||||
"LLM_MODEL_NAME_TRACE, LLM_BASE_URL_TRACE, LLM_API_KEY_TRACE is not set, trace summarize will not be executed."
|
||||
)
|
||||
return
|
||||
|
||||
task = asyncio.create_task(_do_summarize_trace(trace_id))
|
||||
_trace_summary_cache.add_to_cache(trace_id, task)
|
||||
|
||||
|
||||
async def get_summarize_trace(trace_id: str):
|
||||
if not _trace_summary_cache.trace_exists(trace_id):
|
||||
return None
|
||||
cached_value = _trace_summary_cache.get_value(trace_id)
|
||||
if isinstance(cached_value, Task):
|
||||
# try:
|
||||
# result = await cached_value
|
||||
# if isinstance(result, Task):
|
||||
# result = await result
|
||||
# _trace_summary_cache[trace_id] = _fetch_json_from_result(result)
|
||||
# except Exception as e:
|
||||
# logger.error(traceback.format_exc())
|
||||
return None
|
||||
return cached_value
|
||||
|
||||
|
||||
def _fetch_json_from_result(input_str):
|
||||
json_match = re.search(r"\[.*\]", input_str, re.DOTALL)
|
||||
if json_match:
|
||||
json_str = json_match.group(0)
|
||||
try:
|
||||
json.loads(json_str)
|
||||
return json_str
|
||||
except json.JSONDecodeError as e:
|
||||
logger.warning(f"_fetch_json_from_result json_str: {json_str} error: {e}")
|
||||
return ""
|
||||
@@ -0,0 +1,26 @@
|
||||
import subprocess
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def build_webui(force_rebuild: bool = False) -> str:
|
||||
webui_path = Path(__file__).parent.parent / "web" / "webui"
|
||||
static_path = webui_path / "dist"
|
||||
|
||||
if (not static_path.exists()) or force_rebuild:
|
||||
logger.warning(f"Build WebUI at {webui_path}")
|
||||
|
||||
try:
|
||||
subprocess.check_call(
|
||||
["sh", "-c", "npm install && npm run build"],
|
||||
cwd=webui_path,
|
||||
)
|
||||
logger.info("WebUI build successfully")
|
||||
except:
|
||||
logger.error(f"Failed to build WebUI at {webui_path}")
|
||||
sys.exit(1)
|
||||
|
||||
return static_path
|
||||
@@ -0,0 +1,32 @@
|
||||
import logging
|
||||
from fastapi import FastAPI
|
||||
import uvicorn
|
||||
|
||||
from aworld.cmd.utils.agent_server import AgentServer
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
agent_server = AgentServer(
|
||||
server_id="default_server",
|
||||
server_name="default_server",
|
||||
)
|
||||
|
||||
app.state.agent_server = agent_server
|
||||
|
||||
from .routers import chats, workspaces, sessions
|
||||
|
||||
app.include_router(chats.router, prefix=chats.prefix)
|
||||
app.include_router(workspaces.router, prefix=workspaces.prefix)
|
||||
app.include_router(sessions.router, prefix=sessions.prefix)
|
||||
|
||||
|
||||
def run_server(port, args=None, **kwargs):
|
||||
logger.info(f"Running API server on port {port}")
|
||||
uvicorn.run(
|
||||
app,
|
||||
host="0.0.0.0",
|
||||
port=port,
|
||||
)
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "web",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import logging
|
||||
import json
|
||||
from typing import Dict
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from aworld.cmd.data_model import AgentModel, ChatCompletionRequest
|
||||
from aworld.cmd.utils import agent_executor
|
||||
from aworld.cmd.utils.trace_summarize import summarize_trace
|
||||
from aworld.cmd.web.utils.users import get_user_id_from_jwt
|
||||
import aworld.trace as trace
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
prefix = "/api/agent"
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
@router.get("/models")
|
||||
async def list_agents(request: Request) -> Dict[str, AgentModel]:
|
||||
return request.app.state.agent_server.list_agents()
|
||||
|
||||
|
||||
@router.post("/chat/completions")
|
||||
async def chat_completion(
|
||||
form_data: ChatCompletionRequest,
|
||||
request: Request,
|
||||
user_id: str = Depends(get_user_id_from_jwt),
|
||||
) -> StreamingResponse:
|
||||
# Set user_id from JWT to form_data
|
||||
form_data.user_id = user_id
|
||||
|
||||
async def generate_stream():
|
||||
async with trace.span(
|
||||
"/chat/chat_completion", attributes={"model": form_data.model}
|
||||
) as span:
|
||||
form_data.trace_id = span.get_trace_id()
|
||||
async for chunk in agent_executor.stream_run(
|
||||
form_data, request.app.state.agent_server
|
||||
):
|
||||
yield f"data: {json.dumps(chunk.model_dump(), ensure_ascii=False)}\n\n"
|
||||
summarize_trace(form_data.trace_id)
|
||||
|
||||
return StreamingResponse(
|
||||
generate_stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,52 @@
|
||||
import logging
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from pydantic import BaseModel, Field
|
||||
from aworld.cmd.data_model import SessionModel
|
||||
from aworld.cmd.web.utils.users import get_user_id_from_jwt
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
prefix = "/api/session"
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
async def list_sessions(
|
||||
request: Request,
|
||||
user_id: str = Depends(get_user_id_from_jwt),
|
||||
) -> List[SessionModel]:
|
||||
return await request.app.state.agent_server.get_session_service().list_sessions(
|
||||
user_id
|
||||
)
|
||||
|
||||
|
||||
class CommonResponse(BaseModel):
|
||||
code: int = Field(..., description="The code")
|
||||
message: str = Field(..., description="The message")
|
||||
|
||||
@staticmethod
|
||||
def success(message: str = "success"):
|
||||
return CommonResponse(code=0, message=message)
|
||||
|
||||
@staticmethod
|
||||
def error(message: str):
|
||||
return CommonResponse(code=1, message=message)
|
||||
|
||||
|
||||
class DeleteSessionRequest(BaseModel):
|
||||
session_id: str = Field(..., description="The session id")
|
||||
|
||||
|
||||
@router.post("/delete")
|
||||
async def delete_session(
|
||||
request: DeleteSessionRequest, user_id: str = Depends(get_user_id_from_jwt)
|
||||
) -> CommonResponse:
|
||||
try:
|
||||
await request.app.state.agent_server.get_session_service().delete_session(
|
||||
user_id, request.session_id
|
||||
)
|
||||
return CommonResponse.success()
|
||||
except Exception as e:
|
||||
return CommonResponse.error(str(e))
|
||||
@@ -0,0 +1,50 @@
|
||||
import json
|
||||
import logging
|
||||
from fastapi import APIRouter
|
||||
from aworld.trace.server import get_trace_server
|
||||
from aworld.trace.server.util import build_trace_tree, get_agent_flow
|
||||
from aworld.cmd.utils.trace_summarize import get_summarize_trace
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
prefix = "/api/trace"
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
async def list_traces():
|
||||
storage = get_trace_server().get_storage()
|
||||
trace_data = []
|
||||
for trace_id in storage.get_all_traces():
|
||||
spans = storage.get_all_spans(trace_id)
|
||||
spans_sorted = sorted(spans, key=lambda x: x.start_time)
|
||||
trace_tree = build_trace_tree(spans_sorted)
|
||||
trace_data.append({
|
||||
'trace_id': trace_id,
|
||||
'root_span': trace_tree,
|
||||
})
|
||||
return {
|
||||
"data": trace_data
|
||||
}
|
||||
|
||||
|
||||
@router.get("/agent")
|
||||
async def get_agent_trace(trace_id: str):
|
||||
data = get_agent_flow(trace_id)
|
||||
await _add_trace_summary(trace_id, data.get('nodes'))
|
||||
return data
|
||||
|
||||
|
||||
async def _add_trace_summary(trace_id, spans):
|
||||
summary = await get_summarize_trace(trace_id)
|
||||
json_summary_dict = {}
|
||||
if summary:
|
||||
json_summary = json.loads(summary)
|
||||
json_summary_dict = {item['agent']: json.dumps(
|
||||
item) for item in json_summary}
|
||||
|
||||
for span in spans:
|
||||
if summary and "event_id" in span:
|
||||
span['summary'] = json_summary_dict.get(span['event_id'])
|
||||
span['attributes'] = None
|
||||
@@ -0,0 +1,74 @@
|
||||
import logging
|
||||
import os
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Query, Body
|
||||
|
||||
from aworld.output import WorkSpace, ArtifactType
|
||||
from aworld.output.utils import load_workspace
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
prefix = "/api/workspaces"
|
||||
|
||||
@router.get("/{workspace_id}/tree")
|
||||
async def get_workspace_tree(workspace_id: str):
|
||||
logging.info(f"get_workspace_tree: {workspace_id}")
|
||||
workspace = await get_workspace(workspace_id)
|
||||
return workspace.generate_tree_data()
|
||||
|
||||
|
||||
class ArtifactRequest(BaseModel):
|
||||
artifact_ids: Optional[List[str]] = None
|
||||
artifact_types: Optional[List[str]] = None
|
||||
|
||||
|
||||
@router.post("/{workspace_id}/artifacts")
|
||||
async def get_workspace_artifacts(workspace_id: str, request: ArtifactRequest):
|
||||
"""
|
||||
Get artifacts by workspace id and filter by a list of artifact types.
|
||||
Args:
|
||||
workspace_id: Workspace ID
|
||||
request: Request body containing optional artifact_types list
|
||||
Returns:
|
||||
Dict with filtered artifacts
|
||||
"""
|
||||
artifact_types = request.artifact_types
|
||||
if artifact_types:
|
||||
# Validate all types
|
||||
invalid_types = [t for t in artifact_types if t not in ArtifactType.__members__]
|
||||
if invalid_types:
|
||||
logging.error(f"Invalid artifact_types: {invalid_types}")
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Invalid artifact types: {invalid_types}")
|
||||
logging.info(f"Fetching artifacts of types: {artifact_types}")
|
||||
else:
|
||||
logging.info(f"Fetching all artifacts (no type filter)")
|
||||
|
||||
workspace = await get_workspace(workspace_id)
|
||||
all_artifacts = workspace.list_artifacts()
|
||||
filtered_artifacts = all_artifacts
|
||||
if request.artifact_ids:
|
||||
filtered_artifacts = [a for a in filtered_artifacts if a.artifact_id in request.artifact_ids]
|
||||
if artifact_types:
|
||||
filtered_artifacts = [a for a in filtered_artifacts if a.artifact_type.name in artifact_types]
|
||||
|
||||
return {
|
||||
"data": filtered_artifacts
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{workspace_id}/file/{artifact_id}/content")
|
||||
async def get_workspace_file_content(workspace_id: str, artifact_id: str):
|
||||
logging.info(f"get_workspace_file_content: {workspace_id}, {artifact_id}")
|
||||
workspace = await get_workspace(workspace_id)
|
||||
return {
|
||||
"data": workspace.get_file_content_by_artifact_id(artifact_id)
|
||||
}
|
||||
|
||||
|
||||
async def get_workspace(workspace_id: str) -> WorkSpace:
|
||||
workspace_type = os.environ.get("WORKSPACE_TYPE", "local")
|
||||
workspace_path = os.environ.get("WORKSPACE_PATH", "./data/workspaces")
|
||||
return await load_workspace(workspace_id, workspace_type, workspace_path)
|
||||
@@ -0,0 +1,4 @@
|
||||
from fastapi import Request
|
||||
|
||||
def get_user_id_from_jwt(request: Request) -> str:
|
||||
return f"default_user_001"
|
||||
@@ -0,0 +1,62 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from fastapi.responses import RedirectResponse
|
||||
import uvicorn
|
||||
import os
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from aworld.cmd.utils.agent_server import AgentServer
|
||||
from aworld.cmd.utils.webui_builder import build_webui
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return RedirectResponse("/index.html")
|
||||
|
||||
agent_server = AgentServer(
|
||||
server_id="default_server",
|
||||
server_name="default_server",
|
||||
)
|
||||
|
||||
app.state.agent_server = agent_server
|
||||
|
||||
from .routers import chats, workspaces, sessions, traces # noqa
|
||||
|
||||
app.include_router(chats.router, prefix=chats.prefix)
|
||||
app.include_router(workspaces.router, prefix=workspaces.prefix)
|
||||
app.include_router(sessions.router, prefix=sessions.prefix)
|
||||
app.include_router(traces.router, prefix=traces.prefix)
|
||||
|
||||
|
||||
static_path = build_webui(force_rebuild=os.getenv("AWORLD_WEB_UI_FORCE_REBUILD", False))
|
||||
logger.info(f"Mounting static files from {static_path}")
|
||||
app.mount("/", StaticFiles(directory=static_path, html=True), name="static")
|
||||
|
||||
|
||||
class TimeoutMiddleware(BaseHTTPMiddleware):
|
||||
def __init__(self, app, timeout: int = 300):
|
||||
super().__init__(app)
|
||||
self.timeout = timeout
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
try:
|
||||
return await asyncio.wait_for(call_next(request), timeout=self.timeout)
|
||||
except asyncio.TimeoutError:
|
||||
return Response("Request timeout", status_code=408)
|
||||
|
||||
|
||||
app.add_middleware(TimeoutMiddleware, timeout=300)
|
||||
|
||||
|
||||
def run_server(port, args=None, **kwargs):
|
||||
logger.info(f"Running Web server on port {port}")
|
||||
uvicorn.run(
|
||||
app,
|
||||
host="0.0.0.0",
|
||||
port=port,
|
||||
)
|
||||
@@ -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