From ff94b4f08ddd9d726eab84bf4052ec7aea124cd3 Mon Sep 17 00:00:00 2001 From: yuren <317895128@qq.com> Date: Wed, 11 Nov 2026 22:15:14 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=9F=E8=83=BD=EF=BC=9A=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=B4=BB=E5=8A=A8=E6=80=A7=E8=83=BD=E7=80=91=E5=B8=83=E4=B8=8E?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E8=8A=82=E7=82=B9=E5=88=86=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 接入模型首 token、工具排队与执行、SSE 到达及前端绘制计时,并保存执行轨迹。 支持工具列表、性能瀑布、调用节点切换、双向定位、节点详情与真实历史回放。 补齐取消收尾、默认折叠、手动打开详情和子任务轨迹关联。 仅包含本功能生产代码及瀑布运行资源,排除图表功能调整、测试、验收数据与本地配置。 验证暂存区独立副本:后端 60 项、前端 26 项通过;TypeScript 和 ESLint 检查通过。 --- backend/app/api/chat.py | 17 +- backend/app/mcp/client.py | 70 +++++- backend/app/provider/openai_compat.py | 8 + backend/app/session/llm.py | 63 +++-- backend/app/session/processor.py | 24 +- backend/app/session/prompt.py | 11 +- backend/app/session/tool_executor.py | 161 ++++++++++++- backend/app/streaming/events.py | 14 +- backend/app/streaming/manager.py | 43 +++- backend/app/streaming/trace.py | 181 ++++++++++++++ backend/app/streaming/trace_api.py | 110 +++++++++ backend/app/tool/builtin/code_execute.py | 16 +- .../public/vendor/1.0.59/request-waterfall.js | 44 ++++ .../vendor/request-waterfall.PROVENANCE.md | 11 + .../components/activity/activity-panel.tsx | 153 +----------- .../components/activity/activity-summary.tsx | 27 ++- .../activity/execution-activity-panel.tsx | 225 ++++++++++++++++++ .../src/components/activity/tool-call-row.tsx | 28 ++- .../src/components/activity/trace-graph.tsx | 103 ++++++++ .../activity/trace-render-probe.tsx | 12 + .../activity/trace-studio.module.css | 103 ++++++++ .../components/activity/trace-waterfall.tsx | 168 +++++++++++++ .../messages/assistant-message-group.tsx | 8 +- .../components/messages/assistant-message.tsx | 51 ++-- .../components/messages/message-content.tsx | 23 +- .../src/components/messages/message-list.tsx | 6 +- frontend/src/hooks/use-chat.ts | 10 +- frontend/src/lib/execution-trace.ts | 209 ++++++++++++++++ frontend/src/lib/session-stream-registry.ts | 10 + frontend/src/lib/sse.ts | 17 +- frontend/src/lib/trace-layout.ts | 141 +++++++++++ frontend/src/lib/trace-replay.ts | 23 ++ frontend/src/lib/trace-view-spans.ts | 38 +++ frontend/src/lib/trace-view-state.ts | 15 ++ frontend/src/lib/trace-waterfall-state.ts | 27 +++ frontend/src/stores/activity-store.ts | 13 +- frontend/src/stores/execution-trace-store.ts | 72 ++++++ frontend/src/types/execution-trace.ts | 51 ++++ frontend/src/types/message.ts | 2 + frontend/src/types/streaming.ts | 2 + 40 files changed, 2082 insertions(+), 228 deletions(-) create mode 100644 backend/app/streaming/trace.py create mode 100644 backend/app/streaming/trace_api.py create mode 100644 frontend/public/vendor/1.0.59/request-waterfall.js create mode 100644 frontend/public/vendor/request-waterfall.PROVENANCE.md create mode 100644 frontend/src/components/activity/execution-activity-panel.tsx create mode 100644 frontend/src/components/activity/trace-graph.tsx create mode 100644 frontend/src/components/activity/trace-render-probe.tsx create mode 100644 frontend/src/components/activity/trace-studio.module.css create mode 100644 frontend/src/components/activity/trace-waterfall.tsx create mode 100644 frontend/src/lib/execution-trace.ts create mode 100644 frontend/src/lib/trace-layout.ts create mode 100644 frontend/src/lib/trace-replay.ts create mode 100644 frontend/src/lib/trace-view-spans.ts create mode 100644 frontend/src/lib/trace-view-state.ts create mode 100644 frontend/src/lib/trace-waterfall-state.ts create mode 100644 frontend/src/stores/execution-trace-store.ts create mode 100644 frontend/src/types/execution-trace.ts diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 23088d0..6d76b62 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -45,7 +45,10 @@ logger = logging.getLogger(__name__) +from app.streaming.trace_api import router as trace_router + router = APIRouter() +router.include_router(trace_router) _MANUAL_COMPACTION_MIN_USAGE_RATIO = 0.5 @@ -78,13 +81,19 @@ def _on_task_done(task: asyncio.Task[None], *, job: GenerationJob) -> None: async def _run_with_semaphore(sm: StreamManager, job: GenerationJob, coro) -> None: """Run generation under the concurrency semaphore.""" + job.trace._emit(job.trace.spans[job.trace.root_id]) + queue_span = job.trace.start('生成任务排队', '调度', parent_id=job.trace.root_id) try: await asyncio.wait_for(sm._semaphore.acquire(), timeout=30) except asyncio.TimeoutError: + job.trace.finish(queue_span, 'error') + job.trace.close('error') + coro.close() job.publish(SSEEvent(AGENT_ERROR, {"error_message": "Server is busy. Please try again shortly."})) job.complete() return try: + job.trace.finish(queue_span) await coro finally: sm._semaphore.release() @@ -431,13 +440,17 @@ async def event_generator(): @router.post("/chat/abort") -async def abort_generation(sm: StreamManagerDep, body: AbortRequest) -> dict: +async def abort_generation(sm: StreamManagerDep, body: AbortRequest, session_factory: SessionFactoryDep) -> dict: """Abort an active generation.""" job = sm.get_job(body.stream_id) if job is None: return {"status": "not_found"} job.abort() - return {"status": "aborted"} + try: + await job.trace.persist(session_factory) + except Exception: + logger.warning('Failed to persist aborted execution trace', exc_info=True) + return {"status": "aborted", "execution_trace": job.trace.snapshot()} @router.get("/chat/active") diff --git a/backend/app/mcp/client.py b/backend/app/mcp/client.py index 5544de7..1fc62f8 100644 --- a/backend/app/mcp/client.py +++ b/backend/app/mcp/client.py @@ -206,7 +206,75 @@ async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> CallTool """Call a tool on the MCP server.""" if self._session is None: raise RuntimeError(f"MCP server '{self.name}' is not connected") - return await self._session.call_tool(tool_name, arguments) + from app.streaming.trace import current_trace, safe_value + import json + active = current_trace() + if active is None: + return await self._session.call_tool(tool_name, arguments) + trace, parent = active + sent = trace.now() + anchor = None + uncertainty = None + + def import_span(raw): + nonlocal anchor, uncertainty + if trace.completed: + return + if not isinstance(raw, dict) or not isinstance(raw.get('id'), str): + return + if anchor is None: + received = trace.now() + anchor = (sent + received) / 2 + uncertainty = (received - sent) / 2 + key = f'mcp-{parent}-{raw["id"][:64]}' + if len(trace.spans) >= 2000 and key not in trace.spans: + return + try: + start = max(0.0, float(raw['startMs'])) + duration = max(0.0, float(raw['durationMs'])) + import math + if not math.isfinite(start + duration): + return + except (KeyError, TypeError, ValueError): + return + span = {'id': key, 'parentId': f'mcp-{parent}-{raw["parentId"][:64]}' if raw.get('parentId') else parent, + 'name': str(raw.get('name', 'MCP phase'))[:120], 'service': str(raw.get('service', self.name))[:60], + 'kind': 'phase', 'startMs': anchor + start, 'durationMs': duration, + 'status': raw.get('status') if raw.get('status') in {'ok', 'running', 'error', 'cancelled'} else 'incomplete', + 'attributes': {**safe_value(raw.get('attributes') or {}), + 'clock': 'remote monotonic; start aligned by first progress RTT midpoint', + 'alignment_uncertainty_ms': uncertainty, 'connector': self.name}} + trace.spans[key] = span + trace._emit(span) + + async def on_progress(progress, total, message): + if not message or len(message) > 30000: + return + try: + data = json.loads(message) + if data.get('type') == 'codata.trace.v1': + import_span(data.get('span')) + except (ValueError, TypeError, AttributeError): + return + + result = await self._session.call_tool(tool_name, arguments, progress_callback=on_progress) + if trace.completed: + return result + meta = getattr(result, 'meta', None) or {} + remote = meta.get('codata_trace') or {} + if anchor is not None and isinstance(remote.get('duration_ms'), (int, float)): + corrected = max(sent, min(anchor, trace.now() - remote['duration_ms'])) + shift = corrected - anchor + if shift: + for span in trace.spans.values(): + if span['id'].startswith(f'mcp-{parent}-'): + span['startMs'] += shift + trace._emit(span) + anchor = corrected + # Final metadata reconciles missed notifications without duplicating spans. + for span in remote.get('spans', [])[:1000]: + import_span(span) + return result def tool_id(self, tool_name: str) -> str: """Generate a unique tool ID for a tool from this server.""" diff --git a/backend/app/provider/openai_compat.py b/backend/app/provider/openai_compat.py index 2c7697d..c99a549 100644 --- a/backend/app/provider/openai_compat.py +++ b/backend/app/provider/openai_compat.py @@ -188,6 +188,9 @@ async def stream_chat( tool_call_accumulators: dict[int, dict[str, Any]] = {} had_any_content = False # Track whether the stream produced any content + from app.streaming.trace import ProviderTiming + timing = ProviderTiming() + timing_status = 'ok' try: stream = await self._client.chat.completions.create(**kwargs) async for chunk in stream: @@ -201,6 +204,8 @@ async def stream_chat( getattr(delta, "reasoning_content", None) or getattr(delta, "reasoning", None) ) + if reasoning_text or delta.content or delta.tool_calls: + timing.first_token() if reasoning_text: had_any_content = True yield StreamChunk(type="reasoning-delta", data={"text": reasoning_text}) @@ -289,8 +294,11 @@ async def stream_chat( ) except Exception as e: + timing_status = 'error' logger.error("Stream error for model %s: %s", model, e, exc_info=True) yield StreamChunk(type="error", data={"message": str(e)}) + finally: + timing.finish(timing_status) def _build_messages( self, diff --git a/backend/app/session/llm.py b/backend/app/session/llm.py index 744f5ec..087fc4b 100644 --- a/backend/app/session/llm.py +++ b/backend/app/session/llm.py @@ -10,11 +10,13 @@ from __future__ import annotations from typing import Any, AsyncIterator +from contextlib import nullcontext from app.provider.base import BaseProvider from app.schemas.agent import AgentInfo from app.schemas.provider import StreamChunk from app.tool.registry import ToolRegistry +from app.streaming.trace import trace_span async def stream_llm( @@ -30,6 +32,7 @@ async def stream_llm( exclude_tools: set[str] | None = None, discovered_tools: set[str] | None = None, response_format: dict[str, Any] | None = None, + trace_attributes: dict[str, Any] | None = None, ) -> AsyncIterator[StreamChunk]: """Unified LLM streaming call. @@ -38,18 +41,50 @@ async def stream_llm( most providers do not support both simultaneously. """ # Resolve tool specs for this agent; disable when structured output is requested - tool_specs = None if response_format else tool_registry.to_openai_specs( - agent, exclude=exclude_tools, discovered=discovered_tools, + from app.streaming.trace import current_trace + import time + attrs = {'model': model_id, 'provider': provider.id, **(trace_attributes or {})} + active = current_trace() + if active and attrs.get('attempt', 1) > 1: + previous = [s for s in active[0].spans.values() if s['kind'] == 'model' and s['attributes'].get('message_id') == attrs.get('message_id')] + if previous: + attrs['retry_of'] = previous[-1]['id'] + trace = active[0] if active else None + model_id_span = trace.start('模型响应 / 参数准备', '模型', kind='model', parent_id=active[1], attributes=attrs) if active else '' + # Do not hold a ContextVar token across an async-generator yield: early + # cancellation may close that generator from a different asyncio context. + with trace.bind(model_id_span) if trace else nullcontext(): + with trace_span('本地准备与工具协议装配', '调度'): + tool_specs = None if response_format else tool_registry.to_openai_specs( + agent, exclude=exclude_tools, discovered=discovered_tools, + ) + stream = provider.stream_chat( + model_id, messages, system=system_prompt, tools=tool_specs if tool_specs else None, + temperature=agent.temperature, max_tokens=max_tokens, extra_body=extra_body, + response_format=response_format, ) - - async for chunk in provider.stream_chat( - model_id, - messages, - system=system_prompt, - tools=tool_specs if tool_specs else None, - temperature=agent.temperature, - max_tokens=max_tokens, - extra_body=extra_body, - response_format=response_format, - ): - yield chunk + wait_ms = 0.0 + status = 'ok' + try: + while True: + started = time.perf_counter_ns() + try: + with trace.bind(model_id_span) if trace else nullcontext(): + chunk = await anext(stream) + except StopAsyncIteration: + break + finally: + wait_ms += (time.perf_counter_ns() - started) / 1_000_000 + if chunk.type == 'error': + status = 'error' + if trace and chunk.type == 'tool-call': + chunk.data['_trace_model_span_id'] = model_id_span + yield chunk + except BaseException: + status = 'cancelled' + raise + finally: + await stream.aclose() + if trace: + trace.finish(model_id_span, status, provider_await_ms=wait_ms, + duration_note='总跨度含流消费 / 本地调度等待,provider_await_ms 为等待提供商分块累计,不能当独立连续跨度') diff --git a/backend/app/session/processor.py b/backend/app/session/processor.py index 0af0964..c06c875 100644 --- a/backend/app/session/processor.py +++ b/backend/app/session/processor.py @@ -403,6 +403,7 @@ async def run_generation( """ from app.session.prompt import SessionPrompt + job.trace._emit(job.trace.spans[job.trace.root_id]) try: prompt = SessionPrompt( job, @@ -414,7 +415,8 @@ async def run_generation( index_manager=index_manager, skip_user_message=skip_user_message, ) - await prompt.run() + with job.trace.bind(): + await prompt.run() except IntegrityError: # Session was deleted while generation was in-flight — notify frontend # so it can exit the generating state, then stop. @@ -423,14 +425,26 @@ async def run_generation( job.session_id, job.stream_id, ) + job.trace.close('cancelled') job.publish(SSEEvent(DONE, { "session_id": job.session_id, "finish_reason": "aborted", })) except Exception: logger.exception("Generation error for stream %s", job.stream_id) + job.trace.close('error') + try: + await job.trace.persist(session_factory) + except Exception: + logger.warning('Failed to persist failed trace', exc_info=True) job.publish(SSEEvent(AGENT_ERROR, {"error_message": "An internal error occurred. Please try again."})) finally: + if not job.trace.completed: + job.trace.close('cancelled' if job.abort_event.is_set() else 'error') + try: + await job.trace.persist(session_factory) + except Exception: + logger.warning('Failed to persist execution trace', exc_info=True) try: from app.tool.builtin.todo import clear_in_progress_todos @@ -567,6 +581,7 @@ async def process(self) -> Literal["continue", "stop", "compact"]: exclude_tools=_exclude_tools, discovered_tools=sp.discovered_tools, response_format=sp.request.format, + trace_attributes={'step': sp.step, 'attempt': attempt + 1, 'message_id': self._assistant_msg_id}, ): if job.abort_event.is_set(): break @@ -698,6 +713,7 @@ async def process(self) -> Literal["continue", "stop", "compact"]: "tool": _tool.id, "call_id": _ci, "arguments": _ta, "session_id": job.session_id, "message_id": self._assistant_msg_id, + "time_start": datetime.datetime.now(datetime.timezone.utc).isoformat(), })) # Build context @@ -734,6 +750,8 @@ async def process(self) -> Literal["continue", "stop", "compact"]: tool_name=_tool.id, tool_args=_ta, call_id=_ci, ctx=_ctx, timeout=_cfg().tool_timeout, + producer_span_id=str(_tc.get('_trace_model_span_id', '')), + retry_of_call_id=_tc.get('retry_of_call_id'), )) _exec_metadata[_exec_index] = { "tool_part_id": _tpid, @@ -1092,6 +1110,8 @@ async def process(self) -> Literal["continue", "stop", "compact"]: "output": result.output[:500] if result.output else "", "title": result.title, "metadata": result.metadata, + "time_start": exec_result.time_start, + "time_end": exec_result.time_end, }, ) ) @@ -1193,6 +1213,8 @@ async def process(self) -> Literal["continue", "stop", "compact"]: "output": persist_output, "title": result.title, "metadata": result.metadata, + "time_start": exec_result.time_start, + "time_end": exec_result.time_end, }, }, ) diff --git a/backend/app/session/prompt.py b/backend/app/session/prompt.py index 0568bab..bd99cd1 100644 --- a/backend/app/session/prompt.py +++ b/backend/app/session/prompt.py @@ -274,7 +274,9 @@ def system_prompt(self) -> str | list[dict[str, Any]]: async def run(self) -> None: """Main entry point: setup → loop → post-loop.""" - await self._setup() + from app.streaming.trace import trace_span + with trace_span('会话校验与上下文装配', '调度'): + await self._setup() await self._loop() await self._post_loop() @@ -772,10 +774,12 @@ async def _loop(self) -> None: "agent": self.agent.name, "model_id": self.model_id, "provider_id": self.provider.id, + "trace_id": self.job.stream_id, }, ) self.assistant_msg_id = assistant_msg.id self.generation_message_ids.append(assistant_msg.id) + self.job.trace.message_ids.append(assistant_msg.id) # Execute one LLM step — processor handles streaming + tool dispatch processor: SessionProcessor = SessionProcessor( @@ -1215,6 +1219,11 @@ async def _post_loop(self) -> None: logger.warning("Analysis memory queue submission failed", exc_info=True) # Publish DONE to unlock the frontend UI. + self.job.trace.close('cancelled' if self.job.abort_event.is_set() else 'error' if self.finish_reason == 'error' else 'ok') + try: + await self.job.trace.persist(self.session_factory) + except Exception: + logger.warning('Failed to persist execution trace', exc_info=True) self.job.publish( SSEEvent( DONE, diff --git a/backend/app/session/tool_executor.py b/backend/app/session/tool_executor.py index 9ec0e35..0c5c8bb 100644 --- a/backend/app/session/tool_executor.py +++ b/backend/app/session/tool_executor.py @@ -15,7 +15,8 @@ import asyncio import logging from dataclasses import dataclass -from typing import Any +from datetime import datetime, timezone +from typing import Any, Callable from app.tool.base import ToolDefinition, ToolResult from app.tool.context import ToolContext @@ -40,6 +41,14 @@ class ToolCallInfo: call_id: str ctx: ToolContext timeout: float = 300.0 + trace: Any = None + trace_span_id: str = '' + queue_span_id: str = '' + producer_span_id: str = '' + retry_of_call_id: str | None = None + execution_span_id: str = '' + on_started: Callable[['ToolCallInfo'], None] | None = None + on_finished: Callable[['ToolCallInfo'], None] | None = None @dataclass @@ -54,9 +63,11 @@ class ToolExecutionResult: error: Exception | None = None timed_out: bool = False aborted_by_sibling: bool = False + time_start: str | None = None + time_end: str | None = None -async def _execute_single(info: ToolCallInfo) -> ToolExecutionResult: +async def _execute_single_inner(info: ToolCallInfo) -> ToolExecutionResult: """Execute a single tool call with timeout and error handling.""" if info.ctx.is_aborted: return ToolExecutionResult( @@ -88,6 +99,46 @@ async def _execute_single(info: ToolCallInfo) -> ToolExecutionResult: ) +async def _execute_single(info: ToolCallInfo) -> ToolExecutionResult: + """Measure actual scheduling delay, including the exclusive queue.""" + trace = info.trace + time_start = datetime.now(timezone.utc).isoformat() + if trace: + execution_started = trace.now() + trace.finish(info.queue_span_id, end_ms=execution_started) + execution = trace.start('工具执行', '工具', parent_id=info.trace_span_id, + start_ms=execution_started,attributes={'call_id': info.call_id}) + info.execution_span_id = execution + if info.on_started: + info.on_started(info) + try: + if trace: + with trace.bind(execution): + result = await _execute_single_inner(info) + else: + result = await _execute_single_inner(info) + result.time_start = time_start + result.time_end = datetime.now(timezone.utc).isoformat() + if trace: + execution_ended = trace.now() + status = 'cancelled' if result.aborted_by_sibling or isinstance(result.error, asyncio.CancelledError) else 'error' if result.error or result.timed_out or (result.result and result.result.error) else 'ok' + trace.finish(execution, status, end_ms=execution_ended) + trace.finish(info.trace_span_id, status, end_ms=execution_ended,time_start=result.time_start, time_end=result.time_end, + timed_out=result.timed_out, + output_preview=(str(result.result.output)[:2000] if result.result else ''), + error_preview=str(result.result.error or '')[:500] if result.result else type(result.error).__name__ if result.error else '') + return result + except BaseException: + if trace: + stopped=trace.now() + trace.finish(execution, 'cancelled',end_ms=stopped) + trace.finish(info.trace_span_id, 'cancelled',end_ms=stopped) + raise + finally: + if info.on_finished: + info.on_finished(info) + + class StreamingToolExecutor: """Manages tool execution during and after LLM streaming. @@ -110,6 +161,78 @@ def __init__(self, abort_event: asyncio.Event) -> None: # Sibling abort: set when a bash tool errors, cancels other concurrent tasks self._sibling_errored = False self._sibling_error_desc = "" + self._parallel_batches: dict[str, dict[str, Any]] = {} + self._collecting = False + + def _parallel_submitted(self, info: ToolCallInfo) -> None: + # A fork means the executor actually created independent safe tasks + # for this model response. Tiny synchronous bodies may not overlap; + # peak execution concurrency is recorded separately, without pretending. + if not info.trace or info.trace.completed or not info.trace_span_id or not info.tool.is_concurrency_safe: + return + batch = self._parallel_batches.setdefault(info.producer_span_id, { + 'members': [], 'active': set(), 'peak': 0, 'span': '', 'join': '', 'trace': info.trace, + }) + batch['members'].append(info) + if len(batch['members']) < 2: + return + trace = info.trace + members = [item.trace_span_id for item in batch['members']] + start = min(trace.spans[key]['startMs'] for key in members) + if not batch['span']: + batch['span'] = trace.start('并行分支', '调度', parent_id=trace.root_id, start_ms=start, + attributes={'group_kind':'parallel', 'dispatch_strategy':'concurrent_tasks', + 'timing_basis':'first submission to last member result; actual overlap shown in child spans'}) + if not batch['span']: + return + batch['join'] = trace.start('结果汇合', '调度', parent_id=batch['span'], start_ms=start, + attributes={'checkpoint':'join', 'timing_basis':'same batch wall time, not additional serial cost'}) + group = trace.spans[batch['span']] + group['startMs'] = min(group['startMs'], start) + group['attributes'].update(group_members=members, join_span_id=batch['join'], + active_count=len(batch['active']), peak_concurrency=batch['peak']) + trace._emit(group) + if batch['join']: + trace.spans[batch['join']]['startMs'] = group['startMs'] + trace.spans[batch['join']]['attributes']['group_members'] = members + trace._emit(trace.spans[batch['join']]) + for item in batch['members']: + span = trace.spans[item.trace_span_id] + span['parentId'] = batch['span'] + span['attributes']['parallel_group_id'] = batch['span'] + trace._emit(span) + + def _parallel_started(self, info: ToolCallInfo) -> None: + batch = self._parallel_batches.get(info.producer_span_id) + if not batch or info.trace.completed or not info.tool.is_concurrency_safe: + return + batch['active'].add(info.call_id) + batch['peak'] = max(batch['peak'], len(batch['active'])) + if batch['span']: + group = info.trace.spans[batch['span']] + group['attributes'].update(active_count=len(batch['active']), peak_concurrency=batch['peak']) + info.trace._emit(group) + + def _finish_parallel_batch(self, batch: dict[str, Any]) -> None: + if not batch['span'] or not self._collecting or batch['trace'].completed: + return + trace = batch['trace'] + members = [trace.spans[item.trace_span_id] for item in batch['members']] + if any(span['status']=='running' for span in members): + return + ended = max(span['startMs']+span['durationMs'] for span in members) + status = 'cancelled' if any(span['status']=='cancelled' for span in members) else 'ok' + failed = sum(span['status']=='error' for span in members) + trace.spans[batch['span']]['attributes'].update(active_count=0, peak_concurrency=batch['peak']) + trace.finish(batch['join'], status, end_ms=ended, failed_count=failed) + trace.finish(batch['span'], status, end_ms=ended, failed_count=failed) + + def _parallel_finished(self, info: ToolCallInfo) -> None: + batch = self._parallel_batches.get(info.producer_span_id) + if not batch or not info.tool.is_concurrency_safe: + return + batch['active'].discard(info.call_id) + self._finish_parallel_batch(batch) def submit(self, info: ToolCallInfo) -> None: """Submit a tool for execution. @@ -118,6 +241,28 @@ def submit(self, info: ToolCallInfo) -> None: Exclusive tools are queued for sequential execution after streaming. """ self._submission_order.append(info.index) + info.on_started = self._parallel_started + info.on_finished = self._parallel_finished + from app.streaming.trace import current_trace + active = current_trace() + if active: + info.trace, producer = active + info.trace_span_id = info.trace.start(info.tool_name, '工具', kind='tool', parent_id=info.trace.root_id, + attributes={'call_id': info.call_id, 'message_id': info.ctx.message_id, + 'producer_span_id': info.producer_span_id or producer, 'input': info.tool_args, + 'concurrent': info.tool.is_concurrency_safe, + 'timing_basis':'submission to result ready; queue and execution share boundary'}) + info.queue_span_id = info.trace.start('工具排队', '工具排队', parent_id=info.trace_span_id, + start_ms=info.trace.spans[info.trace_span_id]['startMs'] if info.trace_span_id else None) + if info.retry_of_call_id and info.trace_span_id: + previous = next((s for s in info.trace.spans.values() if s['kind']=='tool' + and s['name']==info.tool_name and s['attributes'].get('call_id')==info.retry_of_call_id + and s['status'] in ('error','cancelled')), None) + if previous: + info.trace.spans[info.trace_span_id]['attributes'].update( + retry_of=previous['id'], relation_basis='explicit executor retry_of_call_id') + info.trace._emit(info.trace.spans[info.trace_span_id]) + self._parallel_submitted(info) if info.tool.is_concurrency_safe: task = asyncio.create_task( @@ -143,6 +288,7 @@ async def collect(self) -> list[ToolExecutionResult]: 2. Execute exclusive tools sequentially 3. Return results sorted by submission order """ + self._collecting = True # 1. Collect concurrent results for info, task in self._concurrent_tasks: try: @@ -171,6 +317,11 @@ async def collect(self) -> list[ToolExecutionResult]: except asyncio.CancelledError: # Task was cancelled by sibling abort or external abort + if info.trace: + stopped=info.trace.now() + info.trace.finish(info.queue_span_id,'cancelled',end_ms=stopped) + info.trace.finish(info.execution_span_id,'cancelled',end_ms=stopped) + info.trace.finish(info.trace_span_id,'cancelled',end_ms=stopped) msg = ( f"Cancelled: parallel tool call {self._sibling_error_desc} errored" if self._sibling_errored @@ -189,9 +340,15 @@ async def collect(self) -> list[ToolExecutionResult]: error=e, ) + for batch in self._parallel_batches.values(): + self._finish_parallel_batch(batch) + # 2. Execute exclusive tools sequentially for info in self._exclusive_queue: if self._abort.is_set() or self._sibling_errored: + if info.trace: + info.trace.finish(info.queue_span_id, 'cancelled') + info.trace.finish(info.trace_span_id, 'cancelled') msg = ( f"Cancelled: parallel tool call {self._sibling_error_desc} errored" if self._sibling_errored diff --git a/backend/app/streaming/events.py b/backend/app/streaming/events.py index 7dcc2ac..79ab4ac 100644 --- a/backend/app/streaming/events.py +++ b/backend/app/streaming/events.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import time from dataclasses import dataclass, field from typing import Any @@ -14,6 +15,7 @@ class SSEEvent: event: str # event type name data: dict[str, Any] = field(default_factory=dict) id: int | None = None # monotonic event ID for replay + published_perf_ns: int | None = None def encode(self) -> str: """Encode as SSE wire format.""" @@ -21,7 +23,17 @@ def encode(self) -> str: if self.id is not None: lines.append(f"id: {self.id}") lines.append(f"event: {self.event}") - lines.append(f"data: {json.dumps(self.data, default=str)}") + if self.published_perf_ns is not None: + encoding_started = time.perf_counter_ns() + encoded = json.dumps({k:v for k,v in self.data.items() if k != '_delivery'}, default=str) + encoding_ms = (time.perf_counter_ns() - encoding_started) / 1_000_000 + # Ready-to-send, before ASGI/TCP. Do not label it as a wire timestamp. + delivery = {'sent_epoch_ms': time.time() * 1000, 'encode_ms': encoding_ms, + 'server_queue_ms': max(0, (encoding_started - self.published_perf_ns) / 1_000_000)} + encoded = encoded[:-1] + ', "_delivery": ' + json.dumps(delivery) + '}' if encoded != '{}' else '{"_delivery": ' + json.dumps(delivery) + '}' + else: + encoded = json.dumps(self.data, default=str) + lines.append(f"data: {encoded}") lines.append("") # trailing newline return "\n".join(lines) + "\n" diff --git a/backend/app/streaming/manager.py b/backend/app/streaming/manager.py index d287c5f..3b38b37 100644 --- a/backend/app/streaming/manager.py +++ b/backend/app/streaming/manager.py @@ -4,9 +4,12 @@ import asyncio import logging +import time +import hashlib from typing import Any from app.streaming.events import AGENT_ERROR, DESYNC, DONE, SSEEvent +from app.streaming.trace import traced, current_trace, safe_value, MAX_SPANS # Events that MUST be delivered to the frontend even when the queue overflows. # Losing these causes the UI to get permanently stuck in "generating" state. @@ -52,6 +55,35 @@ def __init__(self, stream_id: str, session_id: str): # Artifact content cache: identifier → {content, type, title, language} # Populated from message history at generation start, updated by artifact tool self.artifact_cache: dict[str, dict[str, Any]] = {} + from app.streaming.trace import TraceRecorder + parent_context = current_trace() + def relay_trace(data): + self.publish(SSEEvent('trace-span', data)) + if not parent_context or parent_context[0].completed: + return + parent, owner = parent_context + raw = data['span'] + def linked_id(key): + return 'child-' + hashlib.sha256(f'{stream_id}:{key}'.encode()).hexdigest()[:24] + key = linked_id(raw['id']) + if len(parent.spans) >= MAX_SPANS and key not in parent.spans: + parent.dropped += 1 + return + attrs = {**raw['attributes'], 'source_trace_id': stream_id, + 'source_session_id': session_id, 'subagent_depth': self._depth} + for field in ('producer_span_id', 'retry_of', 'parallel_group_id', 'join_span_id'): + if isinstance(attrs.get(field), str): + attrs[field] = linked_id(attrs[field]) + if isinstance(attrs.get('group_members'), list): + attrs['group_members'] = [linked_id(value) for value in attrs['group_members']] + mapped = {**raw, 'id': key, 'parentId': linked_id(raw['parentId']) if raw.get('parentId') else owner, + 'startMs': (self.trace.origin_ns-parent.origin_ns)/1_000_000+raw['startMs'], + 'kind': 'phase' if raw['kind']=='request' else raw['kind'], + 'name': '子智能体请求' if raw['kind']=='request' else raw['name'], + 'attributes': safe_value(attrs)} + parent.spans[key] = mapped + parent._emit(mapped) + self.trace = TraceRecorder(stream_id, relay_trace) @property def completed(self) -> bool: @@ -61,6 +93,11 @@ def publish(self, event: SSEEvent) -> None: """Publish an event to all subscribers and buffer for replay.""" self._event_counter += 1 event.id = self._event_counter + event.published_perf_ns = time.perf_counter_ns() + trace = getattr(self, 'trace', None) + if trace is not None: + event.data = {**event.data, '_trace': {'trace_id': self.stream_id, + 'origin_epoch_ms': trace.origin_epoch_ms, 'published_ms': trace.now()}} self.events.append(event) # Cap replay buffer to prevent unbounded memory growth @@ -156,7 +193,11 @@ def complete(self) -> None: def abort(self) -> None: """Signal abort to the generation loop.""" self.abort_event.set() + if not self.trace.completed: + self.trace.spans[self.trace.root_id]['attributes']['cancel_boundary'] = 'server accepted abort; provider/tool cleanup may finish later' + self.trace.close('cancelled') + @traced('等待用户确认', '用户交互') async def wait_for_response(self, call_id: str, timeout: float = 300.0) -> Any: """Wait for user response to a specific call_id. @@ -236,7 +277,7 @@ def active_jobs(self) -> list[dict[str, Any]]: "needs_input": bool(j._response_futures), } for j in self._jobs.values() - if not j.completed + if not j.completed and not j.abort_event.is_set() ] def abort_session(self, session_id: str) -> int: diff --git a/backend/app/streaming/trace.py b/backend/app/streaming/trace.py new file mode 100644 index 0000000..8157807 --- /dev/null +++ b/backend/app/streaming/trace.py @@ -0,0 +1,181 @@ +"""Bounded, monotonic execution traces. Observation never contains model reasoning. + +Spans are streamed as upserts (stable IDs), then saved on the answer message. +ContextVars isolate concurrent runs and propagate through asyncio/to_thread. +""" +from __future__ import annotations + +import contextvars +import functools +import time +import math +import re +from copy import deepcopy +from contextlib import contextmanager +from typing import Any, Callable, Iterator +from uuid import uuid4 + +_context: contextvars.ContextVar[tuple['TraceRecorder', str] | None] = contextvars.ContextVar('execution_trace', default=None) +MAX_SPANS = 2000 +_SECRET_KEYS = ('authorization', 'password', 'secret', 'api_key', 'access_token', 'refresh_token', 'cookie') + + +def safe_value(value: Any, depth: int = 0) -> Any: + if depth > 5: + return '[depth limit]' + if isinstance(value, dict): + return {str(k): '[redacted]' if any(s in str(k).lower() for s in _SECRET_KEYS) else safe_value(v, depth + 1) + for k, v in list(value.items())[:60]} + if isinstance(value, (list, tuple)): + return [safe_value(v, depth + 1) for v in value[:30]] + if isinstance(value, str): + value = re.sub(r'(?i)\bBearer\s+[A-Za-z0-9._~+/=-]+', 'Bearer [redacted]', value) + value = re.sub(r'\bsk-[A-Za-z0-9_-]{8,}', '[redacted]', value) + return value[:8000] + ('… [truncated]' if len(value) > 8000 else '') + if isinstance(value, float) and not math.isfinite(value): + return None + if isinstance(value, (bool, int, float)) or value is None: + return value + return str(value)[:500] + + +class TraceRecorder: + def __init__(self, trace_id: str, publish: Callable[[dict], None]) -> None: + self.trace_id = trace_id + self.origin_ns = time.perf_counter_ns() + self.origin_epoch_ms = time.time() * 1000 + self.publish = publish + self.spans: dict[str, dict] = {} + self.message_ids: list[str] = [] + self.completed = False + self.dropped = 0 + self.root_id = self.start('Agent 请求', '请求', kind='request', parent_id=None, span_id='request', emit=False) + + def now(self) -> float: + return (time.perf_counter_ns() - self.origin_ns) / 1_000_000 + + def _emit(self, span: dict) -> None: + if self.completed: + return + self.publish({'trace_id': self.trace_id, 'origin_epoch_ms': self.origin_epoch_ms, + 'span': deepcopy(span), 'elapsed_ms': self.now()}) + + def start(self, name: str, service: str, *, kind: str = 'phase', parent_id: str | None = None, + span_id: str | None = None, attributes: dict | None = None, emit: bool = True, + start_ms: float | None = None) -> str: + if self.completed: + return '' + if len(self.spans) >= MAX_SPANS: + self.dropped += 1 + return '' + key = span_id or uuid4().hex[:16] + self.spans[key] = {'id': key, 'parentId': parent_id, 'name': name, 'service': service, + 'kind': kind, 'startMs': self.now() if start_ms is None else max(0,start_ms), 'durationMs': 0, + 'status': 'running', 'attributes': safe_value(attributes or {})} + if emit: + self._emit(self.spans[key]) + return key + + def finish(self, key: str, status: str = 'ok', *, end_ms: float | None = None, **attributes: Any) -> None: + if self.completed: + return + s = self.spans.get(key) + if not s or s['status'] != 'running': + return + s.update(durationMs=max(0, (self.now() if end_ms is None else end_ms) - s['startMs']), status=status) + s['attributes'] = {**s['attributes'], **safe_value(attributes)} + self._emit(s) + + @contextmanager + def bind(self, parent_id: str | None = None) -> Iterator[None]: + token = _context.set((self, parent_id or self.root_id)) + try: + yield + finally: + _context.reset(token) + + def snapshot(self) -> dict: + return {'version': 1, 'trace_id': self.trace_id, 'origin_epoch_ms': self.origin_epoch_ms, + 'duration_ms': self.spans[self.root_id]['durationMs'] if self.completed else self.now(), + 'completed': self.completed, 'dropped_spans': self.dropped, + 'spans': list(self.spans.values())} + + def close(self, status: str = 'ok') -> None: + if self.completed: + return + ended = self.now() + for key in reversed(list(self.spans)): + if key != self.root_id and self.spans[key]['status'] == 'running': + self.finish(key, 'cancelled' if status != 'ok' else 'incomplete', end_ms=ended) + self.finish(self.root_id, status, end_ms=ended) + self.completed = True + + async def persist(self, session_factory) -> None: + if not self.message_ids: + return + from app.models.message import Message + async with session_factory() as db: + async with db.begin(): + # The last surviving answer owns the snapshot; all steps carry trace_id. + for message_id in reversed(self.message_ids): + row = await db.get(Message, message_id) + if row is not None: + row.data = {**row.data, 'trace_id': self.trace_id, 'execution_trace': self.snapshot()} + break + + +def current_trace() -> tuple[TraceRecorder, str] | None: + active = _context.get() + return active if active and not active[0].completed else None + + +@contextmanager +def trace_span(name: str, service: str, *, kind: str = 'phase', attributes: dict | None = None) -> Iterator[tuple[TraceRecorder, str] | None]: + active = current_trace() + if active is None: + yield None + return + trace, parent = active + key = trace.start(name, service, kind=kind, parent_id=parent, attributes=attributes) + try: + with trace.bind(key or parent): + yield (trace, key) + except BaseException as exc: + trace.finish(key, 'cancelled' if isinstance(exc, (KeyboardInterrupt, GeneratorExit)) or type(exc).__name__ == 'CancelledError' else 'error', error_type=type(exc).__name__) + raise + else: + trace.finish(key) + + +def traced(name: str, service: str, kind: str = 'phase'): + def decorate(fn): + @functools.wraps(fn) + async def wrapped(*args, **kwargs): + with trace_span(name, service, kind=kind): + return await fn(*args, **kwargs) + return wrapped + return decorate + + +class ProviderTiming: + """Provider boundary, including actual tool/reasoning deltas, not buffered calls.""" + def __init__(self) -> None: + self.active = current_trace() + self.wait_id = '' + self.decode_id = '' + if self.active: + trace, parent = self.active + self.wait_id = trace.start('请求发出 → 首 token', '模型', parent_id=parent, + attributes={'boundary': 'SDK 请求发起 → 首个有效内容 / 推理 / 工具 delta', 'clock': 'server monotonic'}) + + def first_token(self) -> None: + if self.active and not self.decode_id: + trace, parent = self.active + trace.finish(self.wait_id) + self.decode_id = trace.start('后续流式生成', '模型', parent_id=parent) + + def finish(self, status: str = 'ok') -> None: + if self.active: + trace, _ = self.active + trace.finish(self.wait_id, status if status != 'ok' else 'incomplete', note='未收到有效 delta') + trace.finish(self.decode_id, status) diff --git a/backend/app/streaming/trace_api.py b/backend/app/streaming/trace_api.py new file mode 100644 index 0000000..48d6c0c --- /dev/null +++ b/backend/app/streaming/trace_api.py @@ -0,0 +1,110 @@ +"""Execution trace APIs, separate from the generation control protocol.""" +from __future__ import annotations + +import time +from fastapi import APIRouter, HTTPException, Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from fastapi.routing import APIRoute +from pydantic import BaseModel, Field, FiniteFloat +from sqlalchemy import select +from app.dependencies import SessionFactoryDep, StreamManagerDep +from app.models.message import Message + + +class TraceRoute(APIRoute): + def get_route_handler(self): + original = super().get_route_handler() + async def handle(request: Request): + try: + return await original(request) + except RequestValidationError as exc: + # NaN is rejected by FiniteFloat, but echoing NaN (or private + # input) in FastAPI's default error body makes JSONResponse fail. + errors = [{key: item[key] for key in ('type', 'loc', 'msg') if key in item} + for item in exc.errors()] + return JSONResponse(status_code=422, content={'detail': errors}) + return handle + + +router = APIRouter(route_class=TraceRoute) + + +@router.get('/chat/clock') +async def trace_clock() -> dict: + """Client uses the minimum RTT sample; RTT/2 is an error bound, not a SLA.""" + return {'server_epoch_ms': time.time() * 1000} + + +class ClientTraceSpan(BaseModel): + id: str = Field(min_length=1, max_length=100, pattern=r'^client-') + name: str = Field(max_length=100) + service: str = Field(pattern=r'^(前端|SSE)$') + kind: str = Field(pattern=r'^(frontend|sse)$') + startMs: FiniteFloat = Field(ge=-60_000, le=86_400_000) + durationMs: FiniteFloat = Field(ge=0, le=86_400_000) + status: str = Field(pattern=r'^(ok|error|incomplete)$') + attributes: dict[str, str | FiniteFloat | bool | None] = Field(default_factory=dict, max_length=20) + + +class ClientDelivery(BaseModel): + event_seq: int = Field(ge=0) + event_type: str = Field(max_length=80) + received_epoch_ms: FiniteFloat + server_queue_ms: FiniteFloat | None = None + parse_ms: FiniteFloat = Field(ge=0) + handler_ms: FiniteFloat = Field(ge=0) + encode_ms: FiniteFloat | None = None + transfer_estimate_ms: FiniteFloat | None = None + clock_uncertainty_ms: FiniteFloat | None = None + clock: str = Field(max_length=180) + + +class ClientTraceReport(BaseModel): + session_id: str = Field(max_length=100) + spans: list[ClientTraceSpan] = Field(max_length=200) + metrics: dict[str, FiniteFloat] = Field(default_factory=dict, max_length=20) + deliveries: dict[str, ClientDelivery] = Field(default_factory=dict, max_length=2000) + + +async def _trace_message(db, trace_id: str, session_id: str): + return (await db.execute(select(Message).where( + Message.session_id == session_id, + Message.data['trace_id'].as_string() == trace_id, + ).order_by(Message.time_created.desc(), Message.id.desc()))).scalars().first() + + +@router.get('/chat/trace/{trace_id}') +async def get_execution_trace(trace_id: str, session_id: str, sm: StreamManagerDep, session_factory: SessionFactoryDep) -> dict: + job = sm.get_job(trace_id) + if job is not None and job.session_id == session_id: + snap = job.trace.snapshot() + if hasattr(job, '_client_trace'): + snap['client'] = job._client_trace + return snap + async with session_factory() as db: + row = await _trace_message(db, trace_id, session_id) + if row and row.data.get('execution_trace'): + return row.data['execution_trace'] + raise HTTPException(status_code=404, detail='Trace not collected or session does not match') + + +@router.post('/chat/trace/{trace_id}/client') +async def save_client_trace(trace_id: str, body: ClientTraceReport, sm: StreamManagerDep, session_factory: SessionFactoryDep) -> dict: + from app.streaming.trace import safe_value + # Frontend observations are kept separate; they cannot overwrite server spans. + report = safe_value({'spans': [s.model_dump() for s in body.spans], 'metrics': body.metrics}) + # safe_value limits ordinary lists to 30: this dedicated bounded list keeps all 200. + report['spans'] = [safe_value(s.model_dump()) for s in body.spans] + report['deliveries'] = {key[:120]: value.model_dump(exclude_none=True) for key,value in body.deliveries.items()} + async with session_factory() as db: + async with db.begin(): + row = await _trace_message(db, trace_id, body.session_id) + if row is None or not row.data.get('execution_trace'): + raise HTTPException(status_code=409, detail='Server trace is not persisted yet') + snapshot = {**row.data['execution_trace'], 'client': report} + row.data = {**row.data, 'execution_trace': snapshot} + job = sm.get_job(trace_id) + if job is not None and job.session_id == body.session_id: + job._client_trace = report + return {'saved': True, 'spans': len(report['spans'])} diff --git a/backend/app/tool/builtin/code_execute.py b/backend/app/tool/builtin/code_execute.py index 24a6804..0e2bf78 100644 --- a/backend/app/tool/builtin/code_execute.py +++ b/backend/app/tool/builtin/code_execute.py @@ -92,13 +92,16 @@ async def execute(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult: return ToolResult(error="No code provided") timeout = min(args.get("timeout", DEFAULT_TIMEOUT), MAX_TIMEOUT) - before_snapshot = _snapshot_workspace(ctx.workspace) + from app.streaming.trace import trace_span + with trace_span('执行前 · 工作区产物快照', 'Python'): + before_snapshot = _snapshot_workspace(ctx.workspace) try: - output, exit_code = await asyncio.wait_for( - asyncio.to_thread(_run_code, code), - timeout=timeout, - ) + with trace_span('Python 脚本执行', 'Python'): + output, exit_code = await asyncio.wait_for( + asyncio.to_thread(_run_code, code), + timeout=timeout, + ) except asyncio.TimeoutError: return ToolResult( error=f"Execution timed out after {timeout}s", @@ -108,7 +111,8 @@ async def execute(self, args: dict[str, Any], ctx: ToolContext) -> ToolResult: return ToolResult(error=f"Execution failed: {exc}") title = f"python: {code[:60]}..." if len(code) > 60 else f"python: {code}" - after_snapshot = _snapshot_workspace(ctx.workspace) + with trace_span('执行后 · 工作区产物快照', 'Python'): + after_snapshot = _snapshot_workspace(ctx.workspace) written_files = sorted( path for path, sig in after_snapshot.items() diff --git a/frontend/public/vendor/1.0.59/request-waterfall.js b/frontend/public/vendor/1.0.59/request-waterfall.js new file mode 100644 index 0000000..f183042 --- /dev/null +++ b/frontend/public/vendor/1.0.59/request-waterfall.js @@ -0,0 +1,44 @@ +var Je=Symbol.for("openai.visualize.readiness.v1");function he(i,d){let l=globalThis[Je];if(!l){let c=new Set;l={pendingElements:c,mounted:!1,reported:!1},l.report=()=>{l.reported||!l.mounted||c.size||document.readyState!=="complete"||(l.reported=!0,globalThis.openai?.callTool?.("__codex_inline_visualization_ready__",{}))},globalThis[Je]=l,globalThis.addEventListener("load",l.report,{once:!0})}l.reported||(l.mounted=!0,d?l.pendingElements.add(i):l.pendingElements.delete(i),queueMicrotask(l.report))}var Ne='style, link[rel~="stylesheet" i]',tt=["rel","href","media","type","title","nonce","integrity","crossorigin","referrerpolicy","disabled","fetchpriority"],He=new WeakMap;function nt(i){let d=i.host.ownerDocument,l=d.defaultView;if(!l)throw new Error("Host styles require a browser document.");let c=He.get(d);if(!c){let o=new Set,E=new l.MutationObserver(m=>{if(!m.some(T=>St(T,l)))return;let I=Qe(d,l);for(let T of o)et(T,I,l)});c={subscriptions:o,observer:E},He.set(d,c),E.observe(d,{subtree:!0,childList:!0,attributes:!0,attributeFilter:tt,characterData:!0})}let x=d.createComment("Host styles");i.prepend(x);let u={shadow:i,anchor:x,mirrors:new Map};c.subscriptions.add(u),et(u,Qe(d,l),l);let g=Promise.all([...u.mirrors.values()].map(o=>o.ready)).then(()=>{}),y=c,h=!1;return{ready:g,dispose(){if(!h){h=!0,y.subscriptions.delete(u);for(let o of u.mirrors.values())o.settle(),o.element.remove();u.mirrors.clear(),x.remove(),y.subscriptions.size||(y.observer.disconnect(),He.delete(d))}}}}function Qe(i,d){return[...i.querySelectorAll(Ne)].filter(l=>l instanceof d.HTMLStyleElement||l instanceof d.HTMLLinkElement)}function St(i,d){let l=i.target;return l instanceof d.HTMLStyleElement||l instanceof d.HTMLLinkElement||l.parentNode instanceof d.HTMLStyleElement?!0:i.type!=="childList"?!1:[...i.addedNodes,...i.removedNodes].some(c=>c instanceof d.Element&&(c.matches(Ne)||c.querySelector(Ne)!==null))}function et(i,d,l){let c=new Set(d);for(let[u,g]of i.mirrors)c.has(u)||(g.settle(),g.element.remove(),i.mirrors.delete(u));let x=i.shadow.firstChild;for(let u of d){let g=i.mirrors.get(u);g||(g=kt(u,l),i.mirrors.set(u,g)),Et(u,g.element,l),x!==g.element&&i.shadow.insertBefore(g.element,x),g.element.disabled=u.disabled,u instanceof l.HTMLLinkElement&&(u.disabled||!u.getAttribute("href"))&&g.settle(),x=g.element.nextSibling}}function kt(i,d){let l=i.ownerDocument;if(i instanceof d.HTMLStyleElement)return{element:l.createElement("style"),ready:Promise.resolve(),settle(){}};let c=l.createElement("link"),x=()=>{},u=new Promise(g=>{x=()=>{c.removeEventListener("load",x),c.removeEventListener("error",x),g()},c.addEventListener("load",x),c.addEventListener("error",x)});return{element:c,ready:u,settle:()=>x()}}function Et(i,d,l){for(let c of tt){if(!i.hasAttribute(c)){d.removeAttribute(c);continue}let x=c==="nonce"?i.nonce??"":c==="href"&&i instanceof l.HTMLLinkElement?i.href:i.getAttribute(c)??"";(c==="nonce"?d.nonce:d.getAttribute(c))!==x&&d.setAttribute(c,x)}i instanceof l.HTMLStyleElement&&d.textContent!==i.textContent&&(d.textContent=i.textContent)}function Se(i,d){if(!i||typeof i!="object"||Array.isArray(i))throw new TypeError(`${d} must be an object.`)}function ne(i,d,l=!1){if(!(i===void 0&&l)){if(typeof i!="string"||i.length>2e4)throw new TypeError(`${d} must be a string of at most 20000 characters.`);return i}}function ke(i,d){let l=ne(i,d);if(!l.trim()||l.length>200)throw new TypeError(`${d} must be a nonempty identifier of at most 200 characters.`);return l}function Re(i,d,l=0,c=!1){if(typeof i!="number"||!Number.isFinite(i)||i= ${l}.`);return i}function rt(i,d,l=2e4){if(!Array.isArray(i)||i.length>l)throw new TypeError(`${d} must be an array of at most ${l} items.`);return i}function Tt(i,d){let l=new Set;for(let c of i){if(l.has(c.id))throw new TypeError(`${d} contains duplicate id ${c.id}.`);l.add(c.id)}return l}function Ct(i,d){return Se(i,"Viewer config"),{id:i.id===void 0?d:ke(i.id,"Viewer id"),title:ne(i.title,"Title",!0),description:ne(i.description,"Description",!0)}}function at(i,d=""){Se(i,"Viewer config");let l=Ct(i,d),{spans:c=[]}=i,x=rt(c,"Spans").map((m,I)=>{let T=`Span ${I}`;Se(m,T);let $={id:ke(m.id,`${T} id`),parentId:m.parentId==null?null:ke(m.parentId,`${T} parentId`),name:ne(m.name,`${T} name`),service:ne(m.service,`${T} service`,!0),startMs:Re(m.startMs,`${T} startMs`),durationMs:Re(m.durationMs,`${T} durationMs`)};if(m.status!==void 0&&m.status!=="ok"&&m.status!=="warning"&&m.status!=="error")throw new TypeError(`${T} has an unsupported status.`);if($.status=m.status,m.attributes!==void 0){if(Se(m.attributes,`${T} attributes`),Object.keys(m.attributes).length>100)throw new TypeError(`${T} has too many attributes.`);$.attributes=Object.fromEntries(Object.entries(m.attributes).map(([D,H])=>{if(ne(D,"Attribute name"),typeof H=="string")ne(H,"Attribute value");else if(typeof H!="boolean"&&(typeof H!="number"||!Number.isFinite(H)))throw new TypeError("Attribute values must be strings, finite numbers, or booleans.");if(typeof H!="string"&&typeof H!="boolean"&&typeof H!="number")throw new TypeError("Invalid attribute value.");return[D,H]}))}if(!Number.isFinite($.startMs+$.durationMs))throw new TypeError(`${T} end time overflows.`);return $}),u=Tt(x,"Spans"),g=new Map(x.map(m=>[m.id,m])),y=new Map;for(let m of x){let I=[],T=new Set,$=m;for(;$&&!y.has($.id);){if(T.has($.id))throw new TypeError("Span parents must not contain a cycle.");if(I.length>=128)throw new TypeError("Span nesting exceeds 128 levels.");if(T.add($.id),I.push($.id),$.parentId!==null&&!u.has($.parentId))throw new TypeError(`Missing parent ${$.parentId}.`);$=$.parentId===null?void 0:g.get($.parentId)}let D=$?y.get($.id)??0:0;for(let H of I.reverse()){if(D++,D>128)throw new TypeError("Span nesting exceeds 128 levels.");y.set(H,D)}}let h=x.reduce((m,I)=>Math.max(m,I.startMs+I.durationMs),0),o=i.durationMs===void 0?Math.max(1,h):Re(i.durationMs,"Trace durationMs",Number.MIN_VALUE);if(o{let I=ke(m,"Critical path span id");if(i.spans!==void 0&&!u.has(I))throw new TypeError(`Critical path refers to missing span ${I}.`);return I});return{...l,durationMs:o,spans:x,criticalPath:i.spans===void 0?void 0:E}}var $t={up:'',down:'',left:'',right:'',plus:'',minus:'',fit:'',close:'',check:'',warning:'',fields:'',clock:'',sort:'',expand:'',route:''};function We(i){return`
+ + ${V("up","Previous match",'data-action="previous"')} + ${V("down","Next match",'data-action="next"')} + +
`}function Fe(i){return`
+ ${V("left","Pan earlier",'data-action="pan-left"')} + ${V("minus","Zoom out",'data-action="zoom-out"')} + ${V("plus","Zoom in",'data-action="zoom-in"')} + ${V("right","Pan later",'data-action="pan-right"')} + ${V("fit",i,'data-action="fit"')} +
`}function V(i,d,l){return``}function F(i){return``}var it=`.trace-toolbar{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;padding:8px 0}.trace-navigation{display:flex;align-items:center;gap:2px;margin-inline-start:auto}.trace-search-group{display:flex;align-items:center;gap:4px;min-width:0;flex:1 1 min-content}.trace-icon{width:16px;height:16px;flex:0 0 16px;display:inline-block;vertical-align:middle}.btn.trace-icon-button{inline-size:var(--btn-size);padding-inline:0;flex-shrink:0}.trace-toolbar .trace-search{flex-grow:1;width:100px;max-width:160px;height:28px;padding:4px 8px;border:.5px solid var(--input, var(--border));border-radius:var(--radius-md, 8px);corner-shape:var(--corner-shape);background:var( --secondary, color-mix(in srgb, var(--foreground) 6%, var(--background)) );color:var(--foreground);font-size:calc(var(--font-size-base, 16px) * 12 / 16)}.trace-toolbar .trace-search::placeholder{color:var(--muted-foreground)}.trace-matches{font-size:calc(var(--font-size-base, 16px) * 11 / 16);color:var(--muted-foreground);white-space:nowrap}.trace-toolbar .trace-search:focus-visible{outline:2px solid var(--ring, var(--primary));outline-offset:-2px}@container (max-width: 720px){.trace-toolbar .trace-search{max-width:none}}@media(pointer:coarse){.trace-toolbar .trace-search{min-height:44px;font-size:max(16px,calc(var(--font-size-base, 16px) * 12 / 16))}.btn.trace-icon-button{inline-size:44px}}.trace-range-window{border:0;box-shadow:inset 0 0 0 1px var(--trace-range-border, var(--border-strong, var(--border)));border-radius:var(--radius-lg, 10px);corner-shape:var(--corner-shape);cursor:var(--cursor-interaction, pointer);pointer-events:none}.trace-range-window[data-zoomed=true]{pointer-events:auto}.trace-range-window .trace-range-handle{position:absolute;top:0;display:flex;align-items:center;justify-content:center;width:14px;height:100%;padding:0;border:0;background:transparent;cursor:ew-resize;pointer-events:auto;touch-action:none}.trace-range-handle[data-edge=start]{left:0}.trace-range-handle[data-edge=end]{right:0}.trace-range-handle span{position:absolute;width:3px;height:15px;border-radius:2px;background:linear-gradient(color-mix(in srgb,var(--foreground) 80%,var(--muted-foreground) 20%),color-mix(in srgb,var(--foreground) 80%,var(--muted-foreground) 20%)),var(--background);pointer-events:none}.trace-range-handle[data-edge=start] span{left:.5px;transform:translate(-50%)}.trace-range-handle[data-edge=end] span{right:.5px;transform:translate(50%)}.trace-range-shade{background:color-mix(in srgb,var(--background) 72%,transparent);pointer-events:none}.wf-view{--wf-row-height: 28px;--wf-step: 17px;--wf-name-width: 33%;--wf-value-width: 80px;container-type:inline-size;min-width:0;padding:0;color:var(--foreground);font:calc(var(--font-size-base, 16px) * 14 / 16) / 1.4 var(--font-sans, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif);overflow-anchor:none}.wf-view *{box-sizing:border-box}.wf-view [hidden]{display:none!important}.wf-view button:where(:not(.btn)),.wf-view input{font:inherit;color:inherit}.wf-view button:where(:not(.btn)){cursor:var(--cursor-interaction, pointer)}.wf-view button:where(:not(.btn)):focus-visible,.wf-view input:focus-visible{outline:2px solid var(--ring, var(--primary));outline-offset:-2px}.wf-view button:where(:not(.btn)):disabled{opacity:.35;cursor:default}.wf-view .wf-heading{display:flex;align-items:baseline;flex-wrap:wrap;gap:4px 14px;min-height:30px}.wf-view .wf-title{margin:0;font:inherit;font-weight:500;overflow-wrap:anywhere}.wf-view .wf-meta,.wf-view .wf-description{color:var(--muted-foreground);font-size:calc(var(--font-size-base, 16px) * 12 / 16)}.wf-view .wf-description{margin:0 0 8px;overflow-wrap:anywhere}.wf-view .wf-meta,.wf-view .wf-range-label,.wf-view .wf-value,.wf-view .wf-axis{font-variant-numeric:tabular-nums}.wf-view .wf-minimap{position:relative;height:56px;margin:6px 0;touch-action:none;user-select:none;cursor:var(--cursor-interaction, pointer)}.wf-view .wf-mini{position:absolute;height:10px;min-width:1px;border:0;border-radius:3px;background:color-mix(in srgb,var(--wf-series) 88%,transparent);pointer-events:none}.wf-view .wf-mini[data-selected=true]{background:var(--wf-series)}.wf-view .wf-mini[data-muted=true]{opacity:.5}.wf-view .wf-shade{background:color-mix(in srgb,var(--background) 65%,transparent);position:absolute;top:-3px;bottom:-3px;z-index:1}.wf-view .wf-shade-left{left:0}.wf-view .wf-shade-right{right:0}.wf-view .wf-window{--trace-range-border: color-mix(in srgb, var(--foreground) 24%, transparent);border-radius:4px;corner-shape:round;position:absolute;top:-3px;bottom:-3px;z-index:2}.wf-view .wf-summary-bottom{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:6px 12px;padding:3px 0 8px;color:var(--muted-foreground);font-size:calc(var(--font-size-base, 16px) * 11 / 16)}.wf-view .wf-legend{display:flex;flex-wrap:wrap;gap:6px 12px}.wf-view .wf-legend-item{display:inline-flex;align-items:center;gap:5px}.wf-view .wf-swatch{width:8px;height:8px;border-radius:2px;background:var(--wf-series)}.wf-view .wf-range-label{white-space:nowrap}.wf-view .wf-toolbar{border-top:1px solid var(--border)}.wf-view .wf-actions{display:flex;align-items:center;gap:4px;min-width:0;flex-wrap:wrap}.wf-view .wf-actions [data-action=warnings]{color:var(--orange, var(--destructive))}.wf-view .wf-actions .trace-icon-button:is([aria-pressed=true],[aria-expanded=true]){color:var(--foreground);background:color-mix(in srgb,var(--foreground) 10%,transparent)}.wf-view .trace-navigation{margin-inline-start:2px;padding-inline-start:6px;border-inline-start:1px solid var(--border)}.wf-view .wf-menu-wrap{position:relative}.wf-view .wf-menu{position:absolute;top:calc(100% + 5px);right:0;z-index:10;min-width:180px;padding:4px;border:0;border-radius:var(--radius-2xl, 20px);corner-shape:var(--corner-shape, superellipse(1.5));background:var(--popover);color:var(--popover-foreground);box-shadow:0 0 0 .5px var(--border),0 8px 16px -4px #0000001f}.wf-view .wf-menu-item{display:flex;align-items:center;justify-content:space-between;gap:16px;width:100%;min-height:28px;padding:5px 8px;border:0;border-radius:calc(var(--radius-2xl, 20px) * .75);corner-shape:var(--corner-shape, superellipse(1.5));background:transparent;color:var(--popover-foreground);font-size:round(nearest,calc(var(--font-size-base, 16px) * 13 / 16),1px);font-weight:400;line-height:1.4285714286;text-align:left;box-shadow:none}.wf-view .wf-menu-item:is(:hover,:focus){background:color-mix(in srgb,var(--foreground) 5.5%,transparent);outline:none}.wf-view .wf-menu-item[aria-checked=false] .trace-icon{visibility:hidden}.wf-view .wf-table-wrap{min-height:calc(var(--wf-row-height) * var(--wf-count, 0) + 42px);overflow-anchor:none}.wf-view .wf-frame{position:relative;isolation:isolate;border:.5px solid var(--border-strong, var(--border));border-radius:var(--radius-lg, 12px);corner-shape:var(--corner-shape);overflow:hidden}.wf-view .wf-table{width:100%;border-collapse:separate;border-spacing:0;table-layout:fixed;margin:0;font:inherit}.wf-view .wf-name-col{width:var(--wf-name-width)}.wf-view .wf-service-col{width:14%}.wf-view .wf-alternate-col{width:80px}.wf-view .wf-value-col{width:var(--wf-value-width)}.wf-view th{height:32px;padding:0 8px;border:0;border-bottom:1px solid var(--border-strong, var(--border));text-align:left;font-weight:500;white-space:nowrap}.wf-view .wf-name-heading{display:flex;justify-content:space-between;align-items:center;padding-left:24px}.wf-view .wf-axis-cell{padding:0}.wf-view .wf-axis{position:relative;height:20px;font-size:calc(var(--font-size-base, 16px) * 12 / 16);font-weight:400}.wf-view .wf-tick{position:absolute;top:0;transform:translate(-50%);white-space:nowrap}.wf-view .wf-tick:first-child{transform:none;margin-left:6px}.wf-view .wf-tick:last-child{transform:translate(-100%);margin-left:-6px}.wf-view .wf-sort{width:100%;height:32px;display:flex;justify-content:flex-end;align-items:center;gap:4px;padding:0;border:0;background:transparent;font-size:calc(var(--font-size-base, 16px) * 12 / 16)}.wf-view .wf-sort .trace-icon{width:13px;height:13px;flex:0 0 13px}.wf-view td{padding:0;border:0;vertical-align:middle}.wf-view .wf-row{height:var(--wf-row-height)}.wf-view .wf-row[data-stripe=true]{background:color-mix(in srgb,var(--foreground) 3.2%,transparent)}.wf-view .wf-row:hover{background:color-mix(in srgb,var(--foreground) 6%,transparent)}.wf-view .wf-row[data-selected=true]{background:var(--accent);color:var(--accent-foreground, var(--foreground))}.wf-view .wf-row[data-warning=true]:not([data-selected=true]){background:color-mix(in srgb,var(--orange, var(--destructive)) 7%,transparent)}.wf-view .wf-row[data-warning=true] .wf-name-cell{box-shadow:inset 2px 0 var(--orange, var(--destructive))}.wf-view .wf-row[data-muted=true] :is(.wf-name-text,.wf-value,.wf-service-text){color:var(--muted-foreground)}.wf-view .wf-row[data-muted=true] .wf-bar{opacity:.48}.wf-view .wf-name-cell{position:relative;height:var(--wf-row-height)}.wf-view .wf-name{width:100%;height:var(--wf-row-height);display:flex;align-items:center;gap:4px;min-width:0;padding:0 6px 0 calc(37px + var(--depth) * var(--wf-step));border:0;background:transparent;text-align:left}.wf-view .wf-name-text{overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.wf-view .wf-child-count{color:var(--muted-foreground);font-size:calc(var(--font-size-base, 16px) * 11 / 16);font-variant-numeric:tabular-nums;flex:none;margin-left:2px}.wf-view .wf-disclosure{position:absolute;top:calc((var(--wf-row-height) - 20px) / 2);left:calc(13px + var(--depth) * var(--wf-step));z-index:1;display:grid;place-items:center;width:20px;height:20px;padding:0;border:0;border-radius:4px;background:transparent;color:var(--muted-foreground)}.wf-view .wf-disclosure:hover{background:color-mix(in srgb,var(--foreground) 7%,transparent)}.wf-view .wf-disclosure .trace-icon{width:13px;height:13px}.wf-view .wf-disclosure[aria-expanded=false] .trace-icon{transform:rotate(-90deg)}.wf-view .wf-tree-line{position:absolute;top:0;bottom:0;left:calc(23px + var(--level) * var(--wf-step));width:1px;background:var(--border);pointer-events:none}.wf-view .wf-tree-line[data-last=true]{bottom:50%}.wf-view .wf-tree-elbow{position:absolute;top:50%;left:calc(23px + (var(--depth) - 1) * var(--wf-step));width:var(--wf-step);height:1px;background:var(--border);pointer-events:none}.wf-view .wf-warning-icon{display:inline-flex;color:var(--orange, var(--destructive))}.wf-view .wf-service-text{display:block;padding:0 8px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:var(--muted-foreground);font-size:calc(var(--font-size-base, 16px) * 12 / 16)}.wf-view .wf-value{text-align:right;padding:0 8px;white-space:nowrap;font-size:calc(var(--font-size-base, 16px) * 12 / 16)}.wf-view .wf-track{position:relative;display:block;width:100%;height:var(--wf-row-height);padding:0;border:0;background:transparent;overflow:hidden;user-select:none;touch-action:none;cursor:var(--cursor-interaction, pointer);text-align:left}.wf-view .wf-grid{position:absolute;top:0;bottom:0;width:1px;background:color-mix(in srgb,var(--foreground) 6%,transparent);pointer-events:none}.wf-view .wf-bar{position:absolute;top:7px;height:calc(var(--wf-row-height) - 14px);border-radius:3px;background:color-mix(in srgb,var(--wf-series) 72%,transparent);pointer-events:none;min-width:2px}.wf-view[data-time=direct] .wf-bar-total{opacity:.18}.wf-view .wf-bar-label{position:absolute;top:50%;transform:translateY(-50%);padding-left:4px;color:var(--foreground);font-size:calc(var(--font-size-base, 16px) * 11 / 16);font-variant-numeric:tabular-nums;white-space:nowrap;pointer-events:none}.wf-view .wf-bar-label[data-inside=true]{transform:translate(-100%,-50%);padding:0 4px;background:color-mix(in srgb,var(--background) 55%,transparent)}.wf-view .wf-event{position:absolute;top:8px;width:1px;height:calc(var(--wf-row-height) - 16px);background:var(--orange, var(--destructive));pointer-events:none}.wf-view .wf-event:after{content:"";position:absolute;top:0;left:-2px;width:5px;height:5px;border-radius:50%;background:inherit}.wf-view .wf-resizer{position:absolute;top:0;bottom:0;width:8px;padding:0;border:0;background:transparent;z-index:3;cursor:col-resize;touch-action:none}.wf-view .wf-resizer:after{content:"";position:absolute;top:0;bottom:0;left:3.5px;width:1px;background:var(--border)}.wf-view .wf-resizer:hover:after,.wf-view .wf-resizer:focus-visible:after{background:var(--muted-foreground)}.wf-view .wf-resizer[data-column=name]{left:calc(var(--wf-name-width) - 4px)}.wf-view .wf-resizer[data-column=duration]{right:calc(var(--wf-value-width) - 4px)}.wf-view .wf-detail td{position:relative;z-index:4;padding:12px 14px;background:var(--background);border-top:1px solid var(--border);border-bottom:1px solid var(--border)}.wf-view .wf-detail-title{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;font-weight:500;overflow-wrap:anywhere}.wf-view .wf-detail-actions{display:flex;align-items:center;gap:4px;flex:none}.wf-view .wf-detail-data{display:flex;flex-wrap:wrap;gap:6px 20px;margin:9px 0 0;font-size:calc(var(--font-size-base, 16px) * 12 / 16);font-variant-numeric:tabular-nums}.wf-view .wf-detail-data>div{display:flex;gap:5px;min-width:0;overflow-wrap:anywhere}.wf-view .wf-detail-data dt{color:var(--muted-foreground)}.wf-view .wf-detail-data dd{margin:0}.wf-view .wf-empty{padding:14px;color:var(--muted-foreground)}.wf-view .wf-footer{display:flex;justify-content:space-between;flex-wrap:wrap;gap:6px 12px;padding-top:9px;color:var(--muted-foreground);font-size:calc(var(--font-size-base, 16px) * 11 / 16)}.wf-view[data-dragging=true] :is(.wf-track,.wf-window){cursor:grabbing}.wf-view[data-service=false] :is(.wf-service-col,.wf-service-cell),.wf-view[data-both-times=false] :is(.wf-alternate-col,.wf-alternate-cell){display:none}.wf-view[data-labels=false] .wf-bar-label{display:none}.wf-view[data-flat=true] :is(.wf-disclosure,.wf-tree-line,.wf-tree-elbow,.wf-child-count){display:none}.wf-view[data-flat=true] .wf-name{padding-left:12px}@container (max-width: 720px){.wf-view .trace-navigation{margin-inline-start:auto}.wf-view .wf-table-wrap{overflow-x:auto}.wf-view .wf-frame{min-width:610px}}@media(pointer:coarse){.wf-view{--wf-row-height: 44px}.wf-view .wf-menu-item{min-height:44px}.wf-view .wf-disclosure:before{content:"";position:absolute;inset:-12px -3px}} +`;function ot(i,d,{onStateChange:l}={}){let c=i.ownerDocument,x=c.defaultView;if(!x)throw new Error("Waterfall requires a document with a window.");let u=x,g=new u.AbortController,y=b("section","wf-view");y.setAttribute("aria-label","Trace waterfall");let h=b("style");h.textContent=it,y.innerHTML=` +

+ +
+
+
+
+
+
+
+
+ ${We("Search spans")} +
+ ${V("route","Critical path",'data-action="critical" aria-pressed="false"')} + ${V("warning","Warnings",'data-action="warnings" aria-pressed="false"')} +
+ ${V("clock","Total time",'data-menu="time" aria-haspopup="menu" aria-expanded="false"')} + +
+
+ ${V("fields","Fields",'data-menu="fields" aria-haspopup="menu" aria-expanded="false"')} + +
+
+ ${Fe("Fit trace")} +
+
+ + + +
Name
Service nameDirect time
+ `,i.replaceChildren(h,y);function o(e){let r=y.querySelector(e);if(!r)throw new Error(`Missing waterfall element: ${e}`);return r}let E=e=>[...y.querySelectorAll(e)],m=o("tbody"),I=o(".wf-frame"),T=o(".wf-axis"),$=o(".wf-minimap"),D=o(".trace-search"),H=o(".wf-window"),_=new Map,oe=new Map,ae=new Map,ge=b("tr","wf-detail"),be=b("td");ge.append(be);let pt=Array.from({length:5},(e,r)=>{let a=b("span","wf-tick");return a.style.left=`${r*25}%`,T.append(a),a}),v=d,X=new Map,O=new Map,G=new Map,ee=new Map,N=[],ye=new Set,t,U=null,S=null,le=!1,de,ie=!1,De=0,ve=null,Te="";Ve(),t=Ce(),_e(),Y();function b(e,r,a){let n=c.createElement(e);return r&&(n.className=r),a!==void 0&&(n.textContent=a),n}function Ve(){X=new Map(v.spans.map(a=>[a.id,a])),O=new Map(v.spans.map(a=>[a.id,[]])),G=new Map,ee=new Map,N=[];let e=[];for(let a of v.spans)a.parentId===null?e.push(a):k(O,a.parentId).push(a);let r=e.map(a=>({span:a,parents:[]})).reverse();for(;r.length;){let a=r.pop();if(!a)break;let{span:n,parents:s}=a;N.push(n),G.set(n.id,s);for(let f of[...k(O,n.id)].reverse())r.push({span:f,parents:[...s,n.id]})}for(let a of N){let n=a.service??"";ae.has(n)||ae.set(n,`var(--viz-series-${ae.size%6+1}, var(--primary))`)}for(let a of v.spans){let n=a.startMs+a.durationMs,s=[],f=a.startMs;for(let p of[...k(O,a.id)].sort((M,C)=>M.startMs-C.startMs)){let M=Math.max(a.startMs,p.startMs),C=Math.min(n,p.startMs+p.durationMs);C<=M||(M>f&&s.push([f,M]),f=Math.max(f,C))}fp+C-M,0)})}ye=v.criticalPath===void 0?It(e,O):new Set(v.criticalPath)}function Ce(){return{selectedSpanId:null,collapsed:[],query:"",warnings:!1,critical:!1,service:!1,labels:!1,bothTimes:!1,details:!1,nameWidth:null,durationWidth:80,startMs:0,endMs:v.durationMs,order:"trace",time:"total"}}function Oe(e){let r=Ce();if(!zt(e))return r;r.selectedSpanId=typeof e.selectedSpanId=="string"&&X.has(e.selectedSpanId)?e.selectedSpanId:null,r.collapsed=At(e.collapsed)?[...new Set(e.collapsed.filter(a=>typeof a=="string"&&!!O.get(a)?.length))]:[],r.query=typeof e.query=="string"?e.query:"";for(let a of["warnings","critical","service","labels","bothTimes","details"])r[a]=e[a]===!0;return ye.size||(r.critical=!1),r.nameWidth=Ee(e.nameWidth)?Math.max(160,e.nameWidth):null,r.durationWidth=Ee(e.durationWidth)?A(e.durationWidth,64,180):80,r.order=e.order==="longest"||e.order==="shortest"?e.order:"trace",r.time=e.time==="direct"?"direct":"total",Ee(e.startMs)&&Ee(e.endMs)&&e.endMs>e.startMs&&([r.startMs,r.endMs]=Ge(e.startMs,e.endMs)),r.selectedSpanId||(r.details=!1),r}function $e(){return{...t,collapsed:[...t.collapsed]}}function Z(){if(ie)return;let e=t.selectedSpanId?X.get(t.selectedSpanId):void 0;l?.({state:$e(),selection:e?{spanId:e.id,name:e.name,startMs:e.startMs,durationMs:e.durationMs,endMs:e.startMs+e.durationMs}:null})}function Be(e){return k(ae,e??"")}function _e(){_.clear(),oe.clear(),m.replaceChildren(),o(".wf-mini-bars").replaceChildren(),o(".wf-legend").replaceChildren(),Te="",ve=null,o(".wf-title").textContent=v.title||"Trace waterfall",o(".wf-meta").textContent=`${P(v.durationMs)} \xB7 ${v.spans.length} spans`,o(".wf-description").textContent=v.description??"",o(".wf-description").hidden=!v.description,y.style.setProperty("--wf-count",String(v.spans.length));let e=new Set(N.map(n=>n.service??""));for(let[n,s]of ae){if(!e.has(n))continue;let f=b("span","wf-legend-item"),p=b("span","wf-swatch");p.style.setProperty("--wf-series",s),f.append(p,c.createTextNode(n||"Spans")),o(".wf-legend").append(f)}for(let n of N){let s=k(G,n.id),f=Be(n.service),p=b("tr","wf-row");p.dataset.spanId=n.id,p.style.setProperty("--depth",String(s.length)),p.style.setProperty("--wf-series",f);let M=b("td","wf-name-cell");for(let R=0;Rb("span","wf-bar wf-bar-direct")),me=b("span","wf-bar-label"),we=b("span","wf-event");K.append(w,...z,me,we),pe.append(K);let Ze=b("td","wf-value");p.append(M,j,se,pe,Ze),m.append(p),_.set(n.id,{row:p,disclosure:C,name:L,alternate:se,track:K,bar:w,segments:z,label:me,event:we,value:Ze})}let r=[],a=[...N].sort((n,s)=>n.startMs-s.startMs||k(G,n.id).length-k(G,s.id).length);for(let n of a){let s=k(G,n.id).length;for(;(r[s]??-1/0)>n.startMs;)s++;r[s]=n.startMs+n.durationMs;let f=b("span","wf-mini");f.style.setProperty("--wf-series",Be(n.service)),f.style.top=`${s*13}px`,f.style.left=`${n.startMs/v.durationMs*100}%`,f.style.width=`max(1px, calc(${n.durationMs/v.durationMs*100}% - 1px))`,o(".wf-mini-bars").append(f),oe.set(n.id,f)}if($.style.height=`${Math.max(40,r.length*13-3)}px`,!N.length){let n=b("tr"),s=b("td","wf-empty","No spans in this trace.");s.colSpan=5,n.append(s),m.append(n)}}function xe(e){return t.time==="direct"?k(ee,e.id).duration:e.durationMs}function qe(){let e=t.query.trim().toLocaleLowerCase();return e?N.filter(r=>`${r.name} ${r.service??""} ${Object.entries(r.attributes??{}).map(([a,n])=>`${a} ${n}`).join(" ")}`.toLocaleLowerCase().includes(e)):[]}function mt(){if(t.order==="trace")return N;let e=t.order==="longest"?-1:1;return[...N].sort((r,a)=>e*(xe(r)-xe(a))||r.startMs-a.startMs)}function je(e){return t.order!=="trace"||t.query.trim()||!k(G,e.id).some(r=>t.collapsed.includes(r))}function Y(){y.dataset.time=t.time,y.dataset.service=String(t.service),y.dataset.labels=String(t.labels),y.dataset.bothTimes=String(t.bothTimes),y.dataset.flat=String(t.order!=="trace"),D.value!==t.query&&(D.value=t.query);let e=qe(),r=new Set(e.map(w=>w.id)),a=!!t.query.trim();o(".trace-matches").textContent=a?`${e.length?Math.max(0,e.findIndex(w=>w.id===t.selectedSpanId)+1):0} / ${e.length}`:"";for(let w of["previous","next"]){let z=o(`[data-action="${w}"]`);z.hidden=!a,z.disabled=!e.length}let n=N.filter(w=>w.status==="warning"||w.status==="error"),s=n.some(w=>w.status==="error")?"issue":"warning",f=`${n.length} ${s}${n.length===1?"":"s"}`,p=o('[data-action="warnings"]');p.hidden=!n.length,p.setAttribute("aria-pressed",String(t.warnings)),p.setAttribute("aria-label",f),p.dataset.tooltip=f;let M=o('[data-action="critical"]'),C=v.criticalPath===void 0?"Estimated critical path":"Critical path";M.hidden=!ye.size,M.setAttribute("aria-pressed",String(t.critical)),M.setAttribute("aria-label",C),M.dataset.tooltip=C;let L=t.time==="direct"?"Direct time":"Total time",j=o('[data-menu="time"]');j.setAttribute("aria-label",L),j.dataset.tooltip=L,o(".wf-metric-label").textContent=t.time==="direct"?"Direct":"Total",o("th.wf-alternate-cell").textContent=t.time==="direct"?"Total time":"Direct time",o(".wf-value-header").setAttribute("aria-sort",t.order==="trace"?"none":t.order==="longest"?"descending":"ascending"),o(".wf-sort-icon").innerHTML=F(t.order==="trace"?"sort":t.order==="longest"?"down":"up"),o('[data-action="sort"]').title=t.order==="trace"?"Sort by longest duration":t.order==="longest"?"Sort by shortest duration":"Restore trace order",o('[data-action="expand"]').setAttribute("aria-label",t.collapsed.length?"Expand all spans":"Collapse all spans");for(let w of E("[data-field]")){let z=w.dataset.field;st(z)&&w.setAttribute("aria-checked",String(t[z]))}for(let w of E("[data-time]"))w.setAttribute("aria-checked",String(t.time===w.dataset.time));let se=mt(),pe=JSON.stringify(se.map(w=>w.id));if(pe!==Te){for(let w of se)m.append(k(_,w.id).row);Te=pe}let K=0;for(let w of se){let z=k(_,w.id),me=!!je(w);z.row.hidden=!me,z.row.dataset.stripe=String(me&&K++%2===0),z.row.dataset.selected=String(t.selectedSpanId===w.id);let we=t.critical&&!ye.has(w.id)||a&&!r.has(w.id);z.row.dataset.muted=String(we),z.row.dataset.warning=String(t.warnings&&(w.status==="warning"||w.status==="error")),z.disclosure.setAttribute("aria-expanded",String(!t.collapsed.includes(w.id))),z.disclosure.setAttribute("aria-label",`${t.collapsed.includes(w.id)?"Expand":"Collapse"} ${w.name}`),z.name.setAttribute("aria-pressed",String(t.selectedSpanId===w.id)),z.value.textContent=P(xe(w)),z.alternate.textContent=P(t.time==="total"?k(ee,w.id).duration:w.durationMs),k(oe,w.id).dataset.selected=String(t.selectedSpanId===w.id),k(oe,w.id).dataset.muted=String(we)}o(".wf-row-count").textContent=`${K} of ${N.length} spans`,wt(),te(),J()}function wt(){let e=t.selectedSpanId?X.get(t.selectedSpanId):void 0;if(!t.details||!e||!je(e)){ge.remove(),ve=null;return}if(be.colSpan=3+Number(t.service)+Number(t.bothTimes),ve!==e.id){be.replaceChildren();let a=b("div","wf-detail-title");a.append(b("span","",e.name));let n=b("div","wf-detail-actions"),s=b("button","btn btn-sm btn-ghost","Zoom to span");s.type="button",s.dataset.action="focus";let f=b("button","btn btn-sm btn-ghost trace-icon-button");f.type="button",f.dataset.action="close-detail",f.setAttribute("aria-label","Close span details"),f.innerHTML=F("close"),n.append(s,f),a.append(n);let p=b("dl","wf-detail-data"),M=[["Start",P(e.startMs)],["Total",P(e.durationMs)],["Direct",P(k(ee,e.id).duration)]];e.service&&M.push(["Service",e.service]),e.status&&e.status!=="ok"&&M.push(["Status",e.status]),M.push(...Object.entries(e.attributes??{}));for(let[C,L]of M){let j=b("div");j.append(b("dt","",C),b("dd","",String(L))),p.append(j)}be.append(a,p),ve=e.id}let r=k(_,e.id).row;r.nextSibling!==ge&&r.after(ge)}function te(){let e=I.clientWidth||900,r=A(t.durationWidth,64,180),a=(t.service?e*.14:0)+(t.bothTimes?80:0),n=Math.max(160,e-a-r-180),s=A(t.nameWidth??e*.33,160,n);y.style.setProperty("--wf-name-width",`${s}px`),y.style.setProperty("--wf-value-width",`${r}px`);for(let[f,p,M,C]of[["name",s,160,n],["duration",r,64,180]]){let L=o(`[data-column="${f}"]`);L.setAttribute("aria-valuenow",String(Math.round(p))),L.setAttribute("aria-valuemin",String(M)),L.setAttribute("aria-valuemax",String(Math.round(C))),L.setAttribute("aria-valuetext",`${Math.round(p)} pixels`)}}function Ke(e,r,a){let n=a>=t.startMs&&r<=t.endMs;if(e.hidden=!n,!n)return;let s=t.endMs-t.startMs,f=A((r-t.startMs)/s,0,1),p=A((a-t.startMs)/s,0,1);e.style.left=`${f*100}%`,e.style.width=`${Math.max(0,p-f)*100}%`}function J(){let e=t.endMs-t.startMs;pt.forEach((n,s)=>{n.textContent=P(t.startMs+e*s/4),n.hidden=T.clientWidth>0&&T.clientWidth<300&&s%2===1});for(let n of N){let s=k(_,n.id);Ke(s.bar,n.startMs,n.startMs+n.durationMs),s.segments.forEach((M,C)=>{let[L,j]=k(ee,n.id).intervals[C];Ke(M,L,j),t.time!=="direct"&&(M.hidden=!0)});let f=A((n.startMs+n.durationMs-t.startMs)/e,0,1);s.label.hidden=s.bar.hidden,s.label.textContent=P(xe(n)),s.label.style.left=`${f*100}%`,s.label.dataset.inside=String(f>.85);let p=n.startMs+n.durationMs;s.event.hidden=pt.endMs||!t.warnings||!(n.status==="warning"||n.status==="error"),s.event.style.left=`calc(${f*100}% - 2px)`}let r=t.startMs/v.durationMs*100,a=t.endMs/v.durationMs*100;H.style.left=`${r}%`,H.style.width=`${a-r}%`,H.dataset.zoomed=String(!ce()),o(".wf-shade-left").style.width=`${r}%`,o(".wf-shade-right").style.width=`${100-a}%`,o(".wf-range-label").textContent=`${P(t.startMs)}\u2013${P(t.endMs)} / ${P(v.durationMs)}`;for(let n of["start","end"])o(`[data-edge="${n}"]`).setAttribute("aria-label",`Adjust range ${n}: ${P(n==="start"?t.startMs:t.endMs)}`);o('[data-action="fit"]').disabled=ce(),o('[data-action="zoom-out"]').disabled=ce(),o('[data-action="zoom-in"]').disabled=e<=q()*1.001,o('[data-action="pan-left"]').disabled=t.startMs<=0,o('[data-action="pan-right"]').disabled=t.endMs>=v.durationMs}function q(){return Math.min(v.durationMs,Math.max(v.durationMs/1e4,.001))}function Ge(e,r){let a=A(r-e,q(),v.durationMs),n=A(e,0,v.durationMs-a);return[n,n+a]}function W(e,r,a=!0){[t.startMs,t.endMs]=Ge(e,r),J(),a&&Z()}function ce(){return t.startMs<=0&&t.endMs>=v.durationMs}function ue(e,r=.5){let a=t.endMs-t.startMs,n=A(a*e,q(),v.durationMs),s=t.startMs+a*r;W(s-n*r,s+n*(1-r))}function fe(e){let r=(t.endMs-t.startMs)*e;W(t.startMs+r,t.endMs+r)}function Xe(e){if(!e)return;let r=Math.max(e.durationMs*.05,q()/2);W(e.startMs-r,e.startMs+e.durationMs+r)}function Le(e,r=!0){!e||!X.has(e)||(t.selectedSpanId=e,t.details=r,t.collapsed=t.collapsed.filter(a=>!k(G,e).includes(a)),Y(),Z())}function Ie(e){let r=qe();if(!r.length)return;let a=r.findIndex(s=>s.id===t.selectedSpanId),n=a<0?e>0?0:r.length-1:(a+e+r.length)%r.length;Le(r[n].id,t.details),k(_,r[n].id).name.focus({preventScroll:!0}),k(_,r[n].id).row.scrollIntoView({block:"nearest",inline:"nearest"})}function Ue(){if(!U)return;let e=o(`[data-menu="${U}"]`),r=o(`[data-menu-panel="${U}"]`),a=e.getBoundingClientRect().right-y.getBoundingClientRect().left;r.style.right=`${Math.min(0,a-r.offsetWidth)}px`}function B(e,r=!1){U=e;for(let a of E("[data-menu-panel]"))a.hidden=a.dataset.menuPanel!==e;for(let a of E("[data-menu]"))a.setAttribute("aria-expanded",String(a.dataset.menu===e));Ue(),r&&e&&o(`[data-menu-panel="${e}"] button`).focus()}function ht(e){if(e.button!==0||e.ctrlKey||!re(e.target))return;let r=e.target.closest("button[data-menu]"),a=r?.dataset.menu;if(!Pe(a)||r?.disabled)return;let n=U!==a;n&&e.preventDefault(),B(n?a:null,n)}function gt(e){if(!re(e.target)||le)return;if(e.detail>0&&e.target.matches(".wf-menu-wrap")){let s=e.target.querySelector(".wf-menu-item:hover");s&&(s.focus(),s.click());return}let r=e.target.closest("button");if(!r||!y.contains(r)||r.disabled)return;let a=r.dataset.action,n=r.closest("[data-span-id]")?.dataset.spanId;if(Pe(r.dataset.menu)){e.detail===0&&B(U===r.dataset.menu?null:r.dataset.menu,!0);return}if(r.dataset.time==="total"||r.dataset.time==="direct")t.time=r.dataset.time,B(null),o('[data-menu="time"]').focus();else if(st(r.dataset.field))t[r.dataset.field]=!t[r.dataset.field];else if(a==="select"){Le(n,!(t.selectedSpanId===n&&t.details));return}else if(a==="collapse"&&n)t.collapsed=t.collapsed.includes(n)?t.collapsed.filter(s=>s!==n):[...t.collapsed,n];else if(a==="expand")t.collapsed=t.collapsed.length?[]:N.filter(s=>k(O,s.id).length).map(s=>s.id);else if(a==="critical")t.critical=!t.critical;else if(a==="warnings"){if(t.warnings=!t.warnings,t.warnings){let s=N.find(f=>f.status==="warning"||f.status==="error");s&&(t.selectedSpanId=s.id,t.details=!0,t.collapsed=t.collapsed.filter(f=>!k(G,s.id).includes(f)))}}else if(a==="sort")t.order=t.order==="trace"?"longest":t.order==="longest"?"shortest":"trace";else if(a==="close-detail")t.details=!1,t.selectedSpanId&&_.get(t.selectedSpanId)?.name.focus({preventScroll:!0});else if(a==="focus"){Xe(t.selectedSpanId?X.get(t.selectedSpanId):void 0);return}else if(a==="fit"){W(0,v.durationMs);return}else if(a==="zoom-in"){ue(.7);return}else if(a==="zoom-out"){ue(1/.7);return}else if(a==="pan-left"){fe(-.2);return}else if(a==="pan-right"){fe(.2);return}else if(a==="previous"){Ie(-1);return}else if(a==="next"){Ie(1);return}else return;Y(),Z()}function bt(e){if(!re(e.target))return;if(e.target===D){e.key==="Enter"&&(e.preventDefault(),Ie(e.shiftKey?-1:1)),e.key==="Escape"&&t.query&&(e.preventDefault(),t.query="",Y(),Z());return}let r=e.target.closest("[data-menu-panel]"),a=e.target.closest("[data-menu]");if(a&&Pe(a.dataset.menu)&&["ArrowDown","ArrowUp"].includes(e.key)){e.preventDefault(),B(a.dataset.menu,!0);return}if(r){let p=[...r.querySelectorAll("button")],M=e.target.closest("button"),C=M?p.indexOf(M):-1;if(["ArrowDown","ArrowUp","Home","End"].includes(e.key)){e.preventDefault();let L=e.key==="Home"?0:e.key==="End"?p.length-1:(C+(e.key==="ArrowDown"?1:-1)+p.length)%p.length;p[L].focus()}else if(e.key==="Escape"){e.preventDefault();let L=U;B(null),o(`[data-menu="${L}"]`).focus()}else e.key==="Tab"&&B(null);return}let n=e.target.closest("[data-column]");if(n&&["ArrowLeft","ArrowRight","Home"].includes(e.key)){e.preventDefault();let p=n.dataset.column,M=(e.key==="ArrowRight"?1:-1)*(e.shiftKey?32:8);p==="name"?t.nameWidth=e.key==="Home"?null:A(Number(n.getAttribute("aria-valuenow"))+M,160,Number(n.getAttribute("aria-valuemax"))):t.durationWidth=e.key==="Home"?80:A(t.durationWidth-M,64,180),te(),J(),Z();return}let s=e.target.closest("[data-edge]");if(s&&["ArrowLeft","ArrowRight","Home","End"].includes(e.key)){e.preventDefault();let p=v.durationMs*(e.shiftKey?.1:.01)*(e.key==="ArrowRight"?1:-1);if(s.dataset.edge==="start"){let M=e.key==="Home"?0:e.key==="End"?t.endMs-q():t.startMs+p;W(A(M,0,t.endMs-q()),t.endMs)}else{let M=e.key==="End"?v.durationMs:e.key==="Home"?t.startMs+q():t.endMs+p;W(t.startMs,A(M,t.startMs+q(),v.durationMs))}return}e.target.closest(".wf-track, .wf-axis")&&(["ArrowLeft","ArrowRight","+","=","-","_","Home"].includes(e.key)&&e.preventDefault(),e.key==="ArrowLeft"?fe(-.1):e.key==="ArrowRight"?fe(.1):["+","="].includes(e.key)?ue(.7):["-","_"].includes(e.key)?ue(1/.7):e.key==="Home"&&W(0,v.durationMs))}function yt(e){if(!re(e.target))return;let r=e.target.closest(".wf-track, .wf-axis, .wf-minimap");if(!r)return;e.preventDefault();let a=e.deltaMode===1?16:e.deltaMode===2?r.clientWidth:1,n=e.deltaX*a,s=e.deltaY*a;if(e.shiftKey||Math.abs(n)>Math.abs(s))fe((e.shiftKey&&s||n)/Math.max(1,r.clientWidth));else{let f=r.getBoundingClientRect();ue(Math.exp(A(s,-200,200)*.005),A((e.clientX-f.left)/Math.max(1,f.width),0,1))}}function vt(e){if(!re(e.target)||e.button!==0||S)return;let r=e.target.closest(".wf-resizer, .wf-track, .wf-axis, .wf-minimap");if(!r||r.classList.contains("wf-axis")&&e.target.closest("button"))return;B(null);let a=e.target.closest("[data-edge]")?.dataset.edge,n=r.getBoundingClientRect(),s="pan";r.classList.contains("wf-resizer")?s="resize":r===$&&(s=a==="start"||a==="end"?a:e.target.closest(".wf-window")&&!ce()?"overview-pan":"brush"),S={pointerId:e.pointerId,target:r,type:s,x:e.clientX,y:e.clientY,rect:n,moved:!1,startMs:t.startMs,endMs:t.endMs,nameWidth:t.nameWidth,durationWidth:t.durationWidth,column:r.dataset.column,columnWidth:Number(r.getAttribute("aria-valuenow")),anchor:A((e.clientX-n.left)/Math.max(1,n.width),0,1)*v.durationMs},r.focus?.({preventScroll:!0}),r.setPointerCapture?.(e.pointerId),e.preventDefault()}function xt(e){if(!S||S.pointerId!==e.pointerId)return;let r=e.clientX-S.x;if(!S.moved&&Math.abs(r)<3)return;if(S.moved=!0,y.dataset.dragging="true",S.type==="resize"){S.column==="name"?t.nameWidth=A(S.columnWidth+r,160,Number(S.target.getAttribute("aria-valuemax"))):t.durationWidth=A(S.durationWidth-r,64,180),te(),J();return}let a=S.endMs-S.startMs;if(S.type==="pan"){let n=-r/Math.max(1,S.rect.width)*a;W(S.startMs+n,S.endMs+n,!1)}else if(S.type==="overview-pan"){let n=r/Math.max(1,S.rect.width)*v.durationMs;W(S.startMs+n,S.endMs+n,!1)}else{let n=A((e.clientX-S.rect.left)/Math.max(1,S.rect.width),0,1)*v.durationMs;S.type==="start"?W(Math.min(n,S.endMs-q()),S.endMs,!1):S.type==="end"?W(S.startMs,Math.max(n,S.startMs+q()),!1):W(Math.min(S.anchor,n),Math.max(S.anchor,n),!1)}}function Q(e,r=!1){if(!S||e?.pointerId!==void 0&&e.pointerId!==S.pointerId)return;let a=S;if(S=null,y.dataset.dragging="false",a.target.hasPointerCapture?.(a.pointerId)&&a.target.releasePointerCapture(a.pointerId),r)t.startMs=a.startMs,t.endMs=a.endMs,t.nameWidth=a.nameWidth,t.durationWidth=a.durationWidth,te(),J();else if(a.moved)le=!0,u.clearTimeout(de),de=u.setTimeout(()=>{le=!1},0),Z();else if(a.target.classList.contains("wf-track")){let n=a.target.closest("[data-span-id]")?.dataset.spanId;Le(n,!(t.selectedSpanId===n&&t.details)),le=!0,u.clearTimeout(de),de=u.setTimeout(()=>{le=!1},0)}}y.addEventListener("mousedown",ht,{signal:g.signal}),y.addEventListener("click",gt,{signal:g.signal}),y.addEventListener("keydown",bt,{signal:g.signal}),y.addEventListener("wheel",yt,{passive:!1,signal:g.signal}),y.addEventListener("pointerdown",vt,{signal:g.signal}),y.addEventListener("lostpointercapture",e=>Q(e,!0),{signal:g.signal}),y.addEventListener("dblclick",e=>{if(!re(e.target))return;let r=e.target.closest("[data-column]");if(r)r.dataset.column==="name"?t.nameWidth=null:t.durationWidth=80,te(),J(),Z();else if(e.target.closest(".wf-minimap, .wf-axis"))W(0,v.durationMs);else{let a=e.target.closest("[data-span-id]")?.dataset.spanId;a&&!e.target.closest(".wf-disclosure")&&(t.selectedSpanId=a,Y(),Xe(X.get(a)))}},{signal:g.signal}),D.addEventListener("input",()=>{t.query=D.value,Y(),Z()},{signal:g.signal}),c.addEventListener("pointermove",xt,{signal:g.signal}),c.addEventListener("pointerup",e=>Q(e),{signal:g.signal}),c.addEventListener("pointercancel",e=>Q(e,!0),{signal:g.signal}),c.addEventListener("pointerdown",e=>{U&&!e.composedPath().some(r=>re(r)&&r.classList.contains("wf-menu-wrap")&&y.contains(r))&&B(null)},{signal:g.signal}),c.addEventListener("visibilitychange",()=>{c.hidden?(Q(null,!0),B(null)):(te(),J())},{signal:g.signal}),u.addEventListener("blur",()=>Q(null,!0),{signal:g.signal});let ze=new u.ResizeObserver(()=>{if(ie||c.hidden)return;Ue();let e=I.clientWidth;e===De||!e||(De=e,te(),J())});return ze.observe(I),ze.observe(y),{ready:Promise.resolve(),getState:$e,setState(e){ie||(Q(null,!0),t=Oe(e),B(null),Y())},update(e){if(ie)return;Q(null,!0);let r=$e(),a=ce(),n=e.id===v.id;n||ae.clear(),v=e,Ve(),t=n?Oe(r):Ce(),a&&n&&(t.startMs=0,t.endMs=v.durationMs),B(null),_e(),Y()},dispose(){ie||(Q(null,!0),ie=!0,g.abort(),ze.disconnect(),u.clearTimeout(de),y.remove(),h.remove(),_.clear(),oe.clear())}}}function It(i,d){let l=new Set;return i.length===1&&i[0].durationMs>0&&x(i[0]),l;function c(u){return u.startMs+u.durationMs}function x(u){l.add(u.id);let g=c(u),y=[...k(d,u.id)].sort((h,o)=>c(o)-c(h)||h.startMs-o.startMs||h.id.localeCompare(o.id,"en"));for(let h of y)h.durationMs>0&&h.startMs>=u.startMs&&c(h)<=g&&(x(h),g=h.startMs)}}function A(i,d,l){return Math.max(d,Math.min(l,i))}function P(i){if(!i)return"0 ms";let d=Math.abs(i),l=d>=1e3?i/1e3:d<1?i*1e3:i,c=d>=1e3?"s":d<1?"\xB5s":"ms";return`${Number(l.toFixed(Math.abs(l)<10?2:Math.abs(l)<100?1:0))} ${c}`}function re(i){return i!==null&&"nodeType"in i&&i.nodeType===Node.ELEMENT_NODE}function k(i,d){let l=i.get(d);if(l===void 0)throw new Error(`Missing waterfall item: ${d}`);return l}function zt(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function At(i){return Array.isArray(i)}function Ee(i){return typeof i=="number"&&Number.isFinite(i)}function Pe(i){return i==="time"||i==="fields"}function st(i){return i==="service"||i==="labels"||i==="bothTimes"}function Ht(i,d,l){let c=`viz-${i}`;if(customElements.get(c))return;let x=0,u=new Map([["title","title"],["description","description"]]);i==="flame-chart"&&u.set("thread-name","threadName");class g extends HTMLElement{static observedAttributes=["config","id",...u.keys()];static{for(let h of d.properties)Object.defineProperty(this.prototype,h,{configurable:!0,enumerable:!0,get(){let o=this.config;return o!==null&&typeof o=="object"?Reflect.get(o,h):void 0},set(o){let E=this.config;this.config={...E&&typeof E=="object"?E:{},[h]:o}}})}#d=`${c}-${++x}`;#i;#t=null;#e;#a;#s;#n=0;#r=Promise.resolve();constructor(){super(),this.attachShadow({mode:"open"});let h=new Set(["config","viewState",...d.properties]);for(let o of Object.getOwnPropertyNames(this)){if(!h.has(o))continue;let E=Reflect.get(this,o);Reflect.deleteProperty(this,o),Reflect.set(this,o,E)}}get config(){return this.#i===void 0?JSON.parse(this.getAttribute("config")??"null"):this.#i}set config(h){this.#i=h,this.#l()}get viewState(){return this.#e?.getState()??this.#t??null}set viewState(h){this.#t=h,this.#e&&this.#e.setState(h)}get ready(){return this.#r}connectedCallback(){this.#l()}disconnectedCallback(){this.#n++,this.#o(),l?.(this,!1)}attributeChangedCallback(h,o,E){o!==E&&this.#l()}#o(){this.#e&&(this.#t=this.#e.getState()),this.#e?.dispose(),this.#e=void 0,this.#a?.dispose(),this.#a=void 0,this.shadowRoot?.replaceChildren()}#c(){let h=this.config??{},o=this.id||this.#d;if(typeof h!="object"||Array.isArray(h))return d.check(h,o);let E={...h};for(let[m,I]of u){let T=this.getAttribute(m);T!==null&&(E[I]=T)}return d.check(E,o)}#l(){let h=++this.#n;this.isConnected&&(l?.(this,!0),this.#r=Promise.resolve().then(async()=>{if(this.isConnected){if(h!==this.#n)return this.#r;try{let o=this.#c();if(this.#e&&this.#s===o.id)this.#e.update(o);else{let E=this.#s;this.#o(),E&&E!==o.id&&(this.#t=null);let m=this.ownerDocument.createElement("style");m.textContent=":host{display:block;min-width:0}";let I=this.ownerDocument.createElement("div");this.shadowRoot.append(m,I),this.#a=nt(this.shadowRoot),this.#e=d.mount(I,o,{onStateChange:({state:T,selection:$})=>{this.#t=T,this.dispatchEvent(new CustomEvent("viz-state-change",{bubbles:!0,composed:!0,detail:{id:o.id,type:i,state:T,selection:$}}))}}),this.#s=o.id,this.#t&&this.#e.setState(this.#t)}if(await Promise.all([this.#e.ready,this.#a?.ready]),!this.isConnected)return;if(h!==this.#n)return this.#r;l?.(this,!1),this.dispatchEvent(new Event("viz-ready"))}catch(o){if(!this.isConnected)return;if(h!==this.#n)return this.#r;this.#o();let E=this.ownerDocument.createElement("p");E.setAttribute("role","alert"),E.style.cssText="font:inherit;color:var(--destructive,currentColor)";let m=o instanceof Error?o.message:String(o);E.textContent=`Viewer could not be rendered: ${m}`,this.shadowRoot.append(E),l?.(this,!1),this.dispatchEvent(new CustomEvent("viz-error",{bubbles:!0,composed:!0,detail:{message:m}}))}}}))}}customElements.define(c,g)}function lt(i){Ht("waterfall",{properties:["spans","criticalPath","durationMs"],check:at,mount:ot},i)}var dt=Symbol.for("openai.visualize.initial-widget-definitions.v1");function ut(){Reflect.has(document,dt)||(Reflect.set(document,dt,!0),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ct,{once:!0}):ct())}function ct(){let i=new Set(document.querySelectorAll("viz-calendar:not(:defined),viz-waterfall:not(:defined),viz-flame-chart:not(:defined),viz-stack-trace:not(:defined)"));if(i.size===0)return;let d=document.documentElement;he(d,!0);let l=new MutationObserver(c);l.observe(d,{childList:!0,subtree:!0});for(let x of new Set(Array.from(i,u=>u.localName)))customElements.whenDefined(x).then(c);function c(){if(i.size!==0){for(let x of i)(!x.isConnected||x.matches(":defined"))&&i.delete(x);i.size===0&&(l.disconnect(),he(d,!1))}}}var ft=new URL(import.meta.url).pathname.split("/").at(-2),Nt=/^(?:[a-f0-9]{64}|(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*))$/;if(!ft||!Nt.test(ft))throw new Error("Visualize widgets must be loaded from an immutable release directory");ut();var Rt=3,Wt="2ecedad0cf7ebc661e3a0e152fe2a9f0550bdcc4c1e15d7e3496d158ce8801c4";lt(he);export{Wt as buildId,Rt as widgetApiVersion}; diff --git a/frontend/public/vendor/request-waterfall.PROVENANCE.md b/frontend/public/vendor/request-waterfall.PROVENANCE.md new file mode 100644 index 0000000..7587505 --- /dev/null +++ b/frontend/public/vendor/request-waterfall.PROVENANCE.md @@ -0,0 +1,11 @@ +# Request waterfall viewer + +The locally bundled viewer is the exact version used by the supplied +`analysis/agent-latency-waterfall.html` and the approved activity prototype. + +Source: https://persistent.oaistatic.com/plugins/visualize/widgets/1.0.59/waterfall.js + +The application loads this pinned file locally, without a CDN or host API. +It uses the public `spans`, `durationMs`, `viewState`, `ready`, and +`viz-state-change` interfaces. Application telemetry and node details are +implemented separately and do not depend on the visualization host. diff --git a/frontend/src/components/activity/activity-panel.tsx b/frontend/src/components/activity/activity-panel.tsx index 35cadda..44df592 100644 --- a/frontend/src/components/activity/activity-panel.tsx +++ b/frontend/src/components/activity/activity-panel.tsx @@ -15,6 +15,7 @@ import { useTranslation } from "react-i18next"; import { Button } from "@/components/ui/button"; import { CodataLogo } from "@/components/ui/codata-logo"; import { ToolCallRow } from "@/components/activity/tool-call-row"; +import { ExecutionActivityPanel } from './execution-activity-panel'; import { IS_DESKTOP, TITLE_BAR_HEIGHT } from "@/lib/constants"; import { useIsMacOS } from "@/hooks/use-platform"; import { @@ -24,10 +25,10 @@ import { SheetDescription, } from "@/components/ui/sheet"; import * as VisuallyHidden from "@radix-ui/react-visually-hidden"; -import { useActivityStore, computeDuration, type ActivityData, type ChainItem } from "@/stores/activity-store"; +import { useActivityStore, type ActivityData, type ChainItem } from "@/stores/activity-store"; import { ACTIVITY_PANEL_WIDTH } from "@/lib/constants"; import { cn } from "@/lib/utils"; -import type { PartData, ToolPart, StepFinishPart, StepStartPart } from "@/types/message"; +import type { PartData, ToolPart, StepStartPart } from "@/types/message"; // -- Helpers -- @@ -563,156 +564,20 @@ function useIsDesktop() { } export function ActivityPanelContent({ showClose = true }: { showClose?: boolean } = {}) { - const { t } = useTranslation("chat"); const activeData = useActivityStore((s) => s.activeData); const close = useActivityStore((s) => s.close); - const timelineItems = useMemo( () => (activeData?.chain ? buildTimelineItems(activeData.chain) : []), [activeData], ); - if (!activeData) return null; - if (activeData.mode === "expert-team") { - return ; - } - - // Aggregate metrics from step-finish parts - const stepFinishes = activeData.stepParts.filter( - (p): p is StepFinishPart => p.type === "step-finish", - ); - const totalTokens = stepFinishes.reduce((acc, sf) => { - const t = sf.tokens; - return { - input: acc.input + (t.input || 0), - output: acc.output + (t.output || 0), - }; - }, { input: 0, output: 0 }); - const totalCost = stepFinishes.reduce((acc, sf) => acc + (sf.cost || 0), 0); - const hasMetrics = totalTokens.input > 0 || totalTokens.output > 0 || totalCost > 0; - - // Compute total duration - const duration = computeDuration(activeData); - const durationLabel = duration != null && duration > 0 ? `${duration}s` : ""; - const hasRunningTools = activeData.toolParts.some( - (tool) => tool.state.status === "running" || tool.state.status === "pending", - ); - const hasTerminalStepFinish = stepFinishes.some((part) => part.reason !== "tool_use"); - const isComplete = (hasTerminalStepFinish || !!activeData.hasVisibleOutput) && !hasRunningTools; - - return ( -
-
-
-
-

{t("activity")}

-

工具调用与推理过程

-
-
- {durationLabel && ( - - {durationLabel} - - )} - {showClose && ( - - )} -
-
-
- -
- {activeData.toolParts.length > 0 && ( -
-

工具调用

-
- {activeData.toolParts.map((tool) => ( - - ))} -
-
- )} - -
-

推理过程

-
- {timelineItems - .filter((item) => item.kind === "thinking-group") - .map((item, i) => ( - - ))} - - {isComplete ? ( -
-
- -
- {durationLabel && ( -

- {t("thoughtFor", { duration: durationLabel })} -

- )} -

{t("done")}

-
- ) : ( -
-
- -
-

- {hasRunningTools ? t("stageWorkingWithTools") : t("stageFinalizing")} -

-
- )} -
-
- - {/* Metrics */} - {hasMetrics && ( -
-

- {t("metrics")} -

-
- {totalTokens.input > 0 && ( -
- {t("input")} - - {totalTokens.input.toLocaleString()} - -
- )} - {totalTokens.output > 0 && ( -
- {t("output")} - - {totalTokens.output.toLocaleString()} - -
- )} - {totalCost > 0 && ( -
- {t("credits")} - - {(totalCost * 100).toFixed(2)} cr - -
- )} -
-
- )} -
-
- ); + if (activeData.mode === "expert-team") return ; + return item.kind === 'thinking-group') ?
+

过程摘要

+
{timelineItems.filter(item => item.kind === 'thinking-group').map((item,i) => )}
+
: undefined} />; } - export function ActivityPanel() { const { t } = useTranslation("chat"); const isOpen = useActivityStore((s) => s.isOpen); diff --git a/frontend/src/components/activity/activity-summary.tsx b/frontend/src/components/activity/activity-summary.tsx index a769d83..72b3fc5 100644 --- a/frontend/src/components/activity/activity-summary.tsx +++ b/frontend/src/components/activity/activity-summary.tsx @@ -1,10 +1,11 @@ "use client"; -import { CheckCircle2, ChevronRight, Wrench } from "lucide-react"; +import { CheckCircle2, ChevronRight, Wrench, XCircle, CircleSlash } from "lucide-react"; import { useTranslation } from "react-i18next"; import { CodataLogo } from "@/components/ui/codata-logo"; import { useActivityStore, type ActivityData } from "@/stores/activity-store"; import { useRightSidebarStore } from "@/stores/right-sidebar-store"; +import { useExecutionTraceStore } from '@/stores/execution-trace-store'; interface ActivitySummaryProps { data: ActivityData; @@ -15,6 +16,13 @@ export function ActivitySummary({ data }: ActivitySummaryProps) { const toggleForMessage = useActivityStore((s) => s.toggleForMessage); const rightSidebarOpen = useRightSidebarStore((s) => s.isOpen); const activeTab = useRightSidebarStore((s) => s.activeTab); + const completed=useExecutionTraceStore(s=>data.traceId&&s.traces[data.traceId]?.spans.length?s.traces[data.traceId].completed:undefined)??data.executionTrace?.completed; + const rootStatus=useExecutionTraceStore(s=>data.traceId?s.traces[data.traceId]?.spans.find(p=>p.kind==='request')?.status:undefined) + ??data.executionTrace?.spans.find(p=>p.kind==='request')?.status; + const measuredMs=useExecutionTraceStore(s=>data.traceId?s.traces[data.traceId]?.metrics.end_to_end_ms:undefined) + ??data.executionTrace?.client?.metrics.end_to_end_ms; + const measuredTools=useExecutionTraceStore(s=>data.traceId&&s.traces[data.traceId]?.spans.length?s.traces[data.traceId].spans.filter(p=>p.kind==='tool').length:undefined) + ??data.executionTrace?.spans.filter(p=>p.kind==='tool').length; const isActiveOpen = useActivityStore( (s) => rightSidebarOpen && @@ -26,22 +34,21 @@ export function ActivitySummary({ data }: ActivitySummaryProps) { const hasReasoning = data.reasoningTexts.length > 0; const hasTools = data.toolParts.length > 0; - const totalDuration = data.totalDuration; + const totalDuration = measuredMs===undefined?data.totalDuration:measuredMs/1000; const lastStepFinish = [...data.stepParts] .reverse() .find((part) => part.type === "step-finish"); const hasRunningTools = data.toolParts.some( (tool) => tool.state.status === "running" || tool.state.status === "pending", ); - const isCompleted = - (!!lastStepFinish && lastStepFinish.reason !== "tool_use") || - (!!data.hasVisibleOutput && !hasRunningTools); + const isCompleted = completed ?? ((!!lastStepFinish && lastStepFinish.reason !== "tool_use") || + (!!data.hasVisibleOutput && !hasRunningTools)); - if (!hasReasoning && !hasTools) return null; + if (!hasReasoning && !hasTools && !data.traceId) return null; const parts: string[] = []; if (isCompleted) { - parts.push(t("done")); + parts.push(rootStatus==='error'?'执行失败':rootStatus==='cancelled'?'已取消':rootStatus==='incomplete'?'未完整采集':t("done")); } else if (hasReasoning) { parts.push( data.thinkingDuration != null @@ -49,8 +56,8 @@ export function ActivitySummary({ data }: ActivitySummaryProps) { : t("reasoning"), ); } - if (hasTools) { - const count = data.toolParts.length; + if (hasTools||measuredTools) { + const count = measuredTools??data.toolParts.length; parts.push(t("toolCallCount", { count })); } if (totalDuration != null && totalDuration > 0) { @@ -64,7 +71,7 @@ export function ActivitySummary({ data }: ActivitySummaryProps) { className="data-agent-card group flex items-center gap-2 rounded-lg px-3 py-2 text-xs text-[var(--text-tertiary)] transition-colors hover:border-[var(--border-heavy)] hover:text-[var(--text-secondary)]" > {isCompleted ? ( - + rootStatus==='error'?:rootStatus==='cancelled'||rootStatus==='incomplete'?: ) : hasReasoning ? ( ) : ( diff --git a/frontend/src/components/activity/execution-activity-panel.tsx b/frontend/src/components/activity/execution-activity-panel.tsx new file mode 100644 index 0000000..ea69a1d --- /dev/null +++ b/frontend/src/components/activity/execution-activity-panel.tsx @@ -0,0 +1,225 @@ +"use client"; + +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import { Activity, ChartNoAxesGantt, GitBranch, Info, List, Maximize2, Minimize2, Radio, X, Play, Pause, RotateCcw, SkipBack, SkipForward } from 'lucide-react'; +import { api } from '@/lib/api'; +import { displaySpans } from '@/lib/execution-trace'; +import { durationLabel,layoutTrace,relatedToolSpans } from '@/lib/trace-layout'; +import { replaySpans, replayBoundaries, nextReplayTime } from '@/lib/trace-replay'; +import {readTraceViewState,saveTraceViewState} from '@/lib/trace-view-state'; +import { useExecutionTraceStore } from '@/stores/execution-trace-store'; +import type { ActivityData } from '@/stores/activity-store'; +import type { ExecutionTrace, LiveTrace, TraceSpan } from '@/types/execution-trace'; +import type { ToolPart } from '@/types/message'; +import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog'; +import { ToolCallRow } from './tool-call-row'; +import { TraceWaterfall } from './trace-waterfall'; +import { TraceGraph } from './trace-graph'; +import styles from './trace-studio.module.css'; + +type View = 'tools' | 'waterfall' | 'graph'; +const statusText: Record = {running:'执行中',ok:'已完成',error:'失败',cancelled:'已取消',incomplete:'未完整采集'}; +const dump = (value:unknown) => { const text=JSON.stringify(value,null,2)??'未采集';return text.length>30000?text.slice(0,30000)+'\n… 内容已截断':text; }; + +export function ExecutionActivityPanel({ data, onClose, showClose = true, reasoning }: { + data: ActivityData; onClose: () => void; showClose?: boolean; reasoning?: ReactNode; +}) { + const traceId = data.traceId ?? data.executionTrace?.trace_id; + const cacheKey=traceId??data.sourceKey??'pending'; + const initial=useRef(readTraceViewState(cacheKey)); + const trace = useExecutionTraceStore(s => traceId ? s.traces[traceId] : undefined); + const [view,setView] = useState(initial.current?.view??'tools'); + const [selected,setSelected] = useState(initial.current?.selected??null), [expanded,setExpanded]=useState(initial.current?.expanded??false); + const [follow,setFollow]=useState(initial.current?.follow??true), [clockHelp,setClockHelp]=useState(initial.current?.clockHelp??false); + const [tab,setTab]=useState<'summary'|'io'|'events'>(initial.current?.tab??'summary'), [now,setNow]=useState(0); + const [locate,setLocate]=useState(initial.current?.locate??0), [loading,setLoading]=useState(false), [loadError,setLoadError]=useState(''); + const [replayMs,setReplayMs]=useState(initial.current?.replayMs??null),[playing,setPlaying]=useState(initial.current?.playing??false),[speed,setSpeed]=useState(initial.current?.speed??1); + const waterfallState = useRef>(initial.current?.waterfall??{}); + const [expandedToolIds,setExpandedToolIds]=useState(initial.current?.expandedToolIds??[]); + const [toolTargets,setToolTargets]=useState(initial.current?.toolTargets??[]); + const toolsSection=useRef(null),toolElements=useRef(new Map()); + useLayoutEffect(()=>saveTraceViewState(cacheKey,{view,selected,expanded,follow,clockHelp,tab,locate,replayMs,playing,speed,expandedToolIds,toolTargets,waterfall:waterfallState.current}), + [cacheKey,view,selected,expanded,follow,clockHelp,tab,locate,replayMs,playing,speed,expandedToolIds,toolTargets]); + useEffect(()=>{ + if(initial.current?.view)return; + const saved=localStorage.getItem('codata-activity-view'); + if(saved==='tools'||saved==='waterfall'||saved==='graph')setView(saved); + },[]); + useEffect(()=>{ + setLoadError(''); + if(!traceId||!data.sessionId)return; + const store=useExecutionTraceStore.getState(); + if(data.executionTrace){store.hydrate(data.sessionId,data.executionTrace);return;} + if(store.traces[traceId]?.spans.length)return; + let alive=true;setLoading(true); + api.get(`/api/chat/trace/${encodeURIComponent(traceId)}?session_id=${encodeURIComponent(data.sessionId)}`) + .then(snapshot=>{if(alive)useExecutionTraceStore.getState().hydrate(data.sessionId!,snapshot);}) + .catch(()=>{if(alive)setLoadError('未找到该次执行的计时记录,旧会话可能尚未采集。');}) + .finally(()=>{if(alive)setLoading(false);}); + return()=>{alive=false;}; + },[traceId,data.sessionId,data.executionTrace]); + const running=!!trace&&!trace.completed; + useEffect(()=>{ + setNow(performance.now()); + if(!running)return; + const timer=setInterval(()=>setNow(performance.now()),250); + return()=>clearInterval(timer); + },[traceId,running]); + const completed=trace?.completed; + // Collection remains per-event. Heavy views consume at most four live + // snapshots/second, with immediate final/history flushes. + // eslint-disable-next-line react-hooks/exhaustive-deps + const frameTrace=useMemo(()=>trace,[traceId,now,completed,completed?trace?.spans:null,completed?trace?.clientSpans:null]); + const completeSpans=useMemo(()=>frameTrace?displaySpans(frameTrace,now):[],[frameTrace,now]); + const spans=useMemo(()=>replayMs===null?completeSpans:replaySpans(completeSpans,replayMs),[completeSpans,replayMs]); + const replayTotal=useMemo(()=>Math.max(0,...completeSpans.map(s=>s.startMs+s.durationMs)),[completeSpans]); + const boundaries=useMemo(()=>replayBoundaries(view==='graph'?layoutTrace(completeSpans).nodes.map(n=>n.span):view==='tools'?completeSpans.filter(s=>s.kind==='tool'):completeSpans),[completeSpans,view]); + const replaying=replayMs!==null; + const emptyMessage=replaying?'回放开始,等待首个阶段…':loading?'正在读取计时记录…':loadError||'该历史记录未采集细分计时。新执行会实时记录,缺失项不会补造。'; + useEffect(()=>{ + if(!playing||replayMs===null)return; + let last=performance.now(); + const timer=setInterval(()=>{const at=performance.now(),delta=(at-last)*speed;last=at; + setReplayMs(current=>{if(current===null)return null;const next=Math.min(replayTotal,current+delta);if(next>=replayTotal)setPlaying(false);return next;}); + },100); + return()=>clearInterval(timer); + // Cursor advances inside the interval; seeking should not recreate it per frame. + // eslint-disable-next-line react-hooks/exhaustive-deps + },[playing,speed,replayTotal,replaying]); + const chosen=spans.find(s=>s.id===selected); + const related=useMemo(()=>relatedToolSpans(selected,spans),[selected,spans]); + const scrollToTool=useCallback(()=>{ + const target=toolElements.current.get(toolTargets[0]),section=toolsSection.current; + if(target&§ion)section.scrollTo({top:section.scrollTop+target.getBoundingClientRect().top-section.getBoundingClientRect().top-12,behavior:'smooth'}); + },[toolTargets]); + useEffect(()=>{ + if(view!=='tools'||!toolTargets.length)return; + const frame=requestAnimationFrame(scrollToTool); + return()=>cancelAnimationFrame(frame); + },[view,toolTargets,expanded,scrollToTool]); + const toolSpans=spans.filter(s=>s.kind==='tool'); + const firstToken=spans.find(s=>s.name==='请求发出 → 首 token'&&s.status==='ok'); + const rootSpan=spans.find(s=>s.kind==='request'); + const modelCount=spans.filter(s=>s.kind==='model').length; + const elapsed=replayMs??trace?.metrics.end_to_end_ms??(trace?.completed?trace.duration_ms:rootSpan?.durationMs); + const allTools=useMemo(()=>[...data.toolParts,...completeSpans.filter(s=>s.kind==='tool'&&s.attributes.source_session_id&&s.attributes.source_session_id!==data.sessionId).map(s=>({ + type:'tool' as const,tool:s.name,call_id:String(s.attributes.call_id??s.id),state:{ + status:s.status==='running'?'running' as const:s.status==='error'||s.status==='cancelled'?'error' as const:'completed' as const, + input:(s.attributes.input??{}) as Record,output:String(s.attributes.output_preview||s.attributes.error_preview||''), + title:`子智能体 · ${s.name}`,time_start:null,time_end:null,time_compacted:null, + metadata:{__trace_span_id:s.id,source_session_id:s.attributes.source_session_id,trace_output_preview:true}, + }, + }))],[data.toolParts,data.sessionId,completeSpans]); + const visibleTools=useMemo(()=>!replaying?allTools:allTools.flatMap(tool=>{ + const span=spans.find(s=>s.kind==='tool'&&(tool.state.metadata?.__trace_span_id?s.id===tool.state.metadata.__trace_span_id:s.attributes.call_id===tool.call_id&&!s.attributes.source_session_id));if(!span)return []; + return [{...tool,state:{...tool.state,status:span.status==='running'?'running' as const:span.status==='error'||span.status==='cancelled'?'error' as const:'completed' as const, + output:span.status==='running'?null:tool.state.output,metadata:span.status==='running'?(tool.state.metadata?.__trace_span_id?{__trace_span_id:tool.state.metadata.__trace_span_id,source_session_id:tool.state.metadata.source_session_id,trace_output_preview:true}:null):tool.state.metadata}}]; + }),[allTools,replaying,spans]); + const inspectorData=useMemo(()=>({...data,toolParts:visibleTools}),[data,visibleTools]); + function changeView(v:View){ + setView(v);localStorage.setItem('codata-activity-view',v); + if(v==='tools'){ + const targets=relatedToolSpans(selected,spans).map(s=>s.id); + setToolTargets(targets); + if(targets.length)setExpandedToolIds(previous=>[...new Set([...previous,...targets])]); + } + } + const choose=useCallback((id:string)=>{if(selected!==id)setTab('summary');setSelected(id);setFollow(false);},[selected]); + const pauseFollow=useCallback(()=>setFollow(false),[]); + const resumeFollow=useCallback(()=>setFollow(true),[]); + function locateIn(v:View){changeView(v);if(v!=='tools')setLocate(n=>n+1);} + const panel=
+

活动

工具调用、执行链路与端到端性能

+ {replaying?(playing?'历史回放中':'历史回放已暂停'):trace?(trace.completed?(rootSpan?.status==='error'?'执行失败':rootSpan?.status==='cancelled'?'已取消':'执行完成'):'执行中 · 实时更新'):'调用记录'} + {trace?.completed&&completeSpans.length>0&&} + + {showClose&&} +
+
+
+ {([{id:'tools',label:'工具调用',Icon:List},{id:'waterfall',label:'性能瀑布',Icon:ChartNoAxesGantt},{id:'graph',label:'调用节点',Icon:GitBranch}] as const).map(({id,label,Icon})=>)} +
+ +
+
+ {replaying?'回放位置':'总耗时'} {elapsed===undefined?'未采集':durationLabel(elapsed)} + 模型首 token {firstToken?durationLabel(firstToken.durationMs):replaying&&completeSpans.some(s=>s.name==='请求发出 → 首 token'&&s.status==='ok')?'等待中':trace?.completed?'未采集':'等待中'} + 首文本上屏 {replaying&&!spans.some(s=>s.id==='client-first-paint'&&s.status==='ok')&&trace?.metrics.first_text_paint_ms!==undefined?'等待中':trace?.metrics.first_text_paint_ms!==undefined?durationLabel(trace.metrics.first_text_paint_ms):trace?.completed?'未采集':'等待中'} + 工具执行中 {spans.filter(s=>s.name==='工具执行'&&s.status==='running').length} + +
+ {replaying&&
+
+ + + + + +
+
{setPlaying(false);setReplayMs(Number(e.target.value));}}/>{durationLabel(replayMs??0)} / {durationLabel(replayTotal)}
+

按真实跨度时间回放 · 不重新调用模型或工具

+
} + {clockHelp&&
总耗时优先使用点击发送到最终交接绘制的浏览器单调时钟;其他端或后台页未采到绘制时显示服务端耗时。首 token 包含提供商排队、网络与预填充,无法从客户端单独拆分。模型总跨度含本地流消费,等待提供商分块的累计时间在详情中单列。工具排队与执行分别测量;SQL 驱动的执行可能包含接收缓冲,连接获取包含连接池等待、建连与预检。SSE 从发送准备到浏览器回调的间隔含 ASGI、传输与回调排队,不能当作纯网络延迟;跨端校准误差至少 RTT/2。语义服务跨度在各自单调时钟内测量,位置对齐误差见详情。双帧回调近似绘制。并行子项不能直接相加;历史缺失项显示“未采集”。
} +
+
+ + + +
+ {chosen&&setSelected(null)} onLocate={locateIn}/>} +
+
{spans.filter(s=>!s.attributes.__view_derived).length} spans{spans.some(s=>s.attributes.__view_derived)?' + 1 范围容器':''} · {modelCount} 次模型 · {toolSpans.length} 次工具{trace?.dropped_spans?` · ${trace.dropped_spans} 项超限未记录`:''}{traceId??'历史记录 · 未采集 trace'}
+
; + return expanded?setExpanded(open)}>活动与性能分析工具调用、性能瀑布和调用节点三种视图{panel}:panel; +} + +function TraceInspector({span,spans,trace,data,tab,setTab,onSelect,onClose,onLocate}:{ + span:TraceSpan;spans:TraceSpan[];trace:LiveTrace|undefined;data:ActivityData; + tab:'summary'|'io'|'events';setTab:(tab:'summary'|'io'|'events')=>void; + onSelect:(id:string)=>void;onClose:()=>void;onLocate:(v:View)=>void; +}) { + const inspectorElement=useRef(null); + useEffect(()=>{inspectorElement.current?.scrollTo({top:0});},[span.id,tab]); + const children=spans.filter(s=>s.parentId===span.id).sort((a,b)=>a.startMs-b.startMs); + const queue=children.find(s=>s.service==='工具排队'),execution=children.find(s=>s.name==='工具执行'); + let owner:TraceSpan|undefined=span; + const seen=new Set(); + while(owner&&owner.kind!=='tool'&&!seen.has(owner.id)){seen.add(owner.id);owner=spans.find(s=>s.id===owner?.parentId);} + const tool=owner&&data.toolParts.find(t=>t.state.metadata?.__trace_span_id?t.state.metadata.__trace_span_id===owner?.id:t.call_id===owner?.attributes.call_id&&!owner?.attributes.source_session_id); + const sourceSession=span.attributes.source_session_id??owner?.attributes.source_session_id; + const related=relatedToolSpans(span.id,spans); + const derived=span.attributes.__view_derived===true; + const recordedParent=Object.prototype.hasOwnProperty.call(span.attributes,'__recorded_parent_id')?span.attributes.__recorded_parent_id:span.parentId; + const events=trace?.events.filter(e=>e.id===Number((span.attributes.delivery as {event_seq?:number}|undefined)?.event_seq))??[]; + return ; +} diff --git a/frontend/src/components/activity/tool-call-row.tsx b/frontend/src/components/activity/tool-call-row.tsx index a541f20..8b09187 100644 --- a/frontend/src/components/activity/tool-call-row.tsx +++ b/frontend/src/components/activity/tool-call-row.tsx @@ -18,7 +18,10 @@ import { Plug, Search, XCircle, + CircleSlash, } from "lucide-react"; +import { durationLabel } from '@/lib/trace-layout'; +import type { TraceSpan } from '@/types/execution-trace'; import { AnimatePresence, motion } from "framer-motion"; import { useTranslation } from "react-i18next"; import type { ToolPart } from "@/types/message"; @@ -87,13 +90,17 @@ function getElapsed(tool: ToolPart): string { return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`; } -export function ToolCallRow({ tool }: { tool: ToolPart }) { +export function ToolCallRow({ tool, timing, onInspect,expanded,onExpandedChange,onExpansionComplete,highlighted=false }: { tool: ToolPart; timing?: {durationMs:number;queueMs?:number;executionMs?:number;queued?:boolean;status:TraceSpan['status']}; onInspect?:()=>void;expanded?:boolean;onExpandedChange?:(open:boolean)=>void;onExpansionComplete?:(open:boolean)=>void;highlighted?:boolean }) { const { t } = useTranslation("chat"); - const [isOpen, setIsOpen] = useState(false); + const [localOpen,setLocalOpen] = useState(false); + const isOpen=expanded??localOpen; + const setIsOpen=(open:boolean)=>{if(onExpandedChange)onExpandedChange(open);else setLocalOpen(open);}; const ToolIcon = TOOL_ICONS[tool.tool] ?? Plug; - const isRunning = tool.state.status === "running" || tool.state.status === "pending"; - const isError = tool.state.status === "error"; - const elapsed = getElapsed(tool); + const actualStatus = timing?.status ?? tool.state.status; + const isRunning = actualStatus === "running" || actualStatus === "pending"; + const isError = actualStatus === "error"; + const isCancelled = actualStatus === 'cancelled'; + const elapsed = timing ? durationLabel(timing.durationMs) : getElapsed(tool); const title = getToolTitle(tool); const sources = useMemo(() => { @@ -106,11 +113,11 @@ export function ToolCallRow({ tool }: { tool: ToolPart }) { const moreCount = sources.length - MAX_VISIBLE_SOURCES; return ( -
+
{isRunning ? ( - ) : isError ? ( + ) : isCancelled ? : isError ? ( ) : ( @@ -119,6 +126,7 @@ export function ToolCallRow({ tool }: { tool: ToolPart }) { } )} diff --git a/frontend/src/components/activity/trace-graph.tsx b/frontend/src/components/activity/trace-graph.tsx new file mode 100644 index 0000000..cd9d714 --- /dev/null +++ b/frontend/src/components/activity/trace-graph.tsx @@ -0,0 +1,103 @@ +"use client"; + +import { memo,useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import {readTraceViewState,saveTraceViewState} from '@/lib/trace-view-state'; +import { Minus, Plus, Scan, LocateFixed } from 'lucide-react'; +import { layoutTrace, nearestGraphNode, durationLabel,truncateGraphLabel } from '@/lib/trace-layout'; +import type { TraceSpan } from '@/types/execution-trace'; +import styles from './trace-studio.module.css'; + +export const TraceGraph=memo(function TraceGraph({ cacheKey,active, spans, selectedId, onSelect, follow, onPauseFollow, onResumeFollow, locateVersion }: { + cacheKey:string; + active: boolean; + spans: TraceSpan[]; selectedId: string | null; onSelect: (id: string) => void; + follow: boolean; onPauseFollow: () => void; onResumeFollow:()=>void; locateVersion: number; +}) { + const layout = useMemo(() => active?layoutTrace(spans):{nodes:[],edges:[],height:300,minX:0,maxX:850,width:850}, [active,spans]); + const [camera, setCamera] = useState(()=>readTraceViewState(cacheKey)?.graphCamera??{x:0,y:0,w:850}); + useLayoutEffect(()=>saveTraceViewState(cacheKey,{graphCamera:camera}),[cacheKey,camera]); + const lastLocate=useRef(locateVersion); + const [size, setSize] = useState({w:600,h:520}); + const stage = useRef(null), drag = useRef<{x:number;y:number;cx:number;cy:number} | null>(null); + const graphElement=useRef(null); + const focused = nearestGraphNode(selectedId, spans, layout.nodes); + const map = new Map(layout.nodes.map(n => [n.id,n])); + const scale = camera.w / Math.max(1,size.w), height = size.h * scale, overview = 100/scale < 64; + const r = (overview?Math.min(5,35/scale):8)*scale; + const labelStride=Math.max(1,Math.ceil(18*scale/100)); + const peers=new Map(); + const last = layout.nodes.findLast(n => n.span.status === 'running') ?? layout.nodes.at(-1); + const lastY=last?.y; + useEffect(() => { + if (!stage.current) return; + const observer = new ResizeObserver(([entry]) => { + if(entry.contentRect.width>0&&entry.contentRect.height>0)setSize({w:entry.contentRect.width,h:entry.contentRect.height}); + }); + observer.observe(stage.current); return () => observer.disconnect(); + }, [active]); + useEffect(() => { + if (active && follow && lastY!==undefined) setCamera(c => ({...c,x:425-c.w/2,y:Math.max(0,lastY-size.h*c.w/size.w*.65)})); + }, [active,follow, lastY, size.h, size.w]); + useEffect(() => { + if(lastLocate.current===locateVersion)return; + lastLocate.current=locateVersion; + if (locateVersion && focused) { + const n = layout.nodes.find(n=>n.id===focused); + if(n) setCamera(c=>({...c,x:n.x-c.w/2,y:Math.max(0,n.y-150*scale)})); + } + // A deliberate locate action, not every clock tick. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [locateVersion]); + useEffect(()=>{ + const svg=graphElement.current;if(!active||!svg)return; + const onWheel=(e:WheelEvent)=>{ + e.preventDefault();onPauseFollow(); + setCamera(c=>{ + if(e.ctrlKey||e.metaKey){const w=Math.max(350,Math.min(Math.max(5000,layout.width+200),c.w*(e.deltaY>0?1.1:.9)));return {...c,x:c.x+(c.w-w)/2,y:c.y+(c.w-w)*size.h/size.w/2,w};} + return {...c,y:c.y+e.deltaY*c.w/size.w}; + }); + }; + svg.addEventListener('wheel',onWheel,{passive:false});return()=>svg.removeEventListener('wheel',onWheel); + },[active,onPauseFollow,size.h,size.w,layout.width]); + function zoom(factor:number){onPauseFollow();setCamera(c=>{const w=Math.max(350,Math.min(Math.max(5000,layout.width+200),c.w*factor));return {...c,x:c.x+(c.w-w)/2,y:c.y+(c.w-w)*size.h/size.w/2,w};});} + function fit(){onPauseFollow();const w=Math.max(layout.width+100,layout.height/size.h*size.w);setCamera({x:(layout.minX+layout.maxX)/2-w/2,y:0,w});} + function color(s:TraceSpan){return s.status==='error'?'var(--trace-red)':s.status==='cancelled'?'var(--text-tertiary)':s.kind==='model'?'var(--trace-purple)':s.kind==='tool'?'var(--trace-green)':s.kind==='frontend'||s.kind==='sse'?'var(--trace-blue)':'var(--text-tertiary)';} + const viewBox=`${camera.x} ${camera.y} ${camera.w} ${height}`; + if(!active)return null; + return
+
+ +
+
+
+ {if((e.target as Element).closest('[data-node]'))return;e.preventDefault();onPauseFollow();drag.current={x:e.clientX,y:e.clientY,cx:camera.x,cy:camera.y};e.currentTarget.setPointerCapture(e.pointerId);}} + onPointerMove={e=>{const d=drag.current;if(d)setCamera(c=>({...c,x:d.cx-(e.clientX-d.x)*scale,y:d.cy-(e.clientY-d.y)*scale}));}} + onPointerUp={()=>{drag.current=null;}} onPointerCancel={()=>{drag.current=null;}} onLostPointerCapture={()=>{drag.current=null;}}> + {layout.edges.map((edge,i)=>{const a=map.get(edge.from)!,b=map.get(edge.to)!;return ;})} + {layout.nodes.map(n=>{ + const selected=focused===n.id, left=n.x<425, c=color(n.span), running=n.span.status==='running'; + const queued=n.span.kind==='tool'&&spans.some(s=>s.parentId===n.id&&s.service==='工具排队'&&s.status==='running'); + const peer=peers.get(n.y)??0;peers.set(n.y,peer+1); + const showLabel=!overview||selected||n.id===last?.id||(Math.round((n.y-60)/100)%labelStride===0&&peer%Math.max(1,Math.ceil(140*scale/330))===0); + return onSelect(n.id)} onKeyDown={e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();onSelect(n.id);}}} className={styles.graphNode}> + {n.label} · {n.span.status} · {durationLabel(n.span.durationMs)} + + + {selected&&} + + + {showLabel&&{truncateGraphLabel(n.label,Math.min(220,330/scale-18))}} + {!overview&&{running?(queued?'排队中':n.span.attributes.checkpoint==='join'?'等待汇合':'执行中'):n.span.status==='ok'?'已完成':n.span.status==='error'?'失败':n.span.status==='cancelled'?'已取消':'未完整采集'} · {durationLabel(n.span.durationMs)}} + ; + })} + + +
+
● 用户 / 检查点● 模型● 工具 / SQL虚线:失败后修正
+
; +}); diff --git a/frontend/src/components/activity/trace-render-probe.tsx b/frontend/src/components/activity/trace-render-probe.tsx new file mode 100644 index 0000000..26241a5 --- /dev/null +++ b/frontend/src/components/activity/trace-render-probe.tsx @@ -0,0 +1,12 @@ +"use client"; +import { Profiler, useLayoutEffect, useRef, type ReactNode } from 'react'; +import { recordArtifactCommit } from '@/lib/execution-trace'; + +/** In production without React profiling, layout effect still measures delivery-to-frame. */ +export function TraceRenderProbe({traceId,callId,children}:{traceId?:string;callId:string;children:ReactNode}){ + const element=useRef(null); + useLayoutEffect(()=>{if(traceId)recordArtifactCommit(traceId,callId,element.current);},[traceId,callId,children]); + return { + if(traceId)recordArtifactCommit(traceId,callId,element.current,actualDuration); + }}>
{children}
; +} diff --git a/frontend/src/components/activity/trace-studio.module.css b/frontend/src/components/activity/trace-studio.module.css new file mode 100644 index 0000000..1da8c1d --- /dev/null +++ b/frontend/src/components/activity/trace-studio.module.css @@ -0,0 +1,103 @@ +.studio{--trace-blue:var(--data-accent);--trace-purple:#8052b9;--trace-green:var(--tool-completed);--trace-red:var(--tool-error);--font-size-base:14px;--font-sans:var(--font-geist-sans,Arial,sans-serif);--background:var(--surface-primary);--foreground:var(--text-primary);--muted-foreground:var(--text-tertiary);--border:var(--border-subtle);--border-strong:var(--border-default);--input:var(--border-default);--secondary:var(--surface-secondary);--primary:var(--text-primary);--popover:var(--surface-primary);--popover-foreground:var(--text-primary);--destructive:var(--trace-red);--orange:#af6a14;--ring:var(--data-accent);--radius-md:7px;--radius-lg:10px;--btn-size:32px;--cursor-interaction:pointer;--viz-series-1:var(--trace-blue);--viz-series-2:var(--orange);--viz-series-3:var(--trace-green);--viz-series-4:#bd6591;--viz-series-5:var(--trace-purple);--viz-series-6:#209d97;container:trace / inline-size;display:flex;flex-direction:column;height:100%;min-height:0;min-width:0;background:var(--surface-primary);color:var(--text-primary);font-size:14px} +.studio button,.studio select{font:inherit;font-size:12px;cursor:pointer} +.studio button{display:inline-flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--border-subtle);border-radius:7px;padding:6px 9px;background:var(--surface-primary);color:var(--text-secondary);white-space:nowrap} +.studio button:hover{background:var(--surface-secondary)} +.studio button[data-active=true]{color:var(--data-accent);background:var(--data-accent-soft);border-color:transparent} +.studio button svg{width:15px;height:15px;flex-shrink:0} +.heading{display:flex;flex-shrink:0;justify-content:space-between;align-items:flex-start;gap:10px;padding:18px 16px 12px} +.heading h2{margin:0;font-size:20px;font-weight:600;line-height:1.3} +.heading p{margin:4px 0 0;font-size:12px;color:var(--text-tertiary)} +.actions{display:flex;align-items:center;gap:5px;flex-wrap:wrap} +.state{font-size:11px;white-space:nowrap;color:var(--trace-green)} +.tabs{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:6px;padding:0 16px 12px;flex-shrink:0;border-bottom:1px solid var(--border-subtle)} +.tabgroup{display:flex;gap:2px;padding:3px;background:var(--surface-secondary);border-radius:8px} +.tabgroup button{border:0;padding:6px 8px;background:transparent} +.tabgroup button[data-active=true]{background:var(--surface-primary);box-shadow:0 1px 3px #0000000a} +.metrics{display:flex;flex-shrink:0;gap:8px 18px;align-items:center;flex-wrap:wrap;padding:10px 16px;background:var(--surface-secondary);border-bottom:1px solid var(--border-subtle);font-size:11px;color:var(--text-tertiary)} +.metrics span{display:flex;gap:7px;white-space:nowrap} +.metrics b{font-weight:500;color:var(--text-primary);font-variant-numeric:tabular-nums} +.metrics .infoButton{margin-left:auto;padding:1px 0;background:transparent;border:0;font-size:11px} +.clockHelp{flex-shrink:0;max-height:180px;overflow:auto;padding:12px 16px;background:var(--data-accent-soft);font-size:12px;line-height:1.8} +.body{flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr)} +.body.withDetail{grid-template-rows:minmax(0,1fr) minmax(0,1fr)} +.views{min-width:0;min-height:0;display:flex;flex-direction:column;overflow:hidden} +.view{flex:1;min-height:0;min-width:0;overflow:auto;padding:14px 16px;scrollbar-gutter:stable} +.view[hidden]{display:none} +.nodeView{padding:0;overflow:hidden} +.toolsSummary{font-size:12px;color:var(--text-tertiary);margin-bottom:12px} +.toolList{display:flex;flex-direction:column;gap:11px} +.empty{padding:50px 14px;text-align:center;font-size:12px;color:var(--text-tertiary);line-height:1.8} +.footer{flex-shrink:0;padding:8px 14px;border-top:1px solid var(--border-subtle);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:5px;font-size:10px;color:var(--text-tertiary)} +.footer span{display:inline-flex;align-items:center;gap:5px;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.footer svg{width:12px;height:12px} +.inspector{min-height:0;overflow:auto;border-top:1px solid var(--border-subtle);background:var(--surface-primary);font-size:12px;scrollbar-gutter:stable} +.detailHead{display:flex;justify-content:space-between;gap:8px;align-items:flex-start;padding:14px 14px 5px} +.detailHead strong{font-size:13px;font-weight:500;overflow-wrap:anywhere} +.detailHead button{border:0;padding:0 2px} +.detailKind{padding:0 14px 10px;font-size:10px;color:var(--text-tertiary);overflow-wrap:anywhere} +.detailTabs{display:flex;border-bottom:1px solid var(--border-subtle);padding:0 8px;gap:2px} +.detailTabs button{border:0;border-radius:0;padding:8px} +.detailTabs button[data-active=true]{background:transparent;border-bottom:2px solid var(--data-accent)} +.detailBody{padding:12px 14px;overflow-wrap:anywhere} +.detailBody dl{margin:0;display:grid;grid-template-columns:72px minmax(0,1fr);gap:9px} +.detailBody dt{color:var(--text-tertiary)} +.detailBody dd{margin:0;font-variant-numeric:tabular-nums} +.detailBody dd[data-status=running]{color:var(--trace-blue)} +.detailBody dd[data-status=error]{color:var(--trace-red)} +.detailBody h3{font-size:12px;font-weight:500;margin:18px 0 8px} +.detailBody pre{margin:6px 0 10px;padding:10px;background:var(--surface-secondary);border-radius:6px;max-height:260px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;font:11px/1.7 Consolas,monospace} +.studio .phase{display:flex;width:100%;justify-content:space-between;gap:12px;border:0;border-bottom:1px solid var(--border-subtle);border-radius:0;background:transparent;text-align:left;font-size:11px;padding:9px 0;white-space:normal} +.phase span:last-child{white-space:nowrap;color:var(--text-tertiary);font-variant-numeric:tabular-nums} +.muted{color:var(--text-tertiary);font-size:12px} +.evidence{background:var(--data-accent-soft);padding:10px;border-radius:6px;font-size:11px;line-height:1.8;margin-top:14px;color:var(--text-secondary)} +.event{padding:9px 0;border-bottom:1px solid var(--border-subtle);font-size:11px;line-height:1.7} +.detailActions{display:flex;gap:6px;flex-wrap:wrap;padding:0 14px 14px} +.detailActions button{font-size:11px} +.sourceLink{font-size:11px;padding:6px 10px;border:1px solid var(--trace-line);border-radius:7px;color:var(--trace-blue)} +.graph{height:100%;display:flex;flex-direction:column;min-height:0} +.graphToolbar{padding:10px 12px;display:flex;justify-content:space-between;align-items:center;gap:6px;flex-wrap:wrap;border-bottom:1px solid var(--border-subtle);flex-shrink:0} +.graphToolbar select{padding:5px 7px;max-width:195px;min-width:0;border:1px solid var(--border-subtle);background:var(--surface-primary);border-radius:6px;color:var(--text-secondary)} +.graphStage{position:relative;flex:1;min-height:150px;overflow:hidden;touch-action:none} +.graphSvg{width:100%;height:100%;display:block;cursor:grab} +.graphSvg:active{cursor:grabbing} +.graphNode{cursor:pointer} +.graphNode:focus{outline:none} +.graphFocusRing{opacity:0;pointer-events:none} +.graphNode:focus-visible .graphFocusRing{opacity:1} +.graphLabel{fill:var(--text-primary);font-family:inherit} +.graphDuration{fill:var(--text-tertiary);font-family:inherit} +.edge,.retryEdge{stroke:var(--border-default);stroke-width:1.5;fill:none} +.retryEdge{stroke:var(--orange);stroke-dasharray:5 4} +.studio .minimap{position:absolute;right:12px;top:12px;width:78px;height:140px;padding:4px;background:var(--surface-secondary);overflow:hidden;border:1px solid var(--border-subtle);border-radius:7px;opacity:.95} +.minimap svg{width:100%;height:100%} +.legend{font-size:10px;display:flex;flex-wrap:wrap;gap:8px 14px;padding:10px 12px;border-top:1px solid var(--border-subtle);color:var(--text-tertiary);flex-shrink:0} +@container trace (min-width:800px){.body.withDetail{grid-template-columns:minmax(0,1fr) 290px;grid-template-rows:minmax(0,1fr)}.inspector{border-top:0;border-left:1px solid var(--border-subtle)}} +@container trace (max-width:440px){.heading{padding:14px 12px 10px}.heading p{max-width:170px}.heading .state{display:none}.tabs{padding:0 12px 10px}.tabgroup button{padding:7px 6px;font-size:11px}.metrics{padding:10px 12px;gap:8px 12px}.graphToolbar select{max-width:150px}.view:has(viz-waterfall){overflow:auto}.view viz-waterfall{min-width:620px}} + +:global(.dark) .studio{--trace-purple:#c09be8;--orange:#efba65;--viz-series-4:#eb9ec8;--viz-series-6:#67cfc9} +.studio{--trace-bg:#fff;--trace-soft:#f7f8fa;--trace-hover:#edf0f5;--trace-ink:#202b3d;--trace-muted:#68768c;--trace-line:#e5e9f0;--trace-tint:#edf4ff;--trace-blue:#2269e9;--trace-green:#09866c;--trace-red:#db354a;--trace-purple:#8052b9;--surface-primary:var(--trace-bg);--surface-secondary:var(--trace-soft);--surface-tertiary:var(--trace-hover);--text-primary:var(--trace-ink);--text-secondary:var(--trace-ink);--text-tertiary:var(--trace-muted);--text-quaternary:var(--trace-muted);--border-subtle:var(--trace-line);--border-default:var(--trace-line);--data-accent:var(--trace-blue);--data-accent-soft:var(--trace-tint);--tool-completed:var(--trace-green);--tool-error:var(--trace-red);font:14px/1.5 "Segoe UI","Microsoft YaHei",sans-serif} +:global(.dark) .studio{--trace-bg:#171717;--trace-soft:#202022;--trace-hover:#292a2e;--trace-ink:#eeeeef;--trace-muted:#a3aab8;--trace-line:#34363b;--trace-tint:#22324c;--trace-blue:#78a8ff;--trace-green:#58d2b0;--trace-red:#ff8091;--trace-purple:#c09be8;--orange:#efba65} +.studio button{padding:6px 10px} +.heading{padding:18px 18px 10px} +.tabs{padding:0 18px 12px} +.tabgroup button{padding:6px 9px} +.metrics{padding:10px 18px;gap:8px 22px;font-size:12px} +.view{padding:14px 18px} +.nodeView{padding:0} +.state{padding:3px 6px;border-radius:5px;background:var(--trace-soft)} +.detailBody dd[data-status=ok]{color:var(--trace-green)} +.detailBody dd[data-status=cancelled]{color:var(--trace-muted)} +.detailBody dd[data-status=incomplete]{color:var(--orange)} +.studio .minimap{width:84px;height:152px;padding:0} +.legend{font-size:11px;padding:10px 14px} +.detailKind{font-size:11px} +.footer{padding:9px 18px;font-size:11px} +.replayToolbar{padding:10px 18px;border-bottom:1px solid var(--trace-line);background:var(--trace-soft);flex-shrink:0} +.replayActions{display:flex;align-items:center;gap:6px;flex-wrap:wrap} +.replayActions label{font-size:12px;color:var(--trace-muted);display:flex;align-items:center;gap:5px} +.replayActions select{font:inherit;border:1px solid var(--trace-line);border-radius:6px;background:var(--trace-bg);padding:5px;color:var(--trace-ink)} +.replayTrack{display:flex;align-items:center;gap:10px;margin-top:9px} +.replayTrack input{flex:1;min-width:80px;accent-color:var(--trace-blue)} +.replayTrack span{font-size:11px;font-variant-numeric:tabular-nums;white-space:nowrap} +.replayToolbar p{margin:5px 0 0;color:var(--trace-muted);font-size:11px} +@container trace (max-width:440px){.heading{padding:14px 12px 10px}.tabs{padding:0 12px 10px}.metrics{padding:10px 12px;gap:8px 12px}.view{padding:12px}.nodeView{padding:0}.replayToolbar{padding:10px 12px}} diff --git a/frontend/src/components/activity/trace-waterfall.tsx b/frontend/src/components/activity/trace-waterfall.tsx new file mode 100644 index 0000000..c18973a --- /dev/null +++ b/frontend/src/components/activity/trace-waterfall.tsx @@ -0,0 +1,168 @@ +"use client"; + +import { memo,useEffect, useRef, useState, type MutableRefObject } from 'react'; +import type { TraceSpan } from '@/types/execution-trace'; +import {saveTraceViewState} from '@/lib/trace-view-state'; +import {defaultCollapsedCalls,expandSpanAncestors} from '@/lib/trace-waterfall-state'; + +type ViewState = Record; +interface WaterfallElement extends HTMLElement { + spans: unknown[]; + durationMs: number; + viewState: ViewState; + ready: Promise; +} +let loading: Promise | undefined; +function loadViewer() { + if (customElements.get('viz-waterfall')) return Promise.resolve(); + if (!loading) loading = new Promise((resolve, reject) => { + const script = document.createElement('script'); + script.type = 'module'; script.src = '/vendor/1.0.59/request-waterfall.js'; + script.onload = () => { customElements.whenDefined('viz-waterfall').then(() => resolve()); }; + script.onerror = () => { loading = undefined; script.remove(); reject(new Error('瀑布组件加载失败')); }; + document.head.append(script); + }); + return loading; +} + +export const TraceWaterfall=memo(function TraceWaterfall({ cacheKey,spans, active, selectedId, onSelect, follow, onPauseFollow, savedView, locateVersion = 0 }: { + cacheKey:string; + spans: TraceSpan[]; active: boolean; selectedId: string | null; onSelect: (id: string) => void; + follow: boolean; onPauseFollow: () => void; savedView: MutableRefObject; + locateVersion?: number; +}) { + const host = useRef(null), viewer = useRef(null); + const [loaded, setLoaded] = useState(false), [error, setError] = useState(''); + const callbacks = useRef({ onSelect, onPauseFollow, selectedId }); callbacks.current = { onSelect, onPauseFollow, selectedId }; + const latest=useRef({selectedId,follow,spans,active});latest.current={selectedId,follow,spans,active}; + const syncing = useRef(false), version = useRef(0), lastLocate = useRef(0); + const restored=useRef(false); + const knownCallGroups=useRef(new Set()); + const interacting=useRef(false),appliedSpans=useRef(null); + const nativeSelection=useRef(null); + const [interactionVersion,setInteractionVersion]=useState(0); + useEffect(() => { + let disposed = false; + const knownGroups=knownCallGroups.current; + let removeGestureBridge:(()=>void)|undefined; + loadViewer().then(() => { + if (disposed || !host.current) return; + const el = document.createElement('viz-waterfall') as WaterfallElement; + el.id = 'codata-request-waterfall'; + el.setAttribute('title', '调用性能'); + el.setAttribute('description', '真实采集 · 服务端单调时钟;跨端对齐误差见节点详情'); + el.addEventListener('viz-state-change', event => { + const detail = (event as CustomEvent<{state: ViewState; selection?: {spanId: string}}>).detail; + const selected=detail.selection?.spanId??null; + const changed=selected!==nativeSelection.current;nativeSelection.current=selected; + if (syncing.current) return; + savedView.current = { ...detail.state, details: false }; + saveTraceViewState(cacheKey,{waterfall:savedView.current}); + if (selected&&(changed||detail.state.details===true)&&selected!==callbacks.current.selectedId)callbacks.current.onSelect(selected); + if (detail.state.details) { + syncing.current = true; el.viewState = { ...el.viewState, details: false }; syncing.current = false; + } + }); + el.addEventListener('pointerdown', () => callbacks.current.onPauseFollow()); + el.addEventListener('wheel', () => callbacks.current.onPauseFollow(), { passive: true }); + el.addEventListener('viz-error', event => setError((event as CustomEvent).detail.message)); + // Opening the shared inspector changes the track width after the first + // click. Keep a genuine double-click anchored to its FIRST span even if + // the second pointer lands in the newly opened inspector. Focus still + // uses the original viewer's dblclick algorithm, not a replacement. + let firstClick:{id:string;x:number;y:number;at:number}|null=null; + let suppressNativeUntil=0; + let releaseFrame=0; + const releasePointer=()=>{if(!interacting.current)return;cancelAnimationFrame(releaseFrame);releaseFrame=requestAnimationFrame(()=>{interacting.current=false;setInteractionVersion(n=>n+1);});}; + const beginPointer=()=>{cancelAnimationFrame(releaseFrame);interacting.current=true;}; + const abortPointer=()=>{if(interacting.current){cancelAnimationFrame(releaseFrame);interacting.current=false;setInteractionVersion(n=>n+1);}}; + const clearClick=()=>{firstClick=null;}; + const clickCapture=(event:MouseEvent)=>{ + if(!latest.current.active||event.detail===0)return; + const now=performance.now(); + if(firstClick&&now-firstClick.at<500&&Math.hypot(event.clientX-firstClick.x,event.clientY-firstClick.y)<5){ + const rows=el.shadowRoot?.querySelectorAll('[data-span-id]'); + const row=rows&&Array.from(rows).find(item=>item.dataset.spanId===firstClick!.id); + if(row){ + event.preventDefault();event.stopImmediatePropagation();suppressNativeUntil=now+100; + row.dispatchEvent(new MouseEvent('dblclick',{bubbles:true,composed:true,detail:2,clientX:event.clientX,clientY:event.clientY})); + } + firstClick=null;return; + } + const path=event.composedPath(); + const disclosure=path.some(item=>item instanceof Element&&item.classList.contains('wf-disclosure')); + const row=path.find(item=>item instanceof Element&&item.hasAttribute('data-span-id')) as HTMLElement|undefined; + firstClick=!disclosure&&row&&el.shadowRoot?.contains(row)?{id:row.dataset.spanId!,x:event.clientX,y:event.clientY,at:now}:null; + }; + const doubleCapture=(event:MouseEvent)=>{if(event.isTrusted&&performance.now(){cancelAnimationFrame(releaseFrame);interacting.current=false;el.ownerDocument.removeEventListener('click',clickCapture,true);el.ownerDocument.removeEventListener('dblclick',doubleCapture,true);el.ownerDocument.removeEventListener('pointerup',releasePointer,true);el.ownerDocument.removeEventListener('pointercancel',releasePointer,true);el.ownerDocument.removeEventListener('wheel',clearClick,true);el.ownerDocument.defaultView?.removeEventListener('blur',abortPointer);}; + host.current.append(el); viewer.current = el; setError(''); setLoaded(true); + }).catch(e => { if (!disposed) setError(String(e)); }); + return () => { disposed = true;removeGestureBridge?.();viewer.current?.remove(); viewer.current = null;restored.current=false;knownGroups.clear();appliedSpans.current=null; }; + }, [savedView,cacheKey]); + + useEffect(() => { + const el = viewer.current; + if (!el || !loaded || !active||interacting.current||appliedSpans.current===spans) return; + appliedSpans.current=spans; + const update = ++version.current; + const duration = Math.max(1, ...spans.map(s => s.startMs + s.durationMs)); + syncing.current=true; + el.spans = spans.map(s => ({ ...s, + name: s.name + (s.status === 'running' ? ' · 执行中' : s.status === 'cancelled' ? ' · 已取消' : ''), + status: s.status === 'error' ? 'error' : s.status === 'incomplete' || s.status === 'cancelled' ? 'warning' : 'ok', + attributes: Object.fromEntries(Object.entries(s.attributes).map(([k,v]) => [k, typeof v === 'object' ? JSON.stringify(v) : v ?? '未采集'])), + })); + el.durationMs = duration; + void el.ready.then(async () => { + if (update !== version.current) return; + const state={...el.viewState,...(!restored.current?savedView.current:{})}; + const collapsed=defaultCollapsedCalls(spans,Array.isArray(state.collapsed)?state.collapsed:[],knownCallGroups.current, + !restored.current&&Array.isArray(savedView.current.collapsed)); + el.viewState = { ...state, collapsed, selectedSpanId: latest.current.selectedId, details: false, + ...(latest.current.follow ? { startMs: 0, endMs: duration } : {}) }; + restored.current=true; + savedView.current={...el.viewState,details:false}; + saveTraceViewState(cacheKey,{waterfall:savedView.current}); + syncing.current = false; + }); + }, [spans, active, loaded, savedView,interactionVersion,cacheKey]); + useEffect(()=>{ + const el=viewer.current;if(!el||!active||!loaded)return; + void el.ready.then(()=>{ + if(viewer.current!==el||!latest.current.active)return; + if(el.viewState.selectedSpanId!==latest.current.selectedId){syncing.current=true;el.viewState={...el.viewState,selectedSpanId:latest.current.selectedId,details:false};syncing.current=false;} + }); + },[selectedId,active,loaded]); + useEffect(()=>{ + const el=viewer.current;if(!el||!active||!loaded||!follow)return; + void el.ready.then(()=>{ + if(viewer.current!==el||!latest.current.follow)return; + const duration=Math.max(1,...latest.current.spans.map(s=>s.startMs+s.durationMs)); + syncing.current=true;el.viewState={...el.viewState,startMs:0,endMs:duration,details:false};syncing.current=false; + }); + },[follow,active,loaded]); + useEffect(()=>{ + const el=viewer.current;if(!el||!active||!loaded||locateVersion===lastLocate.current)return; + lastLocate.current=locateVersion; + void el.ready.then(async()=>{ + const state=el.viewState; + const collapsed=expandSpanAncestors(latest.current.spans,Array.isArray(state.collapsed)?state.collapsed:[],latest.current.selectedId); + syncing.current=true;el.viewState={...state,selectedSpanId:latest.current.selectedId,details:false,query:'',collapsed};syncing.current=false; + savedView.current={...el.viewState,details:false};saveTraceViewState(cacheKey,{waterfall:savedView.current}); + await el.ready; + const rows=el.shadowRoot?.querySelectorAll('[data-span-id]'); + const row=rows&&Array.from(rows).find(r=>r.dataset.spanId===latest.current.selectedId); + const panel=host.current?.parentElement; + if(row&&panel)panel.scrollTop+=row.getBoundingClientRect().top-panel.getBoundingClientRect().top-60; + }); + },[locateVersion,active,loaded,savedView,cacheKey]); + return
{error &&
{error}
}
; +}); diff --git a/frontend/src/components/messages/assistant-message-group.tsx b/frontend/src/components/messages/assistant-message-group.tsx index 4ba4c51..d780f2b 100644 --- a/frontend/src/components/messages/assistant-message-group.tsx +++ b/frontend/src/components/messages/assistant-message-group.tsx @@ -25,13 +25,19 @@ export const AssistantMessageGroup = memo(function AssistantMessageGroup({ messa ), [messages], ); + const representative = useMemo(() => { + const first = messages[0]; + const traceOwner = messages.findLast(m => m.data.role === 'assistant' && m.data.execution_trace); + if (!traceOwner || traceOwner.data.role !== 'assistant') return first; + return { ...first, data: { ...first.data, trace_id: traceOwner.data.trace_id, execution_trace: traceOwner.data.execution_trace } }; + }, [messages]); // Use the first message as the "representative" for the group return (
diff --git a/frontend/src/components/messages/assistant-message.tsx b/frontend/src/components/messages/assistant-message.tsx index fb2abd2..918e4b5 100644 --- a/frontend/src/components/messages/assistant-message.tsx +++ b/frontend/src/components/messages/assistant-message.tsx @@ -1,6 +1,8 @@ "use client"; -import { useState, useMemo, memo, useEffect, useRef } from "react"; +import { useState, useMemo, memo, useEffect, useLayoutEffect } from "react"; +import { recordTextCommit } from '@/lib/execution-trace'; +import { useExecutionTraceStore } from '@/stores/execution-trace-store'; import { useTranslation } from "react-i18next"; import { motion } from "framer-motion"; import { MessageContent } from "./message-content"; @@ -96,7 +98,7 @@ export function AssistantMessage({ message, combinedParts, onRegenerate, isNew = ); const hasExpertSteps = stepParts.some((part) => part.snapshot?.mode === "expert-team"); - if (reasoningTexts.length === 0 && toolParts.length === 0 && !hasExpertSteps) return null; + if (reasoningTexts.length === 0 && toolParts.length === 0 && !hasExpertSteps && !(message.data.role==='assistant'&&message.data.trace_id)) return null; const chain: ChainItem[] = []; for (const p of mainParts) { @@ -107,6 +109,9 @@ export function AssistantMessage({ message, combinedParts, onRegenerate, isNew = const data: ActivityData = { sourceKey: activityKey, + sessionId: message.session_id, + traceId: message.data.role === 'assistant' ? message.data.trace_id : undefined, + executionTrace: message.data.role === 'assistant' ? message.data.execution_trace : undefined, mode: hasExpertSteps ? "expert-team" : "default", parts: mainParts, reasoningTexts: [...reasoningTexts, ...traceTexts], @@ -127,7 +132,7 @@ export function AssistantMessage({ message, combinedParts, onRegenerate, isNew = }; data.thinkingDuration = computeDuration(data); return data; - }, [activityKey, mainParts, persistedDurationMs]); + }, [activityKey, mainParts, persistedDurationMs, message.session_id, message.data]); useEffect(() => { if (activityData) { @@ -153,6 +158,7 @@ export function AssistantMessage({ message, combinedParts, onRegenerate, isNew = > @@ -214,6 +220,7 @@ export function AssistantMessage({ message, combinedParts, onRegenerate, isNew = > @@ -255,11 +262,11 @@ interface StreamingMessageProps { export const StreamingMessage = memo(function StreamingMessage({ sessionId = null, parts, streamingText, streamingReasoning }: StreamingMessageProps) { const { t } = useTranslation("chat"); - const { isModelLoading, generationStartedAt, generationDurationSeconds } = useChatSession(sessionId); + const { isGenerating, isModelLoading, generationStartedAt, generationDurationSeconds, streamId } = useChatSession(sessionId); + const storedTraceId=useExecutionTraceStore(s=>sessionId?s.activeBySession[sessionId]:undefined); + const traceId=streamId??storedTraceId; const isCodata = useSidebarStore((s) => s.appMode) === "codata"; const refreshForMessage = useActivityStore((s) => s.refreshForMessage); - const openForMessage = useActivityStore((s) => s.openForMessage); - const autoOpenedExpertPanelRef = useRef(false); // Stabilize liveParts reference — without useMemo, a new array is created // on every render, breaking downstream useMemo dependencies in MessageContent. @@ -276,7 +283,7 @@ export const StreamingMessage = memo(function StreamingMessage({ sessionId = nul p.type === "step-start" || p.type === "step-finish", ); const hasExpertSteps = stepParts.some((part) => part.snapshot?.mode === "expert-team"); - if (!hasExpertSteps || !sessionId) return null; + if (!sessionId || (!hasExpertSteps&&!traceId)) return null; const reasoningTexts = liveParts .filter((p): p is PartData & { type: "reasoning" } => p.type === "reasoning") @@ -288,8 +295,9 @@ export const StreamingMessage = memo(function StreamingMessage({ sessionId = nul else if (p.type === "tool") chain.push({ type: "tool", data: p }); } const data: ActivityData = { - sourceKey: `expert:${sessionId}`, - mode: "expert-team", + sourceKey: hasExpertSteps ? `expert:${sessionId}` : `trace:${traceId}`, + mode: hasExpertSteps ? 'expert-team' : 'default', + sessionId, traceId, parts: liveParts, reasoningTexts, toolParts, @@ -301,20 +309,20 @@ export const StreamingMessage = memo(function StreamingMessage({ sessionId = nul }; data.thinkingDuration = computeDuration(data); return data; - }, [liveParts, sessionId]); + }, [liveParts, sessionId, traceId]); + + useLayoutEffect(() => { + if (sessionId) recordTextCommit(sessionId, !!streamingText); + }, [sessionId, streamingText]); useEffect(() => { if (!streamingActivityData?.sourceKey) return; - if (!autoOpenedExpertPanelRef.current) { - openForMessage(streamingActivityData.sourceKey, streamingActivityData); - autoOpenedExpertPanelRef.current = true; - } else { - refreshForMessage(streamingActivityData.sourceKey, streamingActivityData); - } - }, [openForMessage, refreshForMessage, streamingActivityData]); + refreshForMessage(streamingActivityData.sourceKey, streamingActivityData); + }, [refreshForMessage, streamingActivityData]); // No content yet — show blinking cursor to indicate "about to type" if (liveParts.length === 0) { + if (!isGenerating) return ; if (isCodata) { return (
@@ -355,7 +363,7 @@ export const StreamingMessage = memo(function StreamingMessage({ sessionId = nul const isGenerationDone = !!lastStepFinish && lastStepFinish.reason !== "tool_use"; // The stage line already communicates the waiting state. Only show the // trailing dot row when there is actual reasoning/tool activity above it. - const showTail = hasAnyActivity && !isActivelyStreaming && !hasRunningTool && !isGenerationDone; + const showTail = isGenerating && hasAnyActivity && !isActivelyStreaming && !hasRunningTool && !isGenerationDone; let stageLabel = t("stageThinking"); if (hasRunningTool) stageLabel = t("stageWorkingWithTools"); @@ -363,10 +371,11 @@ export const StreamingMessage = memo(function StreamingMessage({ sessionId = nul const streamingBody = (
- {!hasAnyActivity && } + {isGenerating&&!hasAnyActivity && }
Codata - 正在分析 + {isGenerating&&正在分析}
{streamingBody}
diff --git a/frontend/src/components/messages/message-content.tsx b/frontend/src/components/messages/message-content.tsx index a871530..f7d7ce2 100644 --- a/frontend/src/components/messages/message-content.tsx +++ b/frontend/src/components/messages/message-content.tsx @@ -20,7 +20,12 @@ import { hasCodataResult, isTraceOnlyCodataResult } from "@/lib/codata-artifact" import { cn } from "@/lib/utils"; import type { ActivityData, ChainItem } from "@/stores/activity-store"; +import { TraceRenderProbe } from '@/components/activity/trace-render-probe'; + interface MessageContentProps { + traceId?: string; + sessionId?: string; + executionTrace?: import('@/types/execution-trace').ExecutionTrace; parts: PartData[]; /** Whether this is the currently streaming message. */ isStreaming?: boolean; @@ -142,6 +147,7 @@ export function MessageContent({ isStreaming, activityKey, totalDuration, + traceId, sessionId, executionTrace, }: MessageContentProps) { // Thinking duration reported by ReasoningPart's live timer const [thinkingDuration, setThinkingDuration] = useState(); @@ -190,7 +196,7 @@ export function MessageContent({ const hasReasoning = reasoningTexts.length > 0; const hasTools = toolParts.length > 0; const hasExpertSteps = stepParts.some((part) => part.snapshot?.mode === "expert-team"); - const hasActivity = hasReasoning || hasTools || hasExpertSteps; + const hasActivity = hasReasoning || hasTools || hasExpertSteps || !!traceId; const presentedFilePaths = useMemo(() => { const paths = new Set(); @@ -238,6 +244,7 @@ export function MessageContent({ hasActivity ? { sourceKey: activityKey, + traceId, sessionId, executionTrace, mode: hasExpertSteps ? "expert-team" : "default", parts, reasoningTexts: [...reasoningTexts, ...traceTexts], @@ -258,7 +265,7 @@ export function MessageContent({ chain, } : null, - [hasActivity, hasExpertSteps, reasoningTexts, traceTexts, toolParts, thinkingDuration, totalDuration, stepParts, chain, parts, activityKey], + [hasActivity, hasExpertSteps, reasoningTexts, traceTexts, toolParts, thinkingDuration, totalDuration, stepParts, chain, parts, activityKey, traceId, sessionId, executionTrace], ); // Content parts: text, subtask, and deliverable tool calls (shown as inline cards) @@ -483,11 +490,13 @@ export function MessageContent({ return ( {foldCards && } - + + + ); } diff --git a/frontend/src/components/messages/message-list.tsx b/frontend/src/components/messages/message-list.tsx index 0a64ad1..b604d68 100644 --- a/frontend/src/components/messages/message-list.tsx +++ b/frontend/src/components/messages/message-list.tsx @@ -60,7 +60,7 @@ export function MessageList({ fetchPreviousPage, }: MessageListProps) { const { scrollRef, scrollElementRef, bottomRef, isAtBottom, scrollToBottom } = useScrollAnchor(); - const openForMessage = useActivityStore((s) => s.openForMessage); + const refreshForMessage = useActivityStore((s) => s.refreshForMessage); const topSentinelRef = useRef(null); const restoredExpertActivityKeyRef = useRef(null); // IDs whose content was already visible in StreamingMessage. These must not @@ -203,10 +203,10 @@ export function MessageList({ if (!key || restoredExpertActivityKeyRef.current === key) return; const frame = requestAnimationFrame(() => { restoredExpertActivityKeyRef.current = key; - openForMessage(key, historicalExpertActivity); + refreshForMessage(key, historicalExpertActivity); }); return () => cancelAnimationFrame(frame); - }, [historicalExpertActivity, openForMessage]); + }, [historicalExpertActivity, refreshForMessage]); // The shell message only exists after the backend created it (streamId is set). // During beginSending (streamId is null), we must NOT hide the previous response. diff --git a/frontend/src/hooks/use-chat.ts b/frontend/src/hooks/use-chat.ts index d60877c..7c4cf25 100644 --- a/frontend/src/hooks/use-chat.ts +++ b/frontend/src/hooks/use-chat.ts @@ -1,4 +1,5 @@ "use client"; +import { beginClientTrace, cancelClientTrace } from '@/lib/execution-trace'; import { useCallback } from "react"; import { useRouter } from "next/navigation"; @@ -24,6 +25,7 @@ import type { InfiniteData } from "@tanstack/react-query"; import type { FileAttachment, PromptResponse, RespondRequest } from "@/types/chat"; import type { PaginatedMessages } from "@/types/message"; import type { SessionResponse } from "@/types/session"; +import type { ExecutionTrace } from '@/types/execution-trace'; export interface SendMessageOptions { skills?: string[]; @@ -152,6 +154,8 @@ export function useChat(currentSessionId?: string) { } closeResponsePanels(); + const traceStartedPerf = performance.now(); + const traceStartedEpoch = performance.timeOrigin + traceStartedPerf; chatState.beginSending(targetSessionId, text.trim(), attachments); try { @@ -201,6 +205,7 @@ export function useChat(currentSessionId?: string) { }); chatState.startGeneration(res.session_id, res.stream_id); + beginClientTrace(res.session_id, res.stream_id, traceStartedPerf, traceStartedEpoch); if (selectedExpertTeam && !currentSessionId) { const expertStore = useExpertSessionStore.getState(); expertStore.setSelectedExpertTeam(res.session_id, selectedExpertTeam); @@ -241,9 +246,12 @@ export function useChat(currentSessionId?: string) { const streamId = bucket?.streamId; if (!streamId) return; try { - await api.post(API.CHAT.ABORT, { stream_id: streamId }); + const result=await api.post<{status:string;execution_trace?:ExecutionTrace}>(API.CHAT.ABORT, { stream_id: streamId }); + if (targetSessionId!==null) cancelClientTrace(targetSessionId,streamId,result.execution_trace,result.status==='not_found'); } catch (err) { console.error("Failed to abort — backend may still be generating:", err); + toast.error('终止失败,请重试'); + return; } if (targetSessionId !== null) stopStream(targetSessionId); chatState.finishGeneration(targetSessionId); diff --git a/frontend/src/lib/execution-trace.ts b/frontend/src/lib/execution-trace.ts new file mode 100644 index 0000000..11f3746 --- /dev/null +++ b/frontend/src/lib/execution-trace.ts @@ -0,0 +1,209 @@ +"use client"; + +import { api } from "@/lib/api"; +import { useExecutionTraceStore } from "@/stores/execution-trace-store"; +import type { ExecutionTrace, LiveTrace, TraceSpan, TraceTiming } from "@/types/execution-trace"; +import type { SSEEventData } from "@/types/streaming"; +import {traceViewSpans} from './trace-view-spans'; + +const store = useExecutionTraceStore; +const calibrations = new Map>(); +const finalizing = new Set(); + +export function beginClientTrace(sessionId: string, traceId: string, startedPerf: number, startedEpoch: number) { + store.getState().ensure(sessionId, traceId); + store.getState().patch(traceId, { clientStartPerfMs: startedPerf, clientStartEpochMs: startedEpoch }); +} + +/** Abort acknowledgements must close the trace before the SSE stream is torn down. */ +export function cancelClientTrace(sessionId: string, traceId: string, snapshot?: ExecutionTrace, missing = false) { + if (snapshot?.trace_id === traceId && snapshot.completed) { + store.getState().hydrate(sessionId, snapshot); + return; + } + const current=store.getState().traces[traceId]; + if (!current || current.completed) return; + const now=performance.now(); + const elapsed=Math.max(current.duration_ms,(current.receivedServerMs??0)+Math.max(0,now-(current.receivedPerfMs??now))); + store.getState().patch(traceId,{completed:true,duration_ms:elapsed, + spans:current.spans.map(span=>span.status==='running'?{...span,status:missing?'incomplete':'cancelled', + durationMs:Math.max(span.durationMs,elapsed-span.startMs),attributes:{...span.attributes, + cancel_boundary:missing?'server job no longer exists':'browser received abort acknowledgement; server boundary unavailable'}}:span), + metrics:{...current.metrics,...(current.clientStartPerfMs===undefined?{}:{end_to_end_ms:Math.max(0,now-current.clientStartPerfMs)})}, + }); +} + +export function calibrateTrace(traceId: string): Promise { + const existing = calibrations.get(traceId); if (existing) return existing; + const task = (async () => { + let best = Infinity; + for (let i = 0; i < 3; i++) { + try { + const start = performance.now(), epoch = performance.timeOrigin + start; + const result = await api.get<{server_epoch_ms: number}>("/api/chat/clock", { timeoutMs: 3000 }); + const rtt = performance.now() - start; + if (rtt < best) { + best = rtt; + store.getState().patch(traceId, { offsetMs: result.server_epoch_ms - (epoch + rtt / 2), uncertaintyMs: rtt / 2 }); + } + } catch { /* Uncalibrated clocks remain explicitly unavailable. */ } + } + })(); + calibrations.set(traceId, task); + if (calibrations.size > 50) calibrations.delete(calibrations.keys().next().value!); + return task; +} + +function addClientSpan(traceId: string, span: TraceSpan) { + const t = store.getState().traces[traceId]; if (!t) return; + const items = t.clientSpans.filter(s => s.id !== span.id); + store.getState().patch(traceId, { clientSpans: [...items.slice(-198), span] }); +} + +export function ingestTraceSpan(sessionId: string, traceId: string, data: SSEEventData) { + store.getState().ensure(sessionId, traceId); + const payload = data as SSEEventData & { span?: TraceSpan; origin_epoch_ms?: number; elapsed_ms?: number }; + const current=store.getState().traces[traceId]; + if(current.completed)return; + if (payload.span && Number.isFinite(payload.span.startMs)) store.getState().upsert(traceId, payload.span); + if (payload.origin_epoch_ms) store.getState().patch(traceId, { + origin_epoch_ms: payload.origin_epoch_ms, receivedPerfMs: performance.now(), + receivedServerMs: payload.elapsed_ms ?? 0, duration_ms: store.getState().traces[traceId].completed + ?store.getState().traces[traceId].spans.find(s=>s.kind==='request')?.durationMs??payload.elapsed_ms??0:payload.elapsed_ms??0, + }); +} + +export function observeSSE(sessionId: string, traceId: string, type: string, data: SSEEventData, id: number, timing: TraceTiming) { + store.getState().ensure(sessionId, traceId); + const t = store.getState().traces[traceId]; + const meta = data._trace; + const delivery = data._delivery; + if (!meta) return; // Older deployments have no fabricated server/SSE measurements. + const publishedMs = meta.published_ms; + const arrivalMs = t.offsetMs === undefined ? publishedMs + (delivery?.server_queue_ms ?? 0) + : timing.receivedEpochMs + t.offsetMs - meta.origin_epoch_ms; + const transfer = delivery && t.offsetMs !== undefined ? timing.receivedEpochMs + t.offsetMs - delivery.sent_epoch_ms : undefined; + const attrs = { + call_id: data.call_id ?? undefined, + event_seq: id, event_type: type, received_epoch_ms: timing.receivedEpochMs, + server_queue_ms: delivery?.server_queue_ms, parse_ms: timing.parseMs, handler_ms: timing.handlerMs, + encode_ms: delivery?.encode_ms, + transfer_estimate_ms: transfer, clock_uncertainty_ms: t.uncertaintyMs, + clock: t.offsetMs === undefined ? "未校准:不展示单向传输耗时" : "发送准备→浏览器回调:含传输与回调排队,跨端校准误差至少 RTT/2", + }; + if (type === "trace-span") { + const span = (data as SSEEventData & { span?: TraceSpan }).span; + const current = span && store.getState().traces[traceId].spans.find(s => s.id === span.id); + if (current) store.getState().upsert(traceId, { ...current, attributes: { ...current.attributes, delivery: attrs } }); + } + store.getState().event(traceId, { id, type, receivedEpochMs: timing.receivedEpochMs, parseMs: timing.parseMs, handlerMs: timing.handlerMs }); + const current = store.getState().traces[traceId]; + store.getState().patch(traceId, { origin_epoch_ms: meta.origin_epoch_ms, + receivedPerfMs: timing.receivedPerfMs, receivedServerMs: publishedMs + (delivery?.server_queue_ms ?? 0), + duration_ms: current.completed?current.duration_ms:Math.max(current.duration_ms, publishedMs), + metrics: { ...current.metrics, sse_events: (current.metrics.sse_events ?? 0) + 1, + sse_parse_ms: (current.metrics.sse_parse_ms ?? 0) + timing.parseMs, + sse_encode_ms: (current.metrics.sse_encode_ms ?? 0) + (delivery?.encode_ms ?? 0), + sse_handler_ms: (current.metrics.sse_handler_ms ?? 0) + timing.handlerMs }, + }); + if(type==='tool-result'&&data.call_id)store.getState().patch(traceId,{toolReceipts:{...store.getState().traces[traceId].toolReceipts,[data.call_id]:timing.receivedPerfMs}}); + // Sample delivery spans only at meaningful output boundaries, never per token. + if (current.spans.find(s=>s.kind==='request')?.status!=='cancelled'&&((type === 'text-delta' && !current.clientSpans.some(s => s.attributes.event_type === type)) + || ['tool-result', 'tool-error', 'done', 'agent-error'].includes(type))) { + const measured = t.offsetMs !== undefined && arrivalMs >= publishedMs; + addClientSpan(traceId, { id: `client-sse-${id}`, parentId: 'request', name: `SSE 到达 · ${type}`, + service: 'SSE', kind: 'sse', startMs: publishedMs, durationMs: measured ? arrivalMs - publishedMs : delivery?.server_queue_ms ?? 0, + status: measured ? 'ok' : 'incomplete', attributes: attrs }); + } + if (type === 'done' || type === 'agent-error') { + if(type==='done'&&data.finish_reason==='aborted')cancelClientTrace(sessionId,traceId); + store.getState().patch(traceId, { completed: true, metrics: { ...store.getState().traces[traceId].metrics, done_received_perf_ms: timing.receivedPerfMs } }); + } +} + +function browserStartOffset(t: LiveTrace, perf: number) { + return performance.timeOrigin + perf + (t.offsetMs ?? 0) - t.origin_epoch_ms; +} + +const pendingArtifacts = new Set(); +export function recordArtifactCommit(traceId:string, callId:string, element:HTMLElement|null, reactMs?:number) { + const t=store.getState().traces[traceId], received=t?.toolReceipts?.[callId]; + const key=`${traceId}:${callId}`, spanId=`client-artifact-${callId}`; + if(!t||t.completed||received===undefined||!element?.isConnected||element.getBoundingClientRect().width<=0 + ||document.visibilityState!=='visible'||pendingArtifacts.has(key)||t.clientSpans.some(s=>s.id===spanId))return; + pendingArtifacts.add(key); + const committed=performance.now(); + requestAnimationFrame(()=>requestAnimationFrame(()=>{ + pendingArtifacts.delete(key); + if(!element.isConnected||document.visibilityState!=='visible')return; + const painted=performance.now(), current=store.getState().traces[traceId];if(!current||current.completed)return; + addClientSpan(traceId,{id:spanId,parentId:'request',name:'数据卡片 · SSE 接收 → 挂载与帧确认',service:'前端',kind:'frontend', + startMs:browserStartOffset(current,received),durationMs:painted-received,status:'ok',attributes:{call_id:callId, + clock:'browser performance.now()',receive_to_commit_ms:committed-received,commit_to_frame_ms:painted-committed, + ...(reactMs===undefined?{}:{react_actual_duration_ms:reactMs}),boundary:'含事件缓冲、React 调度与双帧确认;非 GPU 精确绘制'}}); + })); +} + +export function recordTextCommit(sessionId: string, hasText: boolean) { + const traceId = store.getState().activeBySession[sessionId]; + const t = store.getState().traces[traceId]; + if (!hasText || !t?.origin_epoch_ms || t.completed || t.metrics.first_text_commit_perf_ms !== undefined || t.metrics.paint_pending) return; + if (typeof document === 'undefined' || document.visibilityState !== 'visible') return; + const commitPerf = performance.now(); + store.getState().patch(traceId, { metrics: { ...t.metrics, paint_pending: 1 } }); + requestAnimationFrame(() => requestAnimationFrame(() => { + const current = store.getState().traces[traceId]; if (!current||current.completed) return; + const painted = performance.now(); + const firstText = current.clientStartPerfMs === undefined ? undefined : painted - current.clientStartPerfMs; + store.getState().patch(traceId, { metrics: { ...current.metrics, paint_pending: 0, + ...(firstText === undefined ? {} : { first_text_paint_ms: firstText }), first_text_commit_perf_ms: commitPerf } }); + addClientSpan(traceId, { id: 'client-first-paint', parentId: 'request', name: '首段文本 · React 提交 → 绘制确认', + service: '前端', kind: 'frontend', startMs: browserStartOffset(current, commitPerf), durationMs: painted - commitPerf, + status: 'ok', attributes: { clock: 'browser performance.now()', boundary: 'useLayoutEffect → 双帧回调(近似绘制)' } }); + })); +} + +export async function finalizeClientTrace(sessionId: string, traceId: string) { + if (finalizing.has(traceId)) return; + const initial = store.getState().traces[traceId]; if (!initial?.origin_epoch_ms) return; + if (initial.spans.find(s=>s.kind==='request')?.status==='cancelled') return; + if (initial.metrics.done_received_perf_ms === undefined) return; + finalizing.add(traceId); + if (document.visibilityState === 'visible') await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))); + const t = store.getState().traces[traceId]; + const now = performance.now(); + if (document.visibilityState === 'visible' && t.metrics.done_received_perf_ms !== undefined) { + const received = t.metrics.done_received_perf_ms; + addClientSpan(traceId, { id: 'client-final-paint', parentId: 'request', name: '完成事件 → 最终内容交接与绘制', + service: '前端', kind: 'frontend', startMs: browserStartOffset(t, received), durationMs: now - received, + status: 'ok', attributes: { clock: 'browser performance.now()', boundary: '含缓冲刷新 / DB 交接 / React 提交 / 双帧确认' } }); + const current = store.getState().traces[traceId]; + store.getState().patch(traceId, { metrics: { ...current.metrics, + ...(t.clientStartPerfMs === undefined ? {} : { end_to_end_ms: now - t.clientStartPerfMs }) } }); + } + const report = store.getState().traces[traceId]; + const deliveries = Object.fromEntries(report.spans.filter(s => s.attributes.delivery).map(s => [s.id, + Object.fromEntries(Object.entries(s.attributes.delivery as Record).filter(([,v])=>v!==undefined))])); + const spans = report.clientSpans.filter(s => s.startMs >= -60000 && Number.isFinite(s.startMs + s.durationMs)).map(s => ({ + ...s, attributes: Object.fromEntries(Object.entries(s.attributes).filter(([,v]) => v !== undefined)) })); + // The server may still be committing its trace; retry observation only. + for (const delay of [0, 300, 1000]) { + if (delay) await new Promise(resolve => setTimeout(resolve, delay)); + try { await api.post(`/api/chat/trace/${encodeURIComponent(traceId)}/client`, { session_id: sessionId, spans, metrics: report.metrics, deliveries }); return; } + catch { /* Keep local evidence even when uploading is unavailable. */ } + } + finalizing.delete(traceId); +} + +export function displaySpans(t: LiveTrace, nowPerf: number): TraceSpan[] { + const elapsed = t.completed ? t.duration_ms : Math.max(t.duration_ms, + (t.receivedServerMs ?? 0) + Math.max(0, nowPerf - (t.receivedPerfMs ?? nowPerf))); + const all = [...t.spans, ...t.clientSpans]; + const projected=all.map(s => ({ ...s, + durationMs: s.status === 'running' ? Math.max(s.durationMs, elapsed - s.startMs) : s.durationMs })); + return traceViewSpans(projected,{ + clientStartMs:t.clientStartEpochMs!==undefined&&t.offsetMs!==undefined&&t.origin_epoch_ms + ?t.clientStartEpochMs+t.offsetMs-t.origin_epoch_ms:undefined, + endToEndMs:t.metrics.end_to_end_ms, + }); +} diff --git a/frontend/src/lib/session-stream-registry.ts b/frontend/src/lib/session-stream-registry.ts index 863dca9..fcdef04 100644 --- a/frontend/src/lib/session-stream-registry.ts +++ b/frontend/src/lib/session-stream-registry.ts @@ -3,6 +3,8 @@ import type { QueryClient, InfiniteData } from "@tanstack/react-query"; import { toast } from "sonner"; import { SSEClient, type SSEConnectionStatus } from "@/lib/sse"; +import { calibrateTrace, finalizeClientTrace, ingestTraceSpan, observeSSE } from "@/lib/execution-trace"; +import { useExecutionTraceStore } from "@/stores/execution-trace-store"; import { API, IS_DESKTOP, getBackendToken, getBackendUrl, queryKeys } from "@/lib/constants"; import { isRemoteMode } from "@/lib/remote-connection"; import { desktopAPI } from "@/lib/tauri-api"; @@ -21,6 +23,7 @@ import { useSettingsStore } from "@/stores/settings-store"; import type { SessionResponse } from "@/types/session"; import type { ArtifactType } from "@/types/artifact"; import type { FilePart, PaginatedMessages } from "@/types/message"; +import type { ExecutionTrace } from '@/types/execution-trace'; const PROGRESSIVE_BUFFER_INTERVAL_MS = 60; const FILE_RESULT_TOOLS = new Set([ @@ -261,6 +264,8 @@ export async function startStream(sessionId: string, streamId: string): Promise< } ensureGlobalListeners(); + useExecutionTraceStore.getState().ensure(sessionId, streamId); + void calibrateTrace(streamId); const store = useChatStore; const connectionStore = useConnectionStore; @@ -351,6 +356,7 @@ export async function startStream(sessionId: string, streamId: string): Promise< } store.getState().finishGeneration(sid); + void finalizeClientTrace(sid, streamId); if (instances.size === 0) connectionStore.getState().setStatus("idle"); const workspace = useWorkspaceStore.getState(); if ( @@ -391,6 +397,7 @@ export async function startStream(sessionId: string, streamId: string): Promise< url: API.CHAT.STREAM(streamId), urlProvider: () => API.CHAT.STREAM(streamId), initialLastEventId: 0, + onTiming: (type, data, id, timing) => observeSSE(sessionId, streamId, type, data, id, timing), onEvent: () => { const inst = instances.get(sessionId); if (inst) inst.lastEventTimestamp = Date.now(); @@ -440,6 +447,7 @@ export async function startStream(sessionId: string, streamId: string): Promise< client.on(SSE_EVENTS.MODEL_LOADING, () => { store.getState().setModelLoading(sessionId, true); }); + client.on('trace-span', data => ingestTraceSpan(sessionId, streamId, data)); client.on(SSE_EVENTS.TEXT_DELTA, (data) => { cancelPendingStepFinish(); @@ -773,6 +781,8 @@ export async function startStream(sessionId: string, streamId: string): Promise< client.on(SSE_EVENTS.DESYNC, () => { const qc = queryClientRef; if (qc) qc.invalidateQueries({ queryKey: queryKeys.messages.list(sessionId) }); + void api.get(`/api/chat/trace/${encodeURIComponent(streamId)}?session_id=${encodeURIComponent(sessionId)}`) + .then(snapshot=>useExecutionTraceStore.getState().hydrate(sessionId,snapshot,true)).catch(()=>{}); }); client.on(SSE_EVENTS.COMPACTION_ERROR, (data) => { diff --git a/frontend/src/lib/sse.ts b/frontend/src/lib/sse.ts index 55cabc3..33a366e 100644 --- a/frontend/src/lib/sse.ts +++ b/frontend/src/lib/sse.ts @@ -19,6 +19,7 @@ import { } from "./constants"; import { getRemoteToken } from "./remote-connection"; import type { SSEEventData } from "@/types/streaming"; +import type { TraceTiming } from "@/types/execution-trace"; export type SSEEventHandler = (data: SSEEventData, id: number) => void; @@ -44,6 +45,7 @@ export interface SSEClientOptions { onStatusChange?: (status: SSEConnectionStatus) => void; /** Called on any received event (for idle timeout tracking). */ onEvent?: () => void; + onTiming?: (type: string, data: SSEEventData, id: number, timing: TraceTiming) => void; } export class SSEClient { @@ -179,8 +181,15 @@ export class SSEClient { /** Dispatch a parsed SSE event to registered handlers. */ private dispatchEvent(eventType: string, data: string, id: string): void { + if (this.closed || this.paused) return; + const receivedPerfMs = performance.now(); + const receivedEpochMs = performance.timeOrigin + receivedPerfMs; if (id) { - this.lastEventId = parseInt(id, 10); + const next = Number(id); + if (Number.isFinite(next)) { + if (next <= this.lastEventId) return; + this.lastEventId = next; + } } this.nativeReconnectCount = 0; @@ -189,16 +198,22 @@ export class SSEClient { this.options.onEvent?.(); let parsed: SSEEventData; + const parseStarted = performance.now(); try { parsed = JSON.parse(data) as SSEEventData; } catch { parsed = {} as SSEEventData; } + const parseMs = performance.now() - parseStarted; + const handlerStarted = performance.now(); const handlers = this.handlers.get(eventType) ?? []; for (const handler of handlers) { handler(parsed, this.lastEventId); } + this.options.onTiming?.(eventType, parsed, this.lastEventId, { + receivedPerfMs, receivedEpochMs, parseMs, handlerMs: performance.now() - handlerStarted, + }); } /** diff --git a/frontend/src/lib/trace-layout.ts b/frontend/src/lib/trace-layout.ts new file mode 100644 index 0000000..7cffc43 --- /dev/null +++ b/frontend/src/lib/trace-layout.ts @@ -0,0 +1,141 @@ +import type { TraceSpan } from '@/types/execution-trace'; + +export function durationLabel(ms: number): string { + if (ms > 0 && ms < 1) return `${Math.round(ms * 1000)} µs`; + return ms < 1000 ? `${ms.toFixed(ms < 10 ? 1 : 0)} ms` : `${(ms / 1000).toFixed(2)} s`; +} + +/** Queue time is deliberately excluded from concurrency detection. */ +export function executionGroups(tools: TraceSpan[], all: TraceSpan[]): TraceSpan[][] { + const executionOf = (tool:TraceSpan) => all.find(s => s.parentId === tool.id && s.name === '工具执行') ?? tool; + const ordered = [...tools].sort((a,b) => executionOf(a).startMs - executionOf(b).startMs); + const groups: TraceSpan[][] = []; + const recorded=new Set(); + let until = -Infinity; + for (const tool of ordered) { + const dispatchGroup=tool.attributes.parallel_group_id; + if(typeof dispatchGroup==='string'){ + if(!recorded.has(dispatchGroup)){groups.push(ordered.filter(s=>s.attributes.parallel_group_id===dispatchGroup));recorded.add(dispatchGroup);} + until=-Infinity; + continue; + } + const execution = executionOf(tool); + if (tool.attributes.concurrent === true && groups.length && execution.startMs < until + && groups.at(-1)!.every(s => s.attributes.concurrent === true)) { + groups.at(-1)!.push(tool); + } else groups.push([tool]); + until = Math.max(execution.startMs + execution.durationMs, groups.at(-1)!.length > 1 ? until : -Infinity); + } + return groups; +} + +export interface GraphNode { id: string; span: TraceSpan; label: string; x: number; y: number } +export interface GraphEdge { from: string; to: string; retry?: boolean } + +export function graphLabel(span:TraceSpan):string{ + const input=span.attributes.input; + if(span.kind==='tool'&&input&&typeof input==='object'&&'title' in input&&typeof input.title==='string'&&input.title.trim())return input.title; + return span.name; +} + +export function truncateGraphLabel(label:string,maxWidth:number):string{ + let width=0,result=''; + for(const char of label){const next=/[\u0000-\u00ff]/.test(char)?6.5:12;if(width+next>maxWidth-12)return result+'…';result+=char;width+=next;} + return result; +} + +export function layoutTrace(spans: TraceSpan[]): { nodes: GraphNode[]; edges: GraphEdge[]; height: number; minX:number; maxX:number; width:number } { + const nodes: GraphNode[] = [], edges: GraphEdge[] = [], used = new Set(); + let previous: string[] = [], row = 0; + const append = (items: TraceSpan[], labels?: string[]) => { + if (!items.length) return; + const ids: string[] = []; + items.forEach((span,i) => { + const x = 425 + (i-(items.length-1)/2)*330; + nodes.push({ id: span.id, span, label: labels?.[i] ?? graphLabel(span), x, y: 60 + row*100 }); + previous.forEach(from => edges.push({ from, to: span.id })); + ids.push(span.id); used.add(span.id); + }); + previous = ids; row++; + }; + const sorted = spans.filter(s=>s.kind!=='sse'&&s.kind!=='frontend'&&s.service!=='SSE'&&s.service!=='前端').sort((a,b) => a.startMs-b.startMs); + append(sorted.filter(s => s.kind === 'request')); + const models = sorted.filter(s => s.kind === 'model'); + const rootPhases=sorted.filter(s=>s.kind==='phase'&&s.parentId==='request'&&s.attributes.group_kind!=='parallel'); + rootPhases.filter(s=>s.startMs<(models[0]?.startMs??Infinity)).forEach(s=>append([s])); + const tools = sorted.filter(s => s.kind === 'tool'); + const appendTools=(group:TraceSpan[])=>{ + const groupId=group[0]?.attributes.parallel_group_id; + const parallel=typeof groupId==='string'&&group.every(s=>s.attributes.parallel_group_id===groupId) + ?spans.find(s=>s.id===groupId&&s.attributes.group_kind==='parallel'):undefined; + if(parallel)append([parallel],['并行分支']); + append(group); + const join=parallel&&spans.find(s=>s.id===parallel.attributes.join_span_id); + if(join)append([join],['结果汇合']); + }; + models.forEach((model, index) => { + append([model], [`${model.attributes.source_session_id?'子智能体 · ':''}模型调用 ${index + 1}`]); + rootPhases.filter(s=>s.startMs>=model.startMs&&s.startMs<(models[index+1]?.startMs??Infinity)).forEach(s=>append([s])); + for (const group of executionGroups(tools.filter(t => t.attributes.producer_span_id === model.id), spans)) appendTools(group); + }); + for (const group of executionGroups(tools.filter(t => !used.has(t.id)), spans)) appendTools(group); + // This is the Agent execution graph. SSE transport and browser rendering + // stay in the complete waterfall and span details, not the graph's spine. + // Retry edges are only marked when the collector explicitly recorded a retry. + for (const node of nodes) { + const retryOf = node.span.attributes.retry_of; + if (typeof retryOf === 'string' && used.has(retryOf)) { + const producer=node.span.attributes.producer_span_id; + const paths=typeof producer==='string'&&nodes.some(n=>n.id===producer&&n.span.kind==='model')&&producer!==retryOf + ?[[retryOf,producer],[producer,node.id]]:[[retryOf,node.id]]; + for(const [from,to] of paths){ + // Replace the ordinary edge; do not leave a solid line behind the dash. + for(let i=edges.length-1;i>=0;i--)if(edges[i].from===from&&edges[i].to===to)edges.splice(i,1); + edges.push({from,to,retry:true}); + } + } + } + const minX=Math.min(0,...nodes.map(n=>n.x)),maxX=Math.max(850,...nodes.map(n=>n.x)); + return { nodes, edges, height: Math.max(300, row*100 + 80), minX, maxX, width:maxX-minX }; +} + +export function nearestGraphNode(selectedId: string | null, spans: TraceSpan[], nodes: GraphNode[]): string | null { + if(selectedId&&nodes.some(n=>n.id===selectedId))return selectedId; + const owner=relatedToolSpans(selectedId,spans).find(s=>nodes.some(n=>n.id===s.id)); + if(owner)return owner.id; + let key = selectedId; + const seen = new Set(); + while (key && !seen.has(key)) { + if (nodes.some(n => n.id === key)) return key; + const anchor=spans.find(s=>s.id===key)?.attributes.__view_graph_anchor; + if(typeof anchor==='string'&&nodes.some(n=>n.id===anchor))return anchor; + seen.add(key); key = spans.find(s => s.id === key)?.parentId ?? null; + } + return null; +} + +/** Resolve by recorded IDs/parentage, never by matching tool names. */ +export function relatedToolSpans(selectedId:string|null,spans:TraceSpan[]):TraceSpan[]{ + let current=spans.find(s=>s.id===selectedId); + const seen=new Set(); + while(current&&!seen.has(current.id)){ + seen.add(current.id); + if(current.kind==='tool')return [current]; + const call=current.attributes.call_id; + if(typeof call==='string'){ + const owner=spans.find(s=>s.kind==='tool'&&s.attributes.call_id===call + &&s.attributes.source_session_id===current?.attributes.source_session_id); + if(owner)return [owner]; + } + if(current.kind==='model')return spans.filter(s=>s.kind==='tool'&&s.attributes.producer_span_id===current!.id); + if(current.attributes.group_kind==='parallel'||Array.isArray(current.attributes.group_members)){ + const members=current.attributes.group_members; + const tools=spans.filter(s=>s.kind==='tool'&&(s.attributes.parallel_group_id===current!.id + ||(Array.isArray(members)&&members.includes(s.id)))); + if(tools.length)return tools.sort((a,b)=>a.startMs-b.startMs); + } + if(current.kind==='request')break; + current=spans.find(s=>s.id===current?.parentId); + } + return []; +} diff --git a/frontend/src/lib/trace-replay.ts b/frontend/src/lib/trace-replay.ts new file mode 100644 index 0000000..8e09da8 --- /dev/null +++ b/frontend/src/lib/trace-replay.ts @@ -0,0 +1,23 @@ +import type { TraceSpan } from '@/types/execution-trace'; + +const END_ATTRIBUTES=new Set(['output_preview','error_preview','time_start','time_end','timed_out','failed_count','provider_await_ms','delivery','active_count','peak_concurrency', + 'received_epoch_ms','parse_ms','handler_ms','transfer_estimate_ms','receive_to_commit_ms','commit_to_frame_ms','react_actual_duration_ms','encode_ms','server_queue_ms']); + +/** Replay measured intervals only. Does not issue requests or fabricate tokens. */ +export function replaySpans(spans:TraceSpan[], cursor:number):TraceSpan[]{ + return spans.filter(s=>s.startMs<=cursor).map(s=>{ + const finished=cursor>=s.startMs+s.durationMs; + return {...s,durationMs:Math.max(0,Math.min(s.durationMs,cursor-s.startMs)), + status:finished?s.status:'running', + attributes:finished?s.attributes:Object.fromEntries(Object.entries(s.attributes).filter(([key])=>!END_ATTRIBUTES.has(key)))}; + }); +} + +export function replayBoundaries(spans:TraceSpan[]):number[]{ + return [...new Set([0,...spans.flatMap(s=>[s.startMs,s.startMs+s.durationMs])])].sort((a,b)=>a-b); +} + +export function nextReplayTime(times:number[],cursor:number,direction:1|-1):number{ + return direction===1?(times.find(t=>t>cursor+.000001)??times.at(-1)??0) + :([...times].reverse().find(t=>ts.id)); + const roots=spans.filter(s=>!s.parentId||!ids.has(s.parentId)); + const earliest=Math.min(...spans.map(s=>s.startMs)); + const first=Math.min(0,earliest); + const last=Math.max(...spans.map(s=>s.startMs+s.durationMs)); + const browser=spans.some(s=>s.kind==='frontend'||s.kind==='sse'); + const missing=spans.some(s=>s.parentId&&!ids.has(s.parentId)); + const needEnvelope=browser||missing||roots.length!==1||roots.some(s=>s.startMs>earliest||s.startMs+s.durationMss.id==='client-final-paint'&&s.status==='ok'); + const browserStart=options.clientStartMs??(finalPaint&&options.endToEndMs!==undefined + ?finalPaint.startMs+finalPaint.durationMs-options.endToEndMs:undefined); + const origin=Math.min(first,browserStart??0); + const id='view-request-envelope'; + const shifted=spans.map(span=>{ + const external=span.kind==='frontend'||span.kind==='sse'; + const parent=needEnvelope&&(external||!span.parentId||!ids.has(span.parentId))?id:span.parentId; + return {...span,startMs:span.startMs-origin,parentId:parent, + attributes:parent!==span.parentId?{...span.attributes,__recorded_parent_id:span.parentId??null}:span.attributes}; + }); + if(!needEnvelope)return shifted; + const anchor=spans.find(s=>s.kind==='request'); + const status=spans.some(s=>s.status==='running')?'running':anchor?.status??'ok'; + const envelope:TraceSpan={id,parentId:null,name:'全链路观测范围',service:'请求',kind:'phase',startMs:0, + durationMs:Math.max(...shifted.map(s=>s.startMs+s.durationMs)),status, + attributes:{__view_derived:true,__view_graph_anchor:anchor?.id, + timing_basis:'view container calculated from collected interval bounds; not an extra model/tool invocation', + recorded_spans:spans.length,axis_shift_ms:-origin, + ...(options.endToEndMs===undefined?{}:{measured_browser_end_to_end_ms:options.endToEndMs})}}; + return [envelope,...shifted]; +} diff --git a/frontend/src/lib/trace-view-state.ts b/frontend/src/lib/trace-view-state.ts new file mode 100644 index 0000000..3fe4652 --- /dev/null +++ b/frontend/src/lib/trace-view-state.ts @@ -0,0 +1,15 @@ +/** Per-record presentation state survives desktop/sidebar/sheet remounts. + * Ephemeral UI only: never changes measurements or restarts execution. + */ +export interface TraceViewState { + view:'tools'|'waterfall'|'graph';selected:string|null;expanded:boolean;follow:boolean;clockHelp:boolean; + tab:'summary'|'io'|'events';locate:number;replayMs:number|null;playing:boolean;speed:number; + waterfall:Record;graphCamera:{x:number;y:number;w:number}; + expandedToolIds:string[];toolTargets:string[]; +} +const cache=new Map>(); +export function readTraceViewState(key:string):Partial|undefined{return cache.get(key);} +export function saveTraceViewState(key:string,patch:Partial):void{ + const previous=cache.get(key);cache.delete(key);cache.set(key,{...previous,...patch}); + if(cache.size>50)cache.delete(cache.keys().next().value!); +} diff --git a/frontend/src/lib/trace-waterfall-state.ts b/frontend/src/lib/trace-waterfall-state.ts new file mode 100644 index 0000000..c460dd7 --- /dev/null +++ b/frontend/src/lib/trace-waterfall-state.ts @@ -0,0 +1,27 @@ +import type { TraceSpan } from '@/types/execution-trace'; + +/** Default only newly seen call groups to closed; never undo a user's choice. */ +export function defaultCollapsedCalls( + spans: TraceSpan[], collapsed: string[], known: Set, restoring = false, +): string[] { + const parents = new Set(spans.map(s => s.parentId)); + const next = new Set(collapsed); + for (const span of spans) { + if ((span.kind !== 'model' && span.kind !== 'tool') || !parents.has(span.id)) continue; + if (!known.has(span.id) && !restoring) next.add(span.id); + known.add(span.id); + } + return [...next]; +} + +/** Cross-view navigation opens only the path to the selected span. */ +export function expandSpanAncestors(spans: TraceSpan[], collapsed: string[], selected: string | null): string[] { + const byId = new Map(spans.map(s => [s.id, s])); + const ancestors = new Set(); + let parent = selected ? byId.get(selected)?.parentId : null; + while (parent && !ancestors.has(parent)) { + ancestors.add(parent); + parent = byId.get(parent)?.parentId; + } + return collapsed.filter(id => !ancestors.has(id)); +} diff --git a/frontend/src/stores/activity-store.ts b/frontend/src/stores/activity-store.ts index 05b73d5..042726d 100644 --- a/frontend/src/stores/activity-store.ts +++ b/frontend/src/stores/activity-store.ts @@ -2,6 +2,7 @@ import { create } from "zustand"; import type { PartData, ToolPart, StepStartPart, StepFinishPart } from "@/types/message"; +import type { ExecutionTrace } from '@/types/execution-trace'; /** A single item in the execution chain (preserves interleaving order). */ export type ChainItem = @@ -9,6 +10,9 @@ export type ChainItem = | { type: "tool"; data: ToolPart }; export interface ActivityData { + traceId?: string; + sessionId?: string; + executionTrace?: ExecutionTrace; sourceKey?: string; mode?: "default" | "expert-team"; parts?: PartData[]; @@ -87,9 +91,12 @@ export const useActivityStore = create((set, get) => ({ set({ isOpen: true, activeKey: key, activeData: data }); }, refreshForMessage: (key, data) => { - const { isOpen, activeKey } = get(); - if (isOpen && activeKey === key) { - set({ activeData: data }); + const { isOpen, activeKey, activeData } = get(); + const completedHandoff = data.traceId && data.traceId === activeData?.traceId && data.executionTrace?.completed; + // Register the latest execution quietly. Only explicit user actions open + // the panel; updates must not reopen a dismissed panel or steal selection. + if (!isOpen || activeKey === key || completedHandoff) { + set({ activeKey: key, activeData: data }); } }, close: () => { diff --git a/frontend/src/stores/execution-trace-store.ts b/frontend/src/stores/execution-trace-store.ts new file mode 100644 index 0000000..ba258d7 --- /dev/null +++ b/frontend/src/stores/execution-trace-store.ts @@ -0,0 +1,72 @@ +"use client"; + +import { create } from "zustand"; +import type { ExecutionTrace, LiveTrace, TraceEvent, TraceSpan } from "@/types/execution-trace"; + +interface TraceState { + traces: Record; + activeBySession: Record; + ensure: (sessionId: string, traceId: string, activate?:boolean) => void; + patch: (traceId: string, patch: Partial) => void; + upsert: (traceId: string, span: TraceSpan) => void; + event: (traceId: string, event: TraceEvent) => void; + hydrate: (sessionId: string, snapshot: ExecutionTrace, recoverLive?:boolean) => void; +} + +export const useExecutionTraceStore = create((set, get) => ({ + traces: {}, activeBySession: {}, + ensure: (sessionId, traceId, activate=true) => { + if (get().traces[traceId]) { + if(activate&&get().activeBySession[sessionId]!==traceId)set(s=>({activeBySession:{...s.activeBySession,[sessionId]:traceId}})); + return; + } + set(s => { + // A bounded cache; historical traces are recoverable from the database. + const entries = Object.entries(s.traces); + const expired = entries.filter(([, t]) => t.completed).slice(0, Math.max(0, entries.length - 19)); + const traces = { ...s.traces }; + expired.forEach(([id]) => delete traces[id]); + traces[traceId] = { version: 1, trace_id: traceId, sessionId, origin_epoch_ms: 0, + duration_ms: 0, completed: false, spans: [], events: [], clientSpans: [], metrics: {} }; + return { traces, ...(activate?{activeBySession: { ...s.activeBySession, [sessionId]: traceId }}:{}) }; + }); + }, + patch: (id, patch) => set(s => s.traces[id] ? { traces: { ...s.traces, [id]: { ...s.traces[id], ...patch } } } : s), + upsert: (id, span) => set(s => { + const trace = s.traces[id]; if (!trace) return s; + if (trace.completed && span.status==='running') return s; + const index = trace.spans.findIndex(p => p.id === span.id); + if (index < 0 && trace.spans.length >= 2000) return s; + const spans = [...trace.spans]; + if (index >= 0) spans[index] = { ...span, attributes: { ...spans[index].attributes, ...span.attributes } }; + else spans.push(span); + return { traces: { ...s.traces, [id]: { ...trace, spans, + completed: span.id === "request" && span.status !== "running" ? true : trace.completed } } }; + }), + event: (id, event) => set(s => { + const trace = s.traces[id]; if (!trace || trace.events.some(e => e.id === event.id)) return s; + return { traces: { ...s.traces, [id]: { ...trace, events: [...trace.events.slice(-199), event] } } }; + }), + hydrate: (sessionId, snapshot, recoverLive=false) => { + if (!snapshot || snapshot.version !== 1 || !Array.isArray(snapshot.spans)) return; + get().ensure(sessionId, snapshot.trace_id, false); + const current = get().traces[snapshot.trace_id]; + if (current.completed && !snapshot.completed) return; + // Never overwrite a live stream or local paint measurements with stale DB data. + if (current.spans.length && !snapshot.completed && !recoverLive) return; + const recovered=recoverLive&&!snapshot.completed?[ + ...snapshot.spans.map(span=>{ + const latest=current.spans.find(s=>s.id===span.id); + return latest&&latest.status!=='running'&&span.status==='running'?latest:span; + }),...current.spans.filter(span=>!snapshot.spans.some(s=>s.id===span.id)), + ]:snapshot.spans; + get().patch(snapshot.trace_id, { ...snapshot, sessionId, + duration_ms:Math.max(snapshot.duration_ms,current.duration_ms), + spans: recovered.map(span => ({ ...span, attributes: { + ...span.attributes, ...current.spans.find(s => s.id === span.id)?.attributes, + ...(snapshot.client?.deliveries?.[span.id] ? {delivery: snapshot.client.deliveries[span.id]} : {}), } })), + clientSpans: current.clientSpans.length ? current.clientSpans : snapshot.client?.spans ?? [], + metrics: { ...snapshot.client?.metrics, ...current.metrics }, + }); + }, +})); diff --git a/frontend/src/types/execution-trace.ts b/frontend/src/types/execution-trace.ts new file mode 100644 index 0000000..906a64e --- /dev/null +++ b/frontend/src/types/execution-trace.ts @@ -0,0 +1,51 @@ +export interface TraceSpan { + id: string; + parentId?: string | null; + name: string; + service: string; + kind: "request" | "phase" | "model" | "tool" | "frontend" | "sse"; + startMs: number; + durationMs: number; + status: "running" | "ok" | "error" | "cancelled" | "incomplete"; + attributes: Record; +} + +export interface ExecutionTrace { + version: number; + trace_id: string; + origin_epoch_ms: number; + duration_ms: number; + completed: boolean; + dropped_spans?: number; + spans: TraceSpan[]; + client?: { spans: TraceSpan[]; metrics: Record; deliveries?: Record> }; +} + +export interface TraceTiming { + receivedEpochMs: number; + receivedPerfMs: number; + parseMs: number; + handlerMs: number; +} + +export interface TraceEvent { + id: number; + type: string; + receivedEpochMs: number; + parseMs: number; + handlerMs: number; +} + +export interface LiveTrace extends ExecutionTrace { + sessionId: string; + events: TraceEvent[]; + receivedPerfMs?: number; + receivedServerMs?: number; + clientStartPerfMs?: number; + clientStartEpochMs?: number; + offsetMs?: number; + uncertaintyMs?: number; + clientSpans: TraceSpan[]; + metrics: Record; + toolReceipts?: Record; +} diff --git a/frontend/src/types/message.ts b/frontend/src/types/message.ts index fc8221b..e7d7f07 100644 --- a/frontend/src/types/message.ts +++ b/frontend/src/types/message.ts @@ -131,6 +131,8 @@ export interface UserMessageInfo { } export interface AssistantMessageInfo { + trace_id?: string; + execution_trace?: import('./execution-trace').ExecutionTrace; role: "assistant"; parent_id?: string | null; agent?: string; diff --git a/frontend/src/types/streaming.ts b/frontend/src/types/streaming.ts index 3800929..ede34fd 100644 --- a/frontend/src/types/streaming.ts +++ b/frontend/src/types/streaming.ts @@ -31,6 +31,8 @@ export const SSE_EVENTS = { /** SSE event payload — mirrors backend app/schemas/streaming.py SSEEventData */ export interface SSEEventData { + _trace?: { trace_id: string; origin_epoch_ms: number; published_ms: number }; + _delivery?: { sent_epoch_ms: number; server_queue_ms: number; encode_ms?: number }; // Common session_id?: string | null; message_id?: string | null;