Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(swarm): add realtime trajectory archive and replay

alan_cheng8b1a815c9480
diff --git a/jiuwenswarm/agents/harness/agent_observability.py b/jiuwenswarm/agents/harness/agent_observability.py
index c877a5f2fb..35e14fae65 100644
--- a/jiuwenswarm/agents/harness/agent_observability.py
+++ b/jiuwenswarm/agents/harness/agent_observability.py
@@ -37,6 +37,11 @@ from jiuwenswarm.common.config import (
get_skill_evolution_enabled,
)
from jiuwenswarm.common.utils import get_user_workspace_dir
+from jiuwenswarm.observability.config import load_trajectory_store_settings
+from jiuwenswarm.observability.runtime import (
+ shutdown_trajectory_runtime,
+ sync_trajectory_runtime,
+)
logger = logging.getLogger(__name__)
@@ -80,9 +85,11 @@ def sync_agent_observability(*, force: bool = False) -> None:
config = get_config()
cfg = config.get("agent_observability", {}) or {}
+ trajectory_settings = load_trajectory_store_settings(config)
evolution_requested = get_skill_evolution_enabled(config)
want_enabled = (
bool(cfg.get("enabled", False))
+ or trajectory_settings.enabled
or evolution_requested
or force
or _force_ever_enabled
@@ -91,6 +98,10 @@ def sync_agent_observability(*, force: bool = False) -> None:
_force_ever_enabled = True
if not want_enabled:
+ try:
+ sync_trajectory_runtime(trajectory_settings)
+ except Exception as exc:
+ logger.warning("[AgentObservability] trajectory runtime stop failed: %s", exc)
if _agent_observability_active:
shutdown_agent_observability()
return
@@ -105,6 +116,12 @@ def sync_agent_observability(*, force: bool = False) -> None:
provider_existed = acquire_observability(obs_cfg)
was_active = _agent_observability_active
_agent_observability_active = True
+ try:
+ sync_trajectory_runtime(trajectory_settings)
+ except Exception as exc:
+ # The trajectory read store is an optional fan-out. Existing file,
+ # OTLP and Langfuse exporters must keep the Agent path available.
+ logger.warning("[AgentObservability] trajectory runtime init failed: %s", exc)
if not was_active:
if provider_existed:
logger.info(
@@ -135,6 +152,11 @@ def sync_agent_observability(*, force: bool = False) -> None:
def shutdown_agent_observability() -> None:
"""Shutdown single-agent observability (on disable or process exit)."""
global _agent_observability_active
+ try:
+ if not shutdown_trajectory_runtime():
+ logger.warning("[AgentObservability] trajectory runtime did not drain cleanly")
+ except Exception as exc:
+ logger.warning("[AgentObservability] trajectory runtime shutdown failed: %s", exc)
if not _agent_observability_active:
return
try:
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.json
index 7914cc56bd..a2fb75b032 100644
--- a/jiuwenswarm/channels/web/frontend/package.json
+++ b/jiuwenswarm/channels/web/frontend/package.json
@@ -39,6 +39,10 @@
"test:desktop-save": "esbuild src/utils/desktopSave.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/desktop-save/desktopSave.mjs && node --test tests/desktopSave.test.mjs",
"test:ask-user-submission": "tsc src/components/InteractionSlot/interactionSubmission.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/ask-user-submission --skipLibCheck --noEmitOnError && node --test tests/askUserSubmission.test.mjs",
"test:skill-approval-presentation": "tsc src/components/ChatPanel/skillApprovalPresentation.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/skill-approval-presentation --skipLibCheck --noEmitOnError && node --test tests/skillApprovalPresentation.test.mjs",
+ "test:trajectory-projector": "esbuild src/features/trajectory/projector/otel-trajectory-projector.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/trajectory-projector/projector.mjs && node --test tests/trajectoryProjector.test.mjs",
+ "test:trajectory-host": "esbuild src/features/trajectory/SingleAgentSurface.tsx --bundle --packages=external --platform=node --format=esm --outfile=node_modules/.cache/trajectory-host/SingleAgentSurface.mjs && node --test tests/singleAgentSurface.test.mjs",
+ "test:trajectory-layout": "esbuild src/features/trajectory/trajectoryLayout.ts --bundle --platform=node --format=esm --outdir=node_modules/.cache/trajectory-layout && node --test tests/trajectoryLayout.test.mjs",
+ "test:trajectory-window": "esbuild src/features/trajectory/trajectoryWindow.ts --bundle --platform=node --format=esm --define:import.meta.env.VITE_API_BASE=undefined --outfile=node_modules/.cache/trajectory-window/trajectoryWindow.mjs && esbuild src/features/trajectory/trajectoryClient.ts --bundle --platform=node --format=esm --define:import.meta.env.VITE_API_BASE=undefined --outfile=node_modules/.cache/trajectory-window/trajectoryClient.mjs && esbuild src/features/trajectory/trajectoryArchive.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/trajectory-window/trajectoryArchive.mjs && esbuild src/features/trajectory/trajectory/record.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/trajectory-window/record.mjs && node --test tests/trajectoryWindow.test.mjs",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
@@ -61,16 +65,31 @@
"@codemirror/legacy-modes": "6.5.3",
"@codemirror/state": "6.7.1",
"@codemirror/view": "6.43.7",
+ "@shikijs/langs": "^4.3.1",
"@tailwindcss/typography": "^0.5.19",
+ "@tanstack/react-virtual": "^3.14.9",
"clsx": "^2.1.0",
+ "diff": "^9.0.0",
"docx-preview": "0.3.7",
"exceljs": "4.4.0",
"html-to-image": "1.11.13",
"i18next": "^25.8.18",
"i18next-browser-languagedetector": "^8.2.1",
"jszip": "3.10.1",
+ "katex": "0.16.47",
"lucide-react": "1.16.0",
+ "mdast-util-from-markdown": "2.0.3",
+ "mdast-util-gfm": "^3.1.0",
+ "mdast-util-math": "^3.0.0",
"mermaid": "11.15.0",
+ "micromark-core-commonmark": "^2.0.3",
+ "micromark-extension-gfm": "^3.0.0",
+ "micromark-extension-math": "^3.1.0",
+ "micromark-factory-space": "^2.0.1",
+ "micromark-util-character": "^2.1.1",
+ "micromark-util-classify-character": "^2.0.1",
+ "micromark-util-sanitize-uri": "^2.0.1",
+ "micromark-util-symbol": "^2.0.1",
"qrcode.react": "^4.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
@@ -78,10 +97,12 @@
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"saxes": "5.0.1",
+ "shiki": "^4.3.1",
"ssf": "0.11.2",
"zustand": "^4.5.0"
},
"devDependencies": {
+ "@types/mdast": "^4.0.4",
"@types/node": "^25.2.3",
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.0",
diff --git a/jiuwenswarm/channels/web/frontend/public/third-party/deepseek-harness/LICENSE b/jiuwenswarm/channels/web/frontend/public/third-party/deepseek-harness/LICENSE
new file mode 100644
index 0000000000..c1f7a78e89
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/public/third-party/deepseek-harness/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 DeepSeek
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/jiuwenswarm/channels/web/frontend/public/third-party/deepseek-harness/NOTICE.md b/jiuwenswarm/channels/web/frontend/public/third-party/deepseek-harness/NOTICE.md
new file mode 100644
index 0000000000..e15030eb35
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/public/third-party/deepseek-harness/NOTICE.md
@@ -0,0 +1,13 @@
+# DeepSeek Harness trajectory source notice
+
+English | [中文](NOTICE.zh.md)
+
+JiuwenSwarm's trajectory renderer adapts source code and behavior from the following DeepSeek Harness source tree at commit `99f6f02fecdb7dff40c3fbc9470f5907c29f74ca`:
+
+- `packages/client/ui-trajectory`
+- `packages/client/ui-theme/src/styles`
+- `packages/client/ui-primitives/src`
+
+The adapted areas include the trajectory explorer, timeline and table presentation, theme tokens, Tooltip, Menu, JSON tree, Markdown and syntax-highlighted content presentation, KaTeX integration, and icons. JiuwenSwarm adds an OpenTelemetry projector, its own data transport, single-Agent host integration, and compatibility mappings.
+
+The DeepSeek sources are distributed under the adjacent [MIT license](LICENSE). Copyright remains with DeepSeek and the other applicable copyright holders.
diff --git a/jiuwenswarm/channels/web/frontend/public/third-party/deepseek-harness/NOTICE.zh.md b/jiuwenswarm/channels/web/frontend/public/third-party/deepseek-harness/NOTICE.zh.md
new file mode 100644
index 0000000000..7625dc16d8
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/public/third-party/deepseek-harness/NOTICE.zh.md
@@ -0,0 +1,13 @@
+# DeepSeek Harness 轨迹源码声明
+
+[English](NOTICE.md) | 中文
+
+JiuwenSwarm 的轨迹 renderer 改编自 DeepSeek Harness 提交 `99f6f02fecdb7dff40c3fbc9470f5907c29f74ca` 中的下列源码目录:
+
+- `packages/client/ui-trajectory`
+- `packages/client/ui-theme/src/styles`
+- `packages/client/ui-primitives/src`
+
+改编范围包括轨迹浏览、时间线和表格展示、主题 token,以及 Tooltip、Menu、JSON tree、Markdown 与语法高亮内容展示、KaTeX 集成和图标。JiuwenSwarm 在此基础上增加了 OpenTelemetry projector、自有数据传输、单 Agent 宿主集成和兼容字段映射。
+
+DeepSeek 源码依据同目录随附的 [MIT 许可证](LICENSE)分发。版权仍归 DeepSeek 及其他适用的版权所有者所有。
diff --git a/jiuwenswarm/channels/web/frontend/src/App.css b/jiuwenswarm/channels/web/frontend/src/App.css
index 6eb9a8c01a..20d5624a5b 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.css
+++ b/jiuwenswarm/channels/web/frontend/src/App.css
@@ -22,6 +22,137 @@
background: var(--color-surface-card);
}
+.chat-surface-toolbar {
+ display: flex;
+ width: 100%;
+ min-width: 0;
+ flex: 0 0 auto;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.5rem;
+ margin: 0.5rem 0 0.375rem;
+}
+
+.chat-surface-tabs {
+ display: inline-flex;
+ flex: 0 0 auto;
+ gap: 0.125rem;
+ border: 1px solid var(--color-border-default);
+ border-radius: 0.5rem;
+ background: var(--color-action-secondary);
+ padding: 0.125rem;
+}
+
+.chat-surface-layout-controls {
+ display: flex;
+ min-width: 0;
+ align-items: center;
+ justify-content: flex-end;
+ gap: 0.25rem;
+}
+
+.chat-surface-layout-control {
+ position: relative;
+ display: inline-flex;
+ width: 1.75rem;
+ height: 1.75rem;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid var(--color-border-default);
+ border-radius: 0.375rem;
+ background: var(--color-action-secondary);
+ color: var(--color-text-secondary);
+ cursor: pointer;
+ font-size: 1.125rem;
+ line-height: 1;
+ padding: 0;
+ white-space: nowrap;
+}
+
+.chat-surface-layout-control:hover::after,
+.chat-surface-layout-control:focus-visible::after {
+ position: absolute;
+ z-index: 20;
+ top: calc(100% + 0.375rem);
+ right: 0;
+ width: max-content;
+ max-width: 12rem;
+ border-radius: 0.375rem;
+ background: var(--color-surface-elevated, var(--color-surface-card));
+ box-shadow: var(--effect-shadow-md);
+ color: var(--color-text-primary);
+ content: attr(data-tooltip);
+ font-size: 0.75rem;
+ font-weight: 400;
+ line-height: 1.25rem;
+ padding: 0.25rem 0.5rem;
+ pointer-events: none;
+}
+
+.chat-surface-layout-control:hover {
+ border-color: var(--color-border-hover);
+ background: var(--color-surface-hover);
+ color: var(--color-text-primary);
+}
+
+.chat-surface-layout-control:focus-visible {
+ outline: 2px solid var(--color-border-focus);
+ outline-offset: 1px;
+}
+
+.chat-surface-layout-control[aria-pressed='true'] {
+ border-color: var(--color-border-focus);
+ color: var(--color-action-primary);
+}
+
+.chat-surface-tabs__tab {
+ min-width: 3.5rem;
+ border: 0;
+ border-radius: 0.375rem;
+ background: transparent;
+ color: var(--color-text-secondary);
+ cursor: pointer;
+ font-size: 0.75rem;
+ font-weight: 500;
+ line-height: 1.25rem;
+ padding: 0.125rem 0.625rem;
+}
+
+.chat-surface-tabs__tab:hover {
+ background: var(--color-surface-hover);
+ color: var(--color-text-primary);
+}
+
+.chat-surface-tabs__tab:focus-visible {
+ outline: 2px solid var(--color-border-focus);
+ outline-offset: 1px;
+}
+
+.chat-surface-tabs__tab.is-active {
+ background: var(--color-surface-card);
+ color: var(--color-action-primary);
+ box-shadow: var(--effect-shadow-sm);
+}
+
+.chat-surface-view {
+ display: flex;
+ flex-direction: column;
+}
+
+.chat-surface-view--hidden {
+ display: none;
+}
+
+.trajectory-view-loading {
+ display: flex;
+ min-height: 12rem;
+ flex: 1 1 0;
+ align-items: center;
+ justify-content: center;
+ color: var(--color-text-secondary);
+ font-size: 0.8125rem;
+}
+
.app-toast-wrapper {
position: fixed;
left: 50%;
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index d96fe9ba50..54364412c1 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -4,7 +4,7 @@
* 应用主布局,整合所有组件
*/
-import { useState, useCallback, useEffect, useRef, Component, ReactNode, useMemo } from 'react';
+import { useState, useCallback, useEffect, useRef, Component, ReactNode, useMemo, lazy, Suspense } from 'react';
import { ChatPanel } from './components/ChatPanel';
import { SessionSidebar } from './components/SessionSidebar';
import { SkillPanel } from './components/SkillPanel';
@@ -100,8 +100,18 @@ import {
type ModelSetupGuideStep,
} from './features/modelSetupGuide/ModelSetupGuide';
import { isSetupGuideEnabled } from './features/modelSetupGuide/modelSetupGuideState';
+import {
+ SingleAgentSurface,
+ type ChatSurfaceView,
+} from './features/trajectory/SingleAgentSurface';
+import { resolveTrajectoryHostLayout } from './features/trajectory/trajectoryLayout';
import './App.css';
+const LazyTrajectoryPanel = lazy(async () => {
+ const module = await import('./features/trajectory/TrajectoryPanel');
+ return { default: module.TrajectoryPanel };
+});
+
const TEAM_SESSION_MODES = new Set(['team', 'team.plan', 'code.team']);
const PREVIEW_MODEL_SETUP_GUIDE = import.meta.env.DEV
&& new URLSearchParams(window.location.search).get('modelSetupGuide') === '1';
@@ -317,6 +327,10 @@ function AppContent() {
if (route.kind === 'chat-session') return route.sessionId;
return 'new';
});
+ const [chatSurfaceViews, setChatSurfaceViews] = useState<Record<string, ChatSurfaceView>>({});
+ const [trajectoryUiRequested, setTrajectoryUiRequested] = useState(false);
+ const [trajectorySessionsCollapsed, setTrajectorySessionsCollapsed] = useState(false);
+ const [trajectoryTasksCollapsed, setTrajectoryTasksCollapsed] = useState(false);
const enterpriseMode = isEnterprise();
const cronJobPullSyncEnabled = enterpriseMode && getWebTransport() === 'http';
@@ -545,6 +559,17 @@ function AppContent() {
)) ?? null;
}, [currentSession, projects, sessions, sessionId]);
const mode = useSessionStore((s) => s.runtimes[sessionId]?.mode ?? 'agent');
+ const chatSurfaceView: ChatSurfaceView = mode === 'agent'
+ ? (chatSurfaceViews[sessionId] ?? 'chat')
+ : 'chat';
+ const selectChatSurfaceView = useCallback((nextView: ChatSurfaceView) => {
+ if (nextView === 'trajectory') setTrajectoryUiRequested(true);
+ setChatSurfaceViews((current) => (
+ current[sessionId] === nextView
+ ? current
+ : { ...current, [sessionId]: nextView }
+ ));
+ }, [sessionId]);
const teamTaskEvents = useSessionStore((s) => s.runtimes[sessionId]?.teamTaskEvents ?? []);
const teamTasks = useSessionStore((s) => s.runtimes[sessionId]?.teamTasks ?? []);
const teamMembers = useSessionStore((s) => s.runtimes[sessionId]?.teamMembers ?? []);
@@ -688,6 +713,17 @@ function AppContent() {
// 单 agent 模式同样复用集群模式的展开布局(百分比宽度 + 可拖拽分割线),
// 避免右侧面板与聊天面板平分空间导致宽度与集群模式不一致;auto_harness 走收起态分支。
const isTeamAreaExpanded = mode !== 'auto_harness' && teamAreaExpanded && toolPanelHasContent;
+ const trajectoryTaskPanelAvailable = toolPanelHasContent || isRestoringTeamHistory;
+ const trajectoryHostLayout = resolveTrajectoryHostLayout(
+ mode,
+ chatSurfaceView,
+ trajectorySessionsCollapsed,
+ trajectoryTasksCollapsed,
+ isTeamAreaExpanded,
+ );
+ const hideTrajectorySessions = trajectoryHostLayout.hideSessions;
+ const hideTrajectoryTasks = trajectoryHostLayout.hideTasks;
+ const effectiveTeamAreaExpanded = trajectoryHostLayout.effectiveTeamAreaExpanded;
// WebSocket 连接 - provider 由后端配置决定 - provider 由后端配置决定,前端默认不在 URL query 传递
const {
@@ -2382,7 +2418,7 @@ function AppContent() {
) : null}
{/* Main Content */}
- <main className={`content ${activeNav === 'chat' ? 'content--chat' : ''} ${activeNav === 'a2aingress' ? 'content--a2a' : ''} ${isTeamAreaExpanded ? 'content--team-expanded' : ''}`}>
+ <main className={`content ${activeNav === 'chat' ? 'content--chat' : ''} ${activeNav === 'a2aingress' ? 'content--a2a' : ''} ${effectiveTeamAreaExpanded ? 'content--team-expanded' : ''}`}>
{configError && (
<div className="card mb-4">
<div className="text-sm text-text-muted">
@@ -2398,14 +2434,14 @@ function AppContent() {
{activeNav === 'chat' && (
<>
<div className="chat-layout flex-1 flex min-h-0 overflow-hidden">
- <ConversationSidebar
+ {hideTrajectorySessions ? null : <ConversationSidebar
activeSessionId={sessionId === NEW_CONVERSATION_ID ? null : sessionId}
onNew={(options) => requestSessionNavigation('new', options)}
onSelect={requestSessionNavigation}
onDelete={(session) => { setDialogError(null); setDeleteTarget(session); }}
onOpenCron={() => handleNavigate('cron')}
isCronActive={false}
- />
+ />}
<div className="chat-workspace flex-1 flex min-h-0 overflow-hidden">
{showConversationNotFound && (
<div className="flex-1 flex flex-col items-center justify-center gap-4">
@@ -2419,11 +2455,12 @@ function AppContent() {
)}
{/* Chat Panel - 在展开时可拖拽调整宽度 */}
<div
- className={`${showConversationNotFound ? 'hidden' : 'flex'} chat-layout__surface p-3 pt-0 flex-col min-w-0 min-h-0 ${isTeamAreaExpanded ? '' : 'flex-1'}`}
- style={isTeamAreaExpanded ? { width: `${chatPanelWidthPct}%` } : undefined}
+ className={`${showConversationNotFound ? 'hidden' : 'flex'} chat-layout__surface p-3 pt-0 flex-col min-w-0 min-h-0 ${effectiveTeamAreaExpanded ? '' : 'flex-1'}`}
+ style={effectiveTeamAreaExpanded ? { width: `${chatPanelWidthPct}%` } : undefined}
>
- <div className={`flex-1 min-h-0`}>
- <ChatPanel
+ <SingleAgentSurface
+ activeView={chatSurfaceView}
+ chat={<ChatPanel
onSendMessage={handleSendMessage}
onPersistMedia={handlePersistMedia}
onPersistDocuments={handlePersistDocuments}
@@ -2452,12 +2489,43 @@ function AppContent() {
onResumeGoal={resumeGoal}
onClearGoal={handleClearGoal}
onDrainTaskQueueIfIdle={drainTaskQueueIfIdle}
- />
- </div>
+ />}
+ chatLabel={t('nav.chat')}
+ mode={mode}
+ onViewChange={selectChatSurfaceView}
+ tabListLabel={t('trajectory.tabs.aria')}
+ trajectory={<Suspense fallback={<div className="trajectory-view-loading">{t('trajectory.loading')}</div>}>
+ <LazyTrajectoryPanel active={chatSurfaceView === 'trajectory'} sessionId={sessionId} />
+ </Suspense>}
+ trajectoryLabel={t('trajectory.tabs.trajectory')}
+ trajectoryControls={<>
+ <button
+ type="button"
+ className="chat-surface-layout-control"
+ aria-pressed={trajectorySessionsCollapsed}
+ aria-label={trajectorySessionsCollapsed ? t('trajectory.layout.showSessions') : t('trajectory.layout.hideSessions')}
+ onClick={() => setTrajectorySessionsCollapsed((collapsed) => !collapsed)}
+ data-testid="trajectory-toggle-sessions"
+ >
+ <span aria-hidden="true">{trajectorySessionsCollapsed ? '›' : '‹'}</span>
+ </button>
+ {trajectoryTaskPanelAvailable ? <button
+ type="button"
+ className="chat-surface-layout-control"
+ aria-pressed={trajectoryTasksCollapsed}
+ aria-label={trajectoryTasksCollapsed ? t('trajectory.layout.showTasks') : t('trajectory.layout.hideTasks')}
+ onClick={() => setTrajectoryTasksCollapsed((collapsed) => !collapsed)}
+ data-testid="trajectory-toggle-tasks"
+ >
+ <span aria-hidden="true">{trajectoryTasksCollapsed ? '‹' : '›'}</span>
+ </button> : null}
+ </>}
+ trajectoryRequested={trajectoryUiRequested}
+ />
</div>
{/* 可拖拽分割线 */}
- {isTeamAreaExpanded && !showConversationNotFound && (
+ {effectiveTeamAreaExpanded && !showConversationNotFound && (
<div
className="resize-divider"
onMouseDown={handleDividerMouseDown}
@@ -2465,7 +2533,7 @@ function AppContent() {
)}
{/* Tool Panel / Expanded Team Panel */}
- {(toolPanelHasContent || isRestoringTeamHistory) && !showConversationNotFound && (
+ {trajectoryTaskPanelAvailable && !hideTrajectoryTasks && !showConversationNotFound && (
<ToolPanel
sessionId={sessionId}
project={sessionProject}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/LICENSE.deepseek-harness b/jiuwenswarm/channels/web/frontend/src/features/trajectory/LICENSE.deepseek-harness
new file mode 100644
index 0000000000..c1f7a78e89
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/LICENSE.deepseek-harness
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 DeepSeek
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/NOTICE.md b/jiuwenswarm/channels/web/frontend/src/features/trajectory/NOTICE.md
new file mode 100644
index 0000000000..8e535157af
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/NOTICE.md
@@ -0,0 +1,7 @@
+# Trajectory source provenance
+
+English | [中文](NOTICE.zh.md)
+
+The migrated trajectory renderer adapts source and behavior from `packages/client/ui-trajectory` at DeepSeek Harness commit `99f6f02fecdb7dff40c3fbc9470f5907c29f74ca`. Theme token styles originate from `packages/client/ui-theme/src/styles`; Tooltip, Menu, JSON tree, Markdown rendering, syntax highlighting, KaTeX integration, and icons originate from `packages/client/ui-primitives/src` at the same commit.
+
+These sources are used under the bundled [MIT license](LICENSE.deepseek-harness). Detailed file mappings and JiuwenSwarm-specific adaptations are recorded in the `trajectory/`, `primitives/`, and `theme/` provenance files.
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/NOTICE.zh.md b/jiuwenswarm/channels/web/frontend/src/features/trajectory/NOTICE.zh.md
new file mode 100644
index 0000000000..6847dbfc79
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/NOTICE.zh.md
@@ -0,0 +1,7 @@
+# 轨迹源码来源
+
+[English](NOTICE.md) | 中文
+
+迁入的轨迹 renderer 改编自 DeepSeek Harness 提交 `99f6f02fecdb7dff40c3fbc9470f5907c29f74ca` 中的 `packages/client/ui-trajectory` 源代码与行为。主题 token 样式源自 `packages/client/ui-theme/src/styles`;Tooltip、Menu、JSON tree、Markdown 渲染、语法高亮、KaTeX 集成和图标源自同一提交中的 `packages/client/ui-primitives/src`。
+
+这些源码依据随附的 [MIT 许可证](LICENSE.deepseek-harness)使用。具体文件映射和 JiuwenSwarm 调整记录在 `trajectory/`、`primitives/`、`theme/` 目录的来源说明中。
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/SingleAgentSurface.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/SingleAgentSurface.tsx
new file mode 100644
index 0000000000..6f1a5ac64d
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/SingleAgentSurface.tsx
@@ -0,0 +1,97 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Stable host boundary for the single-Agent chat and trajectory surfaces. */
+
+import type { ReactNode } from 'react';
+
+export type ChatSurfaceView = 'chat' | 'trajectory';
+
+export interface SingleAgentSurfaceProps {
+ activeView: ChatSurfaceView;
+ chat: ReactNode;
+ chatLabel: string;
+ mode: string;
+ onViewChange: (view: ChatSurfaceView) => void;
+ tabListLabel: string;
+ trajectory: ReactNode;
+ trajectoryLabel: string;
+ trajectoryControls?: ReactNode;
+ trajectoryRequested: boolean;
+}
+
+/**
+ * Keep the chat subtree mounted while gating the trajectory subtree until its
+ * first explicit request. Non-agent modes never expose or mount trajectory UI.
+ */
+export function SingleAgentSurface({
+ activeView,
+ chat,
+ chatLabel,
+ mode,
+ onViewChange,
+ tabListLabel,
+ trajectory,
+ trajectoryControls,
+ trajectoryLabel,
+ trajectoryRequested,
+}: SingleAgentSurfaceProps) {
+ const agentMode = mode === 'agent';
+ const resolvedView: ChatSurfaceView = agentMode ? activeView : 'chat';
+
+ return (
+ <>
+ {agentMode ? (
+ <div className="chat-surface-toolbar">
+ <div
+ className="chat-surface-tabs"
+ role="tablist"
+ aria-label={tabListLabel}
+ data-testid="single-agent-surface-tabs"
+ >
+ <button
+ type="button"
+ role="tab"
+ aria-selected={resolvedView === 'chat'}
+ className={`chat-surface-tabs__tab ${resolvedView === 'chat' ? 'is-active' : ''}`}
+ onClick={() => onViewChange('chat')}
+ data-testid="single-agent-chat-tab"
+ >
+ {chatLabel}
+ </button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={resolvedView === 'trajectory'}
+ className={`chat-surface-tabs__tab ${resolvedView === 'trajectory' ? 'is-active' : ''}`}
+ onClick={() => onViewChange('trajectory')}
+ data-testid="single-agent-trajectory-tab"
+ >
+ {trajectoryLabel}
+ </button>
+ </div>
+ {resolvedView === 'trajectory' && trajectoryControls !== undefined ? (
+ <div className="chat-surface-layout-controls" data-testid="trajectory-layout-controls">
+ {trajectoryControls}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ <div
+ className={`chat-surface-view flex-1 min-h-0 ${resolvedView === 'chat' ? '' : 'chat-surface-view--hidden'}`}
+ aria-hidden={resolvedView !== 'chat'}
+ data-testid="single-agent-chat-view"
+ >
+ {chat}
+ </div>
+ {agentMode && trajectoryRequested ? (
+ <div
+ className={`chat-surface-view flex-1 min-h-0 ${resolvedView === 'trajectory' ? '' : 'chat-surface-view--hidden'}`}
+ aria-hidden={resolvedView !== 'trajectory'}
+ data-testid="single-agent-trajectory-view"
+ >
+ {trajectory}
+ </div>
+ ) : null}
+ </>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.module.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.module.css
new file mode 100644
index 0000000000..e02aa56eb5
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.module.css
@@ -0,0 +1,265 @@
+.root {
+ display: flex;
+ min-height: 0;
+ flex: 1 1 0;
+ flex-direction: column;
+ overflow: hidden;
+ border: 1px solid var(--color-border-default);
+ border-radius: 0.75rem;
+ background: var(--color-surface-card);
+}
+
+.header {
+ display: flex;
+ min-height: 2.5rem;
+ align-items: center;
+ justify-content: space-between;
+ gap: 0.75rem;
+ border-bottom: 1px solid var(--color-border-default);
+ padding: 0.375rem 0.75rem;
+}
+
+.summary {
+ min-width: 0;
+ color: var(--color-text-secondary);
+ font-size: 0.75rem;
+ line-height: 1.25rem;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.archiveActions {
+ display: flex;
+ flex: 0 0 auto;
+ align-items: center;
+ gap: 0.375rem;
+}
+
+.archiveInput {
+ display: none;
+}
+
+.archiveAction {
+ flex: 0 0 auto;
+ border: 1px solid var(--color-border-default);
+ border-radius: 0.375rem;
+ background: var(--color-action-secondary);
+ color: var(--color-action-secondary-text);
+ cursor: pointer;
+ font-size: 0.75rem;
+ line-height: 1.25rem;
+ padding: 0.125rem 0.625rem;
+}
+
+.archiveAction:hover {
+ border-color: var(--color-border-hover);
+ background: var(--color-surface-hover);
+}
+
+.archiveAction:disabled {
+ cursor: default;
+ opacity: 0.55;
+}
+
+.archiveError {
+ margin: 0;
+ border-bottom: 1px solid var(--color-border-default);
+ padding: 0.375rem 0.75rem;
+ font-size: 0.75rem;
+ line-height: 1.25rem;
+}
+
+.body {
+ display: flex;
+ min-height: 0;
+ flex: 1 1 0;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+.explorer {
+ min-height: 0;
+ flex: 1 1 0;
+}
+
+.state {
+ display: flex;
+ min-height: 12rem;
+ flex: 1 1 0;
+ align-items: center;
+ justify-content: center;
+ padding: 2rem;
+ text-align: center;
+}
+
+.stateContent {
+ max-width: 28rem;
+}
+
+.stateTitle {
+ margin: 0;
+ color: var(--color-text-primary);
+ font-size: 0.9375rem;
+ font-weight: 600;
+}
+
+.stateText {
+ margin: 0.5rem 0 0;
+ color: var(--color-text-secondary);
+ font-size: 0.8125rem;
+ line-height: 1.5;
+}
+
+.errorText {
+ color: var(--color-feedback-danger-text);
+}
+
+.retry {
+ margin-top: 0.875rem;
+ border: 1px solid var(--color-border-default);
+ border-radius: 0.375rem;
+ background: var(--color-action-secondary);
+ color: var(--color-action-secondary-text);
+ cursor: pointer;
+ font-size: 0.75rem;
+ padding: 0.375rem 0.75rem;
+}
+
+.rawInspector {
+ position: relative;
+ display: flex;
+ flex: 0 0 auto;
+ flex-direction: column;
+ overflow: hidden;
+ border-top: 1px solid var(--color-border-default);
+ background: var(--color-surface-muted);
+}
+
+.rawInspectorExpanded {
+ min-height: 7.5rem;
+ max-height: 60%;
+}
+
+.rawResizeHandle {
+ position: absolute;
+ z-index: 2;
+ top: -0.25rem;
+ right: 0;
+ left: 0;
+ height: 0.5rem;
+ cursor: ns-resize;
+ touch-action: none;
+}
+
+.rawResizeHandle::after {
+ position: absolute;
+ top: 0.1875rem;
+ right: 45%;
+ left: 45%;
+ height: 0.125rem;
+ border-radius: 999px;
+ background: var(--color-border-default);
+ content: '';
+}
+
+.rawResizeHandle:hover::after,
+.rawResizeHandle:focus-visible::after {
+ background: var(--color-border-focus);
+}
+
+.rawResizeHandle:focus-visible {
+ outline: 2px solid var(--color-border-focus);
+ outline-offset: -2px;
+}
+
+.rawSummary {
+ display: flex;
+ width: 100%;
+ flex: 0 0 auto;
+ align-items: center;
+ justify-content: space-between;
+ border: 0;
+ background: transparent;
+ cursor: pointer;
+ color: var(--color-text-secondary);
+ font-size: 0.75rem;
+ line-height: 1.25rem;
+ padding: 0.5rem 0.75rem;
+ text-align: left;
+ user-select: none;
+}
+
+.rawSummary:hover {
+ background: var(--color-surface-hover);
+ color: var(--color-text-primary);
+}
+
+.rawSummary:focus-visible {
+ outline: 2px solid var(--color-border-focus);
+ outline-offset: -2px;
+}
+
+.rawContent {
+ min-height: 0;
+ flex: 1 1 0;
+ overflow: auto;
+}
+
+.rawControls {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0 0.75rem 0.5rem;
+}
+
+.rawSelect {
+ min-width: 0;
+ flex: 1 1 0;
+ border: 1px solid var(--color-border-input);
+ border-radius: 0.375rem;
+ background: var(--color-surface-card);
+ color: var(--color-text-primary);
+ font-size: 0.75rem;
+ padding: 0.25rem 0.5rem;
+}
+
+.rawNotice {
+ margin: 0;
+ color: var(--color-text-secondary);
+ font-size: 0.75rem;
+ line-height: 1.45;
+ padding: 0 0.75rem 0.5rem;
+}
+
+.rawLoad {
+ margin: 0 0.75rem 0.625rem;
+ border: 1px solid var(--color-border-default);
+ border-radius: 0.375rem;
+ background: var(--color-action-secondary);
+ color: var(--color-action-secondary-text);
+ cursor: pointer;
+ font-size: 0.75rem;
+ padding: 0.375rem 0.75rem;
+}
+
+.rawLoad:disabled {
+ cursor: default;
+ opacity: 0.6;
+}
+
+.rawTree {
+ margin: 0 0.75rem 0.75rem;
+ border: 1px solid var(--color-border-default);
+ border-radius: 0.5rem;
+ background: var(--color-surface-card);
+}
+
+.warning {
+ color: var(--color-feedback-warning-text);
+}
+
+:global(body.trajectory-raw-resize-active) {
+ cursor: ns-resize;
+ user-select: none;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.tsx
new file mode 100644
index 0000000000..a99f6f0f5c
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.tsx
@@ -0,0 +1,986 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Session-scoped transport host for the migrated trajectory explorer. */
+
+import {
+ useCallback,
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+ type ChangeEvent,
+ type KeyboardEvent as ReactKeyboardEvent,
+ type PointerEvent as ReactPointerEvent,
+} from 'react';
+import { useTranslation } from 'react-i18next';
+import { webClient } from '../../services/webClient';
+import { saveBlob } from '../../utils/desktopSave';
+import { TrajectoryExplorer } from './client/TrajectoryExplorer';
+import { JsonTree } from './primitives/JsonTree';
+import { projectOtelTrajectory } from './projector/otel-trajectory-projector';
+import type { OtlpExportTraceServiceRequest } from './shared/otlp';
+import {
+ getTrajectoryRawRecord,
+ getTrajectoryArchive,
+ getTrajectoryTrace,
+ listTrajectoryTraceRevisions,
+ listTrajectoryTraces,
+ TrajectoryApiError,
+ type TrajectoryDetailRecord,
+ type TrajectoryTraceSummary,
+} from './trajectoryClient';
+import {
+ exitTrajectoryReplay,
+ parseTrajectoryArchive,
+ shouldCatchUpTrajectory,
+ trajectoryArchiveView,
+ type TrajectoryArchive,
+} from './trajectoryArchive';
+import {
+ collectHeadRefreshWindow,
+ collectRevisionRefreshWindow,
+ createTrajectoryOperationCoordinator,
+ createTrajectoryWindowState,
+ detailRecordIdentity,
+ resetTrajectoryWindowState,
+ selectSummariesNeedingLoad,
+ spansOf,
+ stageTrajectoryTracePages,
+ trajectoryContentMode,
+} from './trajectoryWindow';
+import {
+ RAW_INSPECTOR_DEFAULT_HEIGHT,
+ clampRawInspectorHeight,
+ rawInspectorHeightBounds,
+ rawInspectorKeyboardHeight,
+} from './trajectoryLayout';
+import css from './TrajectoryPanel.module.css';
+import './client/theme.css';
+
+const INITIAL_TRACE_LIMIT = 30;
+const DETAIL_LIMIT = 1000;
+const DETAIL_CONCURRENCY = 6;
+const MAX_ARCHIVE_BYTES = 128 * 1024 * 1024;
+
+interface TraceUpdatedPayload {
+ session_id?: unknown;
+ trace_id?: unknown;
+ revision?: unknown;
+ change_seq?: unknown;
+ store_epoch?: unknown;
+ lifecycle?: unknown;
+}
+
+interface RawInspectorResizeDrag {
+ pointerId: number;
+ startHeight: number;
+ startY: number;
+}
+
+export interface TrajectoryPanelProps {
+ active: boolean;
+ sessionId: string;
+}
+
+function recordLabel(record: OtlpExportTraceServiceRequest): string {
+ const span = spansOf(record)[0];
+ if (span === undefined) return 'OTLP record';
+ return `${span.name} · ${span.traceId.slice(0, 8)}/${span.spanId.slice(0, 8)}`;
+}
+
+function detailRecordLabel(record: TrajectoryDetailRecord): string {
+ if (record.otlp !== null) return recordLabel(record.otlp);
+ const identity = detailRecordIdentity(record);
+ const shortIdentity = identity === null
+ ? `record #${record.ingest_seq}`
+ : `${identity.slice(0, 8)}/${identity.slice(33, 41)}`;
+ const size = record.raw_size_bytes === undefined
+ ? ''
+ : ` · ${record.raw_size_bytes.toLocaleString()} B`;
+ return `Raw ${shortIdentity}${size}`;
+}
+
+function errorMessage(error: unknown, chinese: boolean): string {
+ if (error instanceof TrajectoryApiError && error.code === 'TRAJECTORY_DISABLED') {
+ return chinese ? '轨迹观测当前未启用。' : 'Trajectory observability is disabled.';
+ }
+ if (error instanceof Error && error.message) return error.message;
+ return chinese ? '轨迹数据加载失败。' : 'Failed to load trajectory data.';
+}
+
+export function TrajectoryPanel({
+ active,
+ sessionId,
+}: TrajectoryPanelProps) {
+ const { i18n } = useTranslation();
+ const chinese = (i18n.resolvedLanguage ?? i18n.language).toLowerCase().startsWith('zh');
+ const windowStateRef = useRef(createTrajectoryWindowState());
+ const operationCoordinatorRef = useRef(createTrajectoryOperationCoordinator());
+ const loadedSessionRef = useRef<string | null>(null);
+ const requestControllerRef = useRef<AbortController | null>(null);
+ const refreshPromiseRef = useRef<Promise<void> | null>(null);
+ const rebuildPromiseRef = useRef<Promise<boolean> | null>(null);
+ const hintFrameRef = useRef<number | null>(null);
+ const pendingHintsRef = useRef(new Map<string, number>());
+ const bodyRef = useRef<HTMLDivElement>(null);
+ const rawResizeDragRef = useRef<RawInspectorResizeDrag | null>(null);
+ const rawContentId = useId();
+ const archiveInputRef = useRef<HTMLInputElement>(null);
+ const [records, setRecords] = useState<OtlpExportTraceServiceRequest[]>([]);
+ const [rawRecords, setRawRecords] = useState<TrajectoryDetailRecord[]>([]);
+ const [lifecycleByRecordId, setLifecycleByRecordId] = useState(
+ new Map<string, 'running' | 'completed' | 'error'>(),
+ );
+ const [traceCount, setTraceCount] = useState(0);
+ const [hasEarlier, setHasEarlier] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [loadingEarlier, setLoadingEarlier] = useState(false);
+ const [exporting, setExporting] = useState(false);
+ const [replayArchive, setReplayArchive] = useState<TrajectoryArchive | null>(null);
+ const [archiveError, setArchiveError] = useState<string | null>(null);
+ const [invalidRecordSeen, setInvalidRecordSeen] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [rawSelection, setRawSelection] = useState('');
+ const [fetchedRaw, setFetchedRaw] = useState<{ identity: string; data: unknown } | null>(null);
+ const [rawLoading, setRawLoading] = useState(false);
+ const [rawError, setRawError] = useState<string | null>(null);
+ const [rawExpanded, setRawExpanded] = useState(true);
+ const [rawHeight, setRawHeight] = useState(RAW_INSPECTOR_DEFAULT_HEIGHT);
+ const [rawContainerHeightPx, setRawContainerHeightPx] = useState(600);
+
+ const copy = useMemo(() => chinese ? {
+ loading: '正在加载轨迹…',
+ emptyTitle: '暂无轨迹',
+ emptyText: '运行一次单 Agent 对话后,这里会展示模型、推理和工具调用轨迹。',
+ newTitle: '尚未创建会话',
+ newText: '发送第一条消息后可查看轨迹。',
+ retry: '重试',
+ importArchive: '导入',
+ exportArchive: '导出',
+ exportingArchive: '导出中…',
+ exitReplay: '退出复现',
+ replay: (sourceSession: string) => `只读复现 · ${sourceSession}`,
+ archiveTooLarge: '轨迹归档超过 128 MB,无法在浏览器中导入。',
+ summary: (traces: number, spans: number) => `${traces} 条 trace · ${spans} 个 OTel Span`,
+ invalid: '· 存在无法投影的原始记录',
+ raw: (count: number) => `原始 OTel 记录 (${count})`,
+ rawLabel: '选择原始 OTel 记录',
+ rawLoad: '按需加载原始记录',
+ rawLoading: '正在加载原始记录…',
+ rawTooLarge: '该 Span 超过详情投影预算,未自动载入;可按需读取原始数据。',
+ rawInvalid: '该记录无法按 OTLP JSON 投影;可按需查看原始内容。',
+ rawOnly: '当前 trace 只有未投影的原始记录,可在下方按需查看。',
+ rawCollapse: '收起原始 OTel 面板',
+ rawExpand: '展开原始 OTel 面板',
+ rawResize: '调整原始 OTel 面板高度',
+ toolbar: {
+ 'toolbar.aria': '轨迹工具栏',
+ 'toolbar.duration': '时长',
+ 'toolbar.useActualDuration': '使用实际时长',
+ 'toolbar.useEqualWidth': '使用等宽操作',
+ 'toolbar.actualTime': '实际时间',
+ 'toolbar.turns': '轮次',
+ 'toolbar.expandTurns': '展开所有轮次',
+ 'toolbar.collapseTurns': '折叠所有轮次',
+ 'toolbar.calls': '调用',
+ 'toolbar.expandCalls': '展开所有调用',
+ 'toolbar.collapseCalls': '折叠所有调用',
+ 'toolbar.search': '搜索轨迹',
+ 'toolbar.searchPlaceholder': '搜索',
+ },
+ } : {
+ loading: 'Loading trajectory…',
+ emptyTitle: 'No trajectory yet',
+ emptyText: 'Run a single-Agent conversation to see model, reasoning, and tool traces here.',
+ newTitle: 'No conversation yet',
+ newText: 'Send the first message to view its trajectory.',
+ retry: 'Retry',
+ importArchive: 'Import',
+ exportArchive: 'Export',
+ exportingArchive: 'Exporting…',
+ exitReplay: 'Exit replay',
+ replay: (sourceSession: string) => `Read-only replay · ${sourceSession}`,
+ archiveTooLarge: 'The trajectory archive exceeds the 128 MB browser import limit.',
+ summary: (traces: number, spans: number) => `${traces} traces · ${spans} OTel spans`,
+ invalid: '· Some raw records could not be projected',
+ raw: (count: number) => `Raw OTel records (${count})`,
+ rawLabel: 'Select a raw OTel record',
+ rawLoad: 'Load raw record on demand',
+ rawLoading: 'Loading raw record…',
+ rawTooLarge: 'This Span exceeds the detail projection budget and was not loaded automatically.',
+ rawInvalid: 'This record could not be projected as OTLP JSON. Its raw content remains available.',
+ rawOnly: 'This trace currently contains only unprojected raw records.',
+ rawCollapse: 'Collapse raw OTel panel',
+ rawExpand: 'Expand raw OTel panel',
+ rawResize: 'Resize raw OTel panel height',
+ toolbar: undefined,
+ }, [chinese]);
+
+ const publish = useCallback((generation: number) => {
+ if (!operationCoordinatorRef.current.isCurrent(generation)) return;
+ const nextRecords = [...windowStateRef.current.buckets.values()].flatMap(bucket => (
+ [...bucket.records.values()]
+ ));
+ const nextRawRecords = [...windowStateRef.current.buckets.values()].flatMap(bucket => (
+ [...bucket.rawRecords.values()]
+ ));
+ setRecords(nextRecords);
+ setRawRecords(nextRawRecords);
+ setLifecycleByRecordId(new Map(
+ [...windowStateRef.current.buckets.values()].flatMap(bucket => (
+ [...(bucket.versions ?? [])].map(([identity, version]) => (
+ [identity, version.lifecycle] as const
+ ))
+ )),
+ ));
+ setTraceCount(windowStateRef.current.buckets.size);
+ }, []);
+
+ const clearPublishedWindow = useCallback(() => {
+ resetTrajectoryWindowState(windowStateRef.current);
+ setRecords([]);
+ setRawRecords([]);
+ setLifecycleByRecordId(new Map());
+ setTraceCount(0);
+ setHasEarlier(false);
+ setInvalidRecordSeen(false);
+ setError(null);
+ setRawSelection('');
+ setFetchedRaw(null);
+ setRawLoading(false);
+ setRawError(null);
+ }, []);
+
+ const loadTrace = useCallback(async (
+ traceId: string,
+ targetRevision: number,
+ signal: AbortSignal,
+ generation: number,
+ ) => {
+ if (!operationCoordinatorRef.current.isCurrent(generation)) return;
+ const current = windowStateRef.current.buckets.get(traceId);
+ if (current !== undefined && current.revision >= targetRevision) return;
+ const staged = await stageTrajectoryTracePages(
+ current,
+ signal,
+ (sinceRevision, pageSignal) => getTrajectoryTrace(sessionId, traceId, {
+ signal: pageSignal,
+ sinceRevision,
+ limit: DETAIL_LIMIT,
+ }),
+ );
+ if (staged === null
+ || signal.aborted
+ || !operationCoordinatorRef.current.isCurrent(generation)) return;
+ const latest = windowStateRef.current.buckets.get(traceId);
+ if (latest !== current
+ && latest !== undefined
+ && latest.revision > staged.bucket.revision) return;
+ windowStateRef.current.buckets.set(traceId, staged.bucket);
+ if (staged.invalidRecordSeen) setInvalidRecordSeen(true);
+ }, [sessionId]);
+
+ const loadSummaries = useCallback(async (
+ summaries: readonly TrajectoryTraceSummary[],
+ signal: AbortSignal,
+ generation: number,
+ ) => {
+ for (let offset = 0; offset < summaries.length; offset += DETAIL_CONCURRENCY) {
+ const batch = summaries.slice(offset, offset + DETAIL_CONCURRENCY);
+ await Promise.all(batch.map(summary => loadTrace(
+ summary.trace_id,
+ summary.revision,
+ signal,
+ generation,
+ )));
+ if (signal.aborted
+ || !operationCoordinatorRef.current.isCurrent(generation)) return;
+ publish(generation);
+ }
+ }, [loadTrace, publish]);
+
+ const rebuildFromHead = useCallback((signal: AbortSignal): Promise<boolean> => {
+ if (rebuildPromiseRef.current !== null) return rebuildPromiseRef.current;
+ const coordinator = operationCoordinatorRef.current;
+ const generation = coordinator.invalidate(() => setLoadingEarlier(false));
+ clearPublishedWindow();
+ setLoading(true);
+ const operation = (async () => {
+ try {
+ const page = await listTrajectoryTraces(sessionId, {
+ signal,
+ cursor: null,
+ limit: INITIAL_TRACE_LIMIT,
+ });
+ if (signal.aborted || !coordinator.isCurrent(generation)) return false;
+ await loadSummaries(page.items, signal, generation);
+ if (signal.aborted || !coordinator.isCurrent(generation)) return false;
+ const windowState = windowStateRef.current;
+ windowState.storeEpoch = page.store_epoch;
+ windowState.pageCursor = page.next_cursor;
+ windowState.revisionCursor = page.revision_cursor;
+ windowState.listWindowInitialized = true;
+ setHasEarlier(page.next_cursor !== null);
+ setError(null);
+ return true;
+ } catch (rebuildError) {
+ if (!signal.aborted && coordinator.isCurrent(generation)) {
+ setError(errorMessage(rebuildError, chinese));
+ }
+ return false;
+ } finally {
+ if (coordinator.isCurrent(generation)) setLoading(false);
+ }
+ })();
+ rebuildPromiseRef.current = operation;
+ void operation.finally(() => {
+ if (rebuildPromiseRef.current === operation) rebuildPromiseRef.current = null;
+ });
+ return operation;
+ }, [chinese, clearPublishedWindow, loadSummaries, sessionId]);
+
+ const refreshLatest = useCallback(async () => {
+ if (!active || sessionId === 'new' || requestControllerRef.current?.signal.aborted) return;
+ if (refreshPromiseRef.current !== null) return refreshPromiseRef.current;
+ const signal = requestControllerRef.current?.signal;
+ if (signal === undefined) return;
+ const operation = (async () => {
+ try {
+ const coordinator = operationCoordinatorRef.current;
+ const generation = coordinator.currentGeneration();
+ const earlier = coordinator.pendingLoadEarlier(generation);
+ if (earlier !== null) await earlier;
+ if (signal.aborted || !coordinator.isCurrent(generation)) return;
+ const expectedStoreEpoch = windowStateRef.current.storeEpoch;
+ if (expectedStoreEpoch === null) {
+ await rebuildFromHead(signal);
+ return;
+ }
+ const loadedRevisions = new Map<string, number>(
+ [...windowStateRef.current.buckets]
+ .map(([traceId, bucket]): [string, number] => [traceId, bucket.revision]),
+ );
+ const headWindow = await collectHeadRefreshWindow(
+ loadedRevisions,
+ expectedStoreEpoch,
+ signal,
+ (cursor, pageSignal) => listTrajectoryTraces(sessionId, {
+ signal: pageSignal,
+ cursor,
+ limit: INITIAL_TRACE_LIMIT,
+ }),
+ );
+ if (headWindow === null
+ || signal.aborted
+ || !coordinator.isCurrent(generation)) return;
+ if (headWindow.reset) {
+ await rebuildFromHead(signal);
+ return;
+ }
+ const feedStart = windowStateRef.current.revisionCursor ?? headWindow.revisionCursor;
+ const revisionWindow = await collectRevisionRefreshWindow(
+ feedStart,
+ expectedStoreEpoch,
+ signal,
+ (afterRevision, pageSignal) => listTrajectoryTraceRevisions(sessionId, {
+ signal: pageSignal,
+ afterRevision,
+ limit: 100,
+ }),
+ );
+ if (revisionWindow === null
+ || signal.aborted
+ || !coordinator.isCurrent(generation)) return;
+ if (revisionWindow.reset) {
+ await rebuildFromHead(signal);
+ return;
+ }
+ const summaries = selectSummariesNeedingLoad(
+ loadedRevisions,
+ headWindow.summaries,
+ revisionWindow.summaries,
+ );
+ await loadSummaries(summaries, signal, generation);
+ if (signal.aborted
+ || !coordinator.isCurrent(generation)
+ || windowStateRef.current.storeEpoch !== expectedStoreEpoch) return;
+ if (!windowStateRef.current.listWindowInitialized || loadedRevisions.size === 0) {
+ windowStateRef.current.pageCursor = headWindow.firstPageNextCursor;
+ windowStateRef.current.listWindowInitialized = true;
+ setHasEarlier(headWindow.firstPageNextCursor !== null);
+ }
+ windowStateRef.current.revisionCursor = revisionWindow.nextCursor;
+ setError(null);
+ } catch (refreshError) {
+ if (!signal.aborted) setError(errorMessage(refreshError, chinese));
+ }
+ })();
+ refreshPromiseRef.current = operation;
+ try {
+ await operation;
+ } finally {
+ if (refreshPromiseRef.current === operation) {
+ refreshPromiseRef.current = null;
+ }
+ }
+ }, [active, chinese, loadSummaries, rebuildFromHead, sessionId]);
+
+ const flushTraceHints = useCallback(async () => {
+ const signal = requestControllerRef.current?.signal;
+ if (!active || signal === undefined || signal.aborted) return;
+ const hints = [...pendingHintsRef.current];
+ pendingHintsRef.current.clear();
+ if (hints.length === 0) return;
+ const coordinator = operationCoordinatorRef.current;
+ const generation = coordinator.currentGeneration();
+ await Promise.all(hints.map(([traceId, revision]) => loadTrace(
+ traceId,
+ revision,
+ signal,
+ generation,
+ )));
+ if (signal.aborted || !coordinator.isCurrent(generation)) return;
+ publish(generation);
+ }, [active, loadTrace, publish]);
+
+ useEffect(() => {
+ requestControllerRef.current?.abort();
+ refreshPromiseRef.current = null;
+ rebuildPromiseRef.current = null;
+ operationCoordinatorRef.current.invalidate(() => setLoadingEarlier(false));
+ const controller = new AbortController();
+ requestControllerRef.current = controller;
+ setRawLoading(false);
+ pendingHintsRef.current.clear();
+ if (hintFrameRef.current !== null) {
+ window.cancelAnimationFrame(hintFrameRef.current);
+ hintFrameRef.current = null;
+ }
+ const sessionChanged = loadedSessionRef.current !== sessionId;
+ if (sessionChanged) {
+ loadedSessionRef.current = sessionId;
+ clearPublishedWindow();
+ }
+ if (!active || sessionId === 'new') {
+ setLoading(false);
+ return () => controller.abort();
+ }
+ if (!sessionChanged && windowStateRef.current.storeEpoch !== null) {
+ setLoading(false);
+ void refreshLatest();
+ return () => controller.abort();
+ }
+ const operation = rebuildFromHead(controller.signal).then(() => undefined);
+ refreshPromiseRef.current = operation;
+ void operation.finally(() => {
+ if (refreshPromiseRef.current === operation) refreshPromiseRef.current = null;
+ });
+ return () => controller.abort();
+ }, [active, clearPublishedWindow, rebuildFromHead, refreshLatest, sessionId]);
+
+ useEffect(() => {
+ if (!active || sessionId === 'new' || replayArchive !== null) return undefined;
+ const unsubscribe = webClient.on<TraceUpdatedPayload>('trace.updated', (event) => {
+ if (event.payload.session_id !== sessionId) return;
+ const traceId = event.payload.trace_id;
+ const revisionValue = event.payload.revision ?? event.payload.change_seq;
+ const revision = typeof revisionValue === 'number'
+ ? revisionValue
+ : typeof revisionValue === 'string' && /^\d+$/.test(revisionValue)
+ ? Number(revisionValue)
+ : Number.NaN;
+ const eventEpoch = event.payload.store_epoch;
+ const currentEpoch = windowStateRef.current.storeEpoch;
+ if (typeof eventEpoch === 'string'
+ && currentEpoch !== null
+ && eventEpoch !== currentEpoch) {
+ const signal = requestControllerRef.current?.signal;
+ if (signal !== undefined && !signal.aborted) void rebuildFromHead(signal);
+ return;
+ }
+ if (typeof traceId !== 'string'
+ || !/^[0-9a-f]{32}$/.test(traceId)
+ || !Number.isSafeInteger(revision)
+ || revision < 0) {
+ void refreshLatest();
+ return;
+ }
+ const prior = pendingHintsRef.current.get(traceId) ?? -1;
+ if (revision > prior) pendingHintsRef.current.set(traceId, revision);
+ if (hintFrameRef.current !== null) return;
+ hintFrameRef.current = window.requestAnimationFrame(() => {
+ hintFrameRef.current = null;
+ void flushTraceHints();
+ });
+ });
+ let previousConnectionState = webClient.getState();
+ const unsubscribeState = webClient.onStateChange((nextConnectionState) => {
+ if (shouldCatchUpTrajectory(previousConnectionState, nextConnectionState)) {
+ void refreshLatest();
+ }
+ previousConnectionState = nextConnectionState;
+ });
+ return () => {
+ unsubscribe();
+ unsubscribeState();
+ if (hintFrameRef.current !== null) {
+ window.cancelAnimationFrame(hintFrameRef.current);
+ hintFrameRef.current = null;
+ }
+ pendingHintsRef.current.clear();
+ };
+ }, [active, flushTraceHints, rebuildFromHead, refreshLatest, replayArchive, sessionId]);
+
+ const loadEarlier = useCallback((): Promise<boolean> => {
+ const signal = requestControllerRef.current?.signal;
+ if (!active || replayArchive !== null || signal === undefined || signal.aborted) {
+ return Promise.resolve(false);
+ }
+ const coordinator = operationCoordinatorRef.current;
+ return coordinator.runLoadEarlier(async (generation) => {
+ try {
+ const runningRefresh = refreshPromiseRef.current;
+ if (runningRefresh !== null) await runningRefresh;
+ if (signal.aborted || !coordinator.isCurrent(generation)) return false;
+ const cursor = windowStateRef.current.pageCursor;
+ const expectedStoreEpoch = windowStateRef.current.storeEpoch;
+ if (cursor === null || expectedStoreEpoch === null) return false;
+ const page = await listTrajectoryTraces(sessionId, {
+ signal,
+ cursor,
+ limit: INITIAL_TRACE_LIMIT,
+ });
+ if (signal.aborted || !coordinator.isCurrent(generation)) return false;
+ if (page.store_epoch !== expectedStoreEpoch) {
+ await rebuildFromHead(signal);
+ return false;
+ }
+ const loadedRevisions = new Map<string, number>(
+ [...windowStateRef.current.buckets]
+ .map(([traceId, bucket]): [string, number] => [traceId, bucket.revision]),
+ );
+ const summaries = selectSummariesNeedingLoad(loadedRevisions, page.items);
+ await loadSummaries(summaries, signal, generation);
+ if (signal.aborted
+ || !coordinator.isCurrent(generation)
+ || windowStateRef.current.storeEpoch !== expectedStoreEpoch
+ || windowStateRef.current.pageCursor !== cursor) return false;
+ windowStateRef.current.pageCursor = page.next_cursor;
+ windowStateRef.current.listWindowInitialized = true;
+ setHasEarlier(page.next_cursor !== null);
+ setError(null);
+ return page.items.length > 0;
+ } catch (loadError) {
+ if (!signal.aborted && coordinator.isCurrent(generation)) {
+ setError(errorMessage(loadError, chinese));
+ }
+ return false;
+ }
+ }, setLoadingEarlier);
+ }, [active, chinese, loadSummaries, rebuildFromHead, replayArchive, sessionId]);
+
+ const replayView = useMemo(
+ () => replayArchive === null ? null : trajectoryArchiveView(replayArchive),
+ [replayArchive],
+ );
+ const displayedRecords = replayView?.records ?? records;
+ const displayedRawRecords = replayView?.rawRecords ?? rawRecords;
+ const displayedLifecycle = replayView?.lifecycleByRecordId ?? lifecycleByRecordId;
+ const displayedTraceCount = replayView?.traceCount ?? traceCount;
+ const displayedInvalidRecordSeen = replayView?.invalidRecordSeen ?? invalidRecordSeen;
+
+ useEffect(() => {
+ if (displayedRawRecords.length === 0) {
+ windowStateRef.current.rawSelection = '';
+ setRawSelection('');
+ return;
+ }
+ const identities = displayedRawRecords
+ .map(detailRecordIdentity)
+ .filter((value): value is string => value !== null);
+ if (!identities.includes(rawSelection)) {
+ const nextSelection = identities[0] ?? '';
+ windowStateRef.current.rawSelection = nextSelection;
+ setRawSelection(nextSelection);
+ }
+ }, [displayedRawRecords, rawSelection]);
+
+ useEffect(() => {
+ setFetchedRaw(null);
+ setRawError(null);
+ setRawLoading(false);
+ }, [rawSelection, replayArchive, sessionId]);
+
+ const snapshot = useMemo(() => projectOtelTrajectory(displayedRecords, {
+ lifecycleByRecordId: displayedLifecycle,
+ }), [displayedLifecycle, displayedRecords]);
+ const rawRecord = useMemo(
+ () => displayedRawRecords.find(record => detailRecordIdentity(record) === rawSelection),
+ [displayedRawRecords, rawSelection],
+ );
+ const rawData = replayView === null
+ ? rawRecord?.otlp ?? (fetchedRaw?.identity === rawSelection ? fetchedRaw.data : undefined)
+ : replayView.rawDataByRecordId.get(rawSelection);
+
+ const loadSelectedRaw = useCallback(async () => {
+ if (replayArchive !== null) return;
+ if (rawRecord?.trace_id === undefined || rawRecord.span_id === undefined) return;
+ const signal = requestControllerRef.current?.signal;
+ if (signal === undefined || signal.aborted) return;
+ const generation = operationCoordinatorRef.current.currentGeneration();
+ setRawLoading(true);
+ setRawError(null);
+ try {
+ const data = await getTrajectoryRawRecord(
+ sessionId,
+ rawRecord.trace_id,
+ rawRecord.span_id,
+ { signal },
+ );
+ if (!signal.aborted
+ && operationCoordinatorRef.current.isCurrent(generation)) {
+ setFetchedRaw({ identity: rawSelection, data });
+ }
+ } catch (loadError) {
+ if (!signal.aborted
+ && operationCoordinatorRef.current.isCurrent(generation)) {
+ setRawError(errorMessage(loadError, chinese));
+ }
+ } finally {
+ if (!signal.aborted
+ && operationCoordinatorRef.current.isCurrent(generation)) {
+ setRawLoading(false);
+ }
+ }
+ }, [chinese, rawRecord, rawSelection, replayArchive, sessionId]);
+
+ const exportArchive = useCallback(async () => {
+ if (exporting || (replayArchive === null && sessionId === 'new')) return;
+ const signal = requestControllerRef.current?.signal;
+ if (replayArchive === null && (signal === undefined || signal.aborted)) return;
+ setExporting(true);
+ setArchiveError(null);
+ try {
+ const archive = replayArchive ?? parseTrajectoryArchive(
+ await getTrajectoryArchive(sessionId, { signal }),
+ );
+ const safeSession = archive.session_id.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80) || 'session';
+ const blob = new Blob([`${JSON.stringify(archive, null, 2)}\n`], {
+ type: 'application/json;charset=utf-8',
+ });
+ const outcome = await saveBlob(blob, `trajectory-${safeSession}.json`);
+ if (outcome === 'failed') throw new Error('Trajectory archive could not be saved');
+ } catch (exportError) {
+ if (!(exportError instanceof DOMException && exportError.name === 'AbortError')) {
+ setArchiveError(errorMessage(exportError, chinese));
+ }
+ } finally {
+ setExporting(false);
+ }
+ }, [chinese, exporting, replayArchive, sessionId]);
+
+ const importArchive = useCallback(async (event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.currentTarget.files?.[0];
+ event.currentTarget.value = '';
+ if (file === undefined) return;
+ setArchiveError(null);
+ try {
+ if (file.size > MAX_ARCHIVE_BYTES) throw new Error(copy.archiveTooLarge);
+ const archive = parseTrajectoryArchive(await file.text());
+ setReplayArchive(archive);
+ setRawSelection('');
+ setFetchedRaw(null);
+ setRawError(null);
+ } catch (importError) {
+ setArchiveError(errorMessage(importError, chinese));
+ }
+ }, [chinese, copy.archiveTooLarge]);
+
+ const exitReplay = useCallback(() => {
+ const transition = exitTrajectoryReplay(replayArchive);
+ setReplayArchive(transition.archive);
+ setArchiveError(null);
+ setRawSelection('');
+ if (transition.catchUpLiveRevision) void refreshLatest();
+ }, [refreshLatest, replayArchive]);
+
+ const rawContainerHeight = useCallback(() => (
+ bodyRef.current?.getBoundingClientRect().height ?? 600
+ ), []);
+
+ useEffect(() => {
+ const body = bodyRef.current;
+ if (body === null || typeof ResizeObserver === 'undefined') return undefined;
+ const syncHeight = () => {
+ const nextContainerHeight = body.getBoundingClientRect().height;
+ if (nextContainerHeight <= 0) return;
+ setRawContainerHeightPx(nextContainerHeight);
+ setRawHeight(current => clampRawInspectorHeight(current, nextContainerHeight));
+ };
+ syncHeight();
+ const observer = new ResizeObserver(syncHeight);
+ observer.observe(body);
+ return () => observer.disconnect();
+ }, []);
+
+ const handleRawResizePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
+ if (event.button !== 0 || rawResizeDragRef.current !== null) return;
+ event.preventDefault();
+ event.currentTarget.setPointerCapture(event.pointerId);
+ document.body.classList.add('trajectory-raw-resize-active');
+ rawResizeDragRef.current = {
+ pointerId: event.pointerId,
+ startHeight: rawHeight,
+ startY: event.clientY,
+ };
+ }, [rawHeight]);
+
+ const handleRawResizePointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
+ const drag = rawResizeDragRef.current;
+ if (drag === null || drag.pointerId !== event.pointerId) return;
+ const nextHeight = drag.startHeight + drag.startY - event.clientY;
+ setRawHeight(clampRawInspectorHeight(nextHeight, rawContainerHeight()));
+ }, [rawContainerHeight]);
+
+ const clearRawResize = useCallback((pointerId?: number) => {
+ if (pointerId !== undefined && rawResizeDragRef.current?.pointerId !== pointerId) return;
+ rawResizeDragRef.current = null;
+ document.body.classList.remove('trajectory-raw-resize-active');
+ }, []);
+
+ const finishRawResize = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
+ clearRawResize(event.pointerId);
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ }
+ }, [clearRawResize]);
+
+ const handleRawResizeKeyDown = useCallback((event: ReactKeyboardEvent<HTMLDivElement>) => {
+ const nextHeight = rawInspectorKeyboardHeight(
+ rawHeight,
+ event.key,
+ rawContainerHeight(),
+ );
+ if (nextHeight === null) return;
+ event.preventDefault();
+ setRawHeight(nextHeight);
+ }, [rawContainerHeight, rawHeight]);
+
+ useEffect(() => () => {
+ document.body.classList.remove('trajectory-raw-resize-active');
+ }, []);
+
+ const rawHeightBounds = rawInspectorHeightBounds(rawContainerHeightPx);
+
+ const rawInspector = displayedRawRecords.length === 0 ? null : (
+ <section
+ className={`${css.rawInspector} ${rawExpanded ? css.rawInspectorExpanded : ''} jiuwenTrajectoryTheme`}
+ data-trajectory-theme="light"
+ data-testid="trajectory-raw-inspector"
+ // The migrated theme gives every `.jiuwenTrajectoryTheme` root
+ // `height: 100%`. Override it in both states so a collapsed inspector is
+ // only its summary row instead of filling the trajectory body.
+ style={{ height: rawExpanded ? `${rawHeight}px` : 'auto' }}
+ >
+ {rawExpanded ? (
+ <div
+ className={css.rawResizeHandle}
+ role="separator"
+ aria-label={copy.rawResize}
+ aria-orientation="horizontal"
+ aria-valuemin={rawHeightBounds.min}
+ aria-valuemax={rawHeightBounds.max}
+ aria-valuenow={rawHeight}
+ tabIndex={0}
+ onKeyDown={handleRawResizeKeyDown}
+ onPointerDown={handleRawResizePointerDown}
+ onPointerMove={handleRawResizePointerMove}
+ onPointerUp={finishRawResize}
+ onPointerCancel={finishRawResize}
+ onLostPointerCapture={(event) => clearRawResize(event.pointerId)}
+ data-testid="trajectory-raw-resize-handle"
+ />
+ ) : null}
+ <button
+ type="button"
+ className={css.rawSummary}
+ aria-controls={rawContentId}
+ aria-expanded={rawExpanded}
+ title={rawExpanded ? copy.rawCollapse : copy.rawExpand}
+ onClick={() => setRawExpanded(expanded => !expanded)}
+ data-testid="trajectory-raw-toggle"
+ >
+ <span>{copy.raw(displayedRawRecords.length)}</span>
+ <span aria-hidden="true">{rawExpanded ? '▾' : '▴'}</span>
+ </button>
+ {rawExpanded ? (
+ <div id={rawContentId} className={css.rawContent}>
+ <div className={css.rawControls}>
+ <select
+ className={css.rawSelect}
+ aria-label={copy.rawLabel}
+ value={rawSelection}
+ onChange={(event) => {
+ const nextSelection = event.currentTarget.value;
+ windowStateRef.current.rawSelection = nextSelection;
+ setRawSelection(nextSelection);
+ }}
+ >
+ {displayedRawRecords.map((record) => {
+ const identity = detailRecordIdentity(record);
+ return identity === null ? null : (
+ <option key={identity} value={identity}>{detailRecordLabel(record)}</option>
+ );
+ })}
+ </select>
+ </div>
+ {rawRecord?.projection_omitted === 'record_too_large' ? (
+ <p className={css.rawNotice}>{copy.rawTooLarge}</p>
+ ) : rawRecord?.raw_valid === false ? (
+ <p className={css.rawNotice}>{copy.rawInvalid}</p>
+ ) : null}
+ {rawData === undefined && rawRecord !== undefined && replayArchive === null ? (
+ <button
+ className={css.rawLoad}
+ type="button"
+ disabled={rawLoading}
+ onClick={() => { void loadSelectedRaw(); }}
+ >
+ {rawLoading ? copy.rawLoading : copy.rawLoad}
+ </button>
+ ) : null}
+ {rawError === null ? null : <p className={`${css.rawNotice} ${css.errorText}`}>{rawError}</p>}
+ {rawData === undefined ? null : (
+ <JsonTree
+ data={typeof rawData === 'object' && rawData !== null ? rawData : { raw: rawData }}
+ className={css.rawTree}
+ label={copy.rawLabel}
+ expandTopLevel={false}
+ />
+ )}
+ </div>
+ ) : null}
+ </section>
+ );
+
+ const contentMode = trajectoryContentMode({
+ sessionId: replayArchive?.session_id ?? sessionId,
+ loading: replayArchive === null ? loading : false,
+ error: replayArchive === null ? error : null,
+ projectedCount: displayedRecords.length,
+ rawCount: displayedRawRecords.length,
+ });
+ let content;
+ if (contentMode === 'new') {
+ content = (
+ <div className={css.state}>
+ <div className={css.stateContent}>
+ <h2 className={css.stateTitle}>{copy.newTitle}</h2>
+ <p className={css.stateText}>{copy.newText}</p>
+ </div>
+ </div>
+ );
+ } else if (contentMode === 'loading') {
+ content = <div className={css.state}><p className={css.stateText}>{copy.loading}</p></div>;
+ } else if (contentMode === 'blocking-error') {
+ content = (
+ <div className={css.state}>
+ <div className={css.stateContent}>
+ <h2 className={css.stateTitle}>{copy.emptyTitle}</h2>
+ <p className={`${css.stateText} ${css.errorText}`}>{error}</p>
+ <button className={css.retry} type="button" onClick={() => { void refreshLatest(); }}>
+ {copy.retry}
+ </button>
+ </div>
+ </div>
+ );
+ } else if (contentMode === 'empty') {
+ content = (
+ <div className={css.state}>
+ <div className={css.stateContent}>
+ <h2 className={css.stateTitle}>{copy.emptyTitle}</h2>
+ <p className={css.stateText}>{copy.emptyText}</p>
+ </div>
+ </div>
+ );
+ } else {
+ content = (
+ <>
+ {error !== null && replayArchive === null && displayedRecords.length === 0 ? (
+ <p className={`${css.rawNotice} ${css.errorText}`}>{error}</p>
+ ) : null}
+ {displayedRecords.length === 0 ? (
+ <div className={css.state}><p className={css.stateText}>{copy.rawOnly}</p></div>
+ ) : (
+ <TrajectoryExplorer
+ snapshot={snapshot}
+ loading={replayArchive === null ? loading : false}
+ loadingEarlier={replayArchive === null ? loadingEarlier : false}
+ hasEarlier={replayArchive === null ? hasEarlier : false}
+ loadEarlier={loadEarlier}
+ error={replayArchive === null ? error : null}
+ messages={copy.toolbar}
+ colorMode="light"
+ className={css.explorer}
+ />
+ )}
+ {rawInspector}
+ </>
+ );
+ }
+
+ return (
+ <section className={css.root} aria-label={chinese ? '轨迹' : 'Trajectory'}>
+ <header className={css.header}>
+ <div className={css.summary}>
+ {replayArchive === null
+ ? copy.summary(displayedTraceCount, displayedRawRecords.length || displayedRecords.length)
+ : copy.replay(replayArchive.session_id)}
+ {displayedInvalidRecordSeen ? <span className={css.warning}> {copy.invalid}</span> : null}
+ </div>
+ <div className={css.archiveActions}>
+ <input
+ ref={archiveInputRef}
+ className={css.archiveInput}
+ type="file"
+ accept="application/json,.json"
+ onChange={(event) => { void importArchive(event); }}
+ data-testid="trajectory-archive-input"
+ />
+ <button
+ type="button"
+ className={css.archiveAction}
+ onClick={() => archiveInputRef.current?.click()}
+ data-testid="trajectory-archive-import"
+ >
+ {copy.importArchive}
+ </button>
+ <button
+ type="button"
+ className={css.archiveAction}
+ disabled={exporting || (replayArchive === null && sessionId === 'new')}
+ onClick={() => { void exportArchive(); }}
+ data-testid="trajectory-archive-export"
+ >
+ {exporting ? copy.exportingArchive : copy.exportArchive}
+ </button>
+ {replayArchive === null ? null : (
+ <button
+ type="button"
+ className={css.archiveAction}
+ onClick={exitReplay}
+ data-testid="trajectory-archive-exit"
+ >
+ {copy.exitReplay}
+ </button>
+ )}
+ </div>
+ </header>
+ {archiveError === null ? null : (
+ <p className={`${css.archiveError} ${css.errorText}`} role="alert">{archiveError}</p>
+ )}
+ <div ref={bodyRef} className={css.body}>{content}</div>
+ </section>
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.module.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.module.css
new file mode 100644
index 0000000000..d9f3114dc1
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.module.css
@@ -0,0 +1,45 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+/*
+ * Full-bleed, fixed-height host for the trajectory ledger.
+ * Adapted from packages/client/ui-trajectory/src/client/views.module.css under MIT.
+ */
+.root {
+ --dsh-trajectory-toolbar-height: 32px;
+
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ height: 100%;
+ min-height: 0;
+ width: 100%;
+ box-sizing: border-box;
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-bg-layer-1);
+}
+
+.ledger {
+ position: relative;
+ z-index: 0;
+ isolation: isolate;
+ display: flex;
+ flex: 1;
+ min-height: 0;
+ min-width: 0;
+ overflow: hidden;
+
+ --dsh-trajectory-bottom-clearance: var(--trajectory-bottom-inset, 0px);
+}
+
+.error {
+ position: relative;
+ z-index: 2;
+ flex: 0 0 auto;
+ min-height: 28px;
+ box-sizing: border-box;
+ padding: 6px 10px;
+ border-bottom: 1px solid var(--dsw-alias-border-l2);
+ color: var(--dsw-alias-state-error);
+ background: var(--dsw-alias-bg-layer-1);
+ font: var(--dsw-font-xxs-12);
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.tsx
new file mode 100644
index 0000000000..f68086a811
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.tsx
@@ -0,0 +1,313 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Standalone trajectory explorer assembled from the DSH presentation components. */
+
+import {
+ useCallback, useEffect, useMemo, useState, type CSSProperties,
+} from 'react'
+import type {
+ TrajectoryRequest, TrajectorySnapshot, TrajectoryTurnModel,
+} from '../trajectory/model.ts'
+import { trajectoryRecordId } from '../trajectory/record.ts'
+import {
+ trajectoryTimelineFocusIndexes,
+ type TrajectoryTimelineMode,
+ type TrajectoryTimeRange,
+} from '../trajectory/timeline.ts'
+import { TrajectorySearchIndex } from '../trajectory/search-index.ts'
+import {
+ TrajectoryThemeProvider, type TrajectoryColorMode,
+} from '../theme/context.tsx'
+import { TrajectoryTable } from './TrajectoryTable.tsx'
+import { TrajectoryTimeline } from './TrajectoryTimeline.tsx'
+import { TrajectoryToolbar } from './TrajectoryToolbar.tsx'
+import {
+ trajectoryTranslator, type TrajectoryKey, type TrajectoryTranslate,
+} from './i18n.ts'
+import css from './TrajectoryExplorer.module.css'
+
+const EMPTY_TURN_IDS: ReadonlySet<number> = new Set()
+const EMPTY_RECORD_IDS: ReadonlySet<string> = new Set()
+
+interface ExplorerStyle extends CSSProperties {
+ '--trajectory-bottom-inset'?: string
+}
+
+/** Ordinary React props; no Cordis, Session, slot, or locale service is required. */
+export interface TrajectoryExplorerProps {
+ /** Atomic read model produced by an OTel projector or a static fixture. */
+ snapshot?: TrajectorySnapshot
+ /** Static grouped records; ignored when `snapshot` is supplied. */
+ turns?: readonly TrajectoryTurnModel[]
+ /** Request-inspector metadata for static `turns`. */
+ requests?: readonly TrajectoryRequest[]
+ /** Whether the initial tail has not reached the browser yet. */
+ loading?: boolean
+ /** Whether one older page request is pending. */
+ loadingEarlier?: boolean
+ /** Whether an earlier page exists. */
+ hasEarlier?: boolean
+ /** Prepend one earlier page. */
+ loadEarlier?: () => Promise<boolean>
+ /** Retryable store or transport failure shown without hiding loaded records. */
+ error?: string | null
+ /** Optional inspector handoff using the projected tool call id. */
+ inspectCallId?: string | null
+ /** Called after an inspect handoff is consumed or cannot be resolved. */
+ onInspectApplied?: () => void
+ /** Override individual toolbar labels. */
+ messages?: Partial<Record<TrajectoryKey, string>>
+ /** Full custom translator; takes precedence over `messages`. */
+ translate?: TrajectoryTranslate
+ /** Space reserved for a host-owned bottom overlay. */
+ bottomInset?: number | string
+ /** Local viewer palette. The host remains responsible for choosing it. */
+ colorMode?: TrajectoryColorMode
+ className?: string
+}
+
+function firstSourceSeq(turns: readonly TrajectoryTurnModel[]): number | undefined {
+ for (const turn of turns) {
+ for (const group of turn.groups) {
+ for (const cell of group.cells) {
+ if (cell.sourceSeq !== undefined) return cell.sourceSeq
+ }
+ }
+ }
+ return undefined
+}
+
+function searchIndexes(
+ index: TrajectorySearchIndex,
+ turns: readonly TrajectoryTurnModel[],
+ query: string,
+): ReadonlySet<number> | null {
+ index.update([turns])
+ const ids = index.search(query)
+ if (ids === null) return null
+ const matches = new Set<number>()
+ for (const turn of turns) {
+ for (const group of turn.groups) {
+ for (const cell of group.cells) {
+ if (ids.has(trajectoryRecordId(cell))) matches.add(cell.index)
+ }
+ }
+ }
+ return matches
+}
+
+/** Render the full toolbar, overview timeline, virtual ledger, and inspector. */
+export function TrajectoryExplorer({
+ snapshot,
+ turns: staticTurns = [],
+ requests: staticRequests,
+ loading = false,
+ loadingEarlier = false,
+ hasEarlier = false,
+ loadEarlier,
+ error = null,
+ inspectCallId = null,
+ onInspectApplied,
+ messages,
+ translate,
+ bottomInset = 0,
+ colorMode = 'light',
+ className,
+}: TrajectoryExplorerProps) {
+ const turns = snapshot?.turns ?? staticTurns
+ const requests = snapshot?.requests ?? staticRequests
+ const streamingCells = snapshot?.streamingCells
+ const hasRunningCells = useMemo(() => turns.some(turn => (
+ turn.groups.some(group => group.cells.some(cell => cell.status === 'running'))
+ )), [turns])
+ const [liveNowMilliseconds, setLiveNowMilliseconds] = useState(() => Date.now())
+ useEffect(() => {
+ if (!hasRunningCells) return undefined
+ const update = () => setLiveNowMilliseconds(Date.now())
+ update()
+ const interval = window.setInterval(update, 250)
+ const onVisibility = () => {
+ if (document.visibilityState === 'visible') update()
+ }
+ document.addEventListener('visibilitychange', onVisibility)
+ return () => {
+ window.clearInterval(interval)
+ document.removeEventListener('visibilitychange', onVisibility)
+ }
+ }, [hasRunningCells])
+ const [actualDuration, setActualDuration] = useState(false)
+ const [actualTime, setActualTime] = useState(false)
+ const [collapsedTurns, setCollapsedTurns] = useState<ReadonlySet<number>>(EMPTY_TURN_IDS)
+ const [collapsedAssistants, setCollapsedAssistants] =
+ useState<ReadonlySet<string>>(EMPTY_RECORD_IDS)
+ const [searchQuery, setSearchQuery] = useState('')
+ const [searchIndex] = useState(() => new TrajectorySearchIndex())
+ const [timelineRange, setTimelineRange] = useState<TrajectoryTimeRange | null>(null)
+ const [selectedTimelineIndex, setSelectedTimelineIndex] = useState<number | null>(null)
+ const [recordSelection, setRecordSelection] = useState<{ readonly index: number } | null>(null)
+ const [recordFocus, setRecordFocus] = useState<{ readonly index: number } | null>(null)
+ const t = useMemo(
+ () => translate ?? trajectoryTranslator(messages),
+ [messages, translate],
+ )
+ const timelineMode: TrajectoryTimelineMode = actualDuration
+ ? actualTime ? 'actual' : 'duration'
+ : actualTime ? 'time' : 'sequence'
+ const searchMatchIndexes = useMemo(
+ () => searchIndexes(searchIndex, turns, searchQuery),
+ [searchIndex, searchQuery, turns],
+ )
+ const timelineFocusIndexes = useMemo(
+ () => timelineRange === null
+ ? null
+ : trajectoryTimelineFocusIndexes(
+ turns,
+ timelineRange,
+ timelineMode,
+ liveNowMilliseconds,
+ ),
+ [liveNowMilliseconds, timelineMode, timelineRange, turns],
+ )
+ const collapsibleTurnIds = useMemo(
+ () => turns.flatMap(turn => turn.turn !== null && turn.groups.reduce(
+ (count, group) => count + group.cells.filter(cell =>
+ cell.requestOnly !== true && cell.kind !== 'system').length,
+ 0,
+ ) > 1 ? [turn.turn] : []),
+ [turns],
+ )
+ const collapsibleAssistantIds = useMemo(() => {
+ const ids: string[] = []
+ for (const turn of turns) {
+ const cells = turn.groups.flatMap(group => group.cells)
+ for (let index = 0; index < cells.length; index++) {
+ const cell = cells[index]
+ const next = cells[index + 1]
+ if (cell?.kind === 'message' && (next?.kind === 'tool' || next?.kind === 'subtool')) {
+ ids.push(trajectoryRecordId(cell))
+ }
+ }
+ }
+ return ids
+ }, [turns])
+ const allTurnsCollapsed = collapsibleTurnIds.length > 0
+ && collapsibleTurnIds.every(turn => collapsedTurns.has(turn))
+ const allAssistantsCollapsed = collapsibleAssistantIds.length > 0
+ && collapsibleAssistantIds.every(id => collapsedAssistants.has(id))
+ const toggleTurn = useCallback((turn: number) => {
+ setCollapsedTurns((current) => {
+ const next = new Set(current)
+ if (next.has(turn)) next.delete(turn)
+ else next.add(turn)
+ return next
+ })
+ }, [])
+ const toggleAssistant = useCallback((id: string) => {
+ setCollapsedAssistants((current) => {
+ const next = new Set(current)
+ if (next.has(id)) next.delete(id)
+ else next.add(id)
+ return next
+ })
+ }, [])
+ const toggleAllTurns = useCallback(() => {
+ setCollapsedTurns((current) => {
+ const next = new Set(current)
+ for (const turn of collapsibleTurnIds) {
+ if (allTurnsCollapsed) next.delete(turn)
+ else next.add(turn)
+ }
+ return next
+ })
+ }, [allTurnsCollapsed, collapsibleTurnIds])
+ const toggleAllAssistants = useCallback(() => {
+ setCollapsedAssistants((current) => {
+ const next = new Set(current)
+ for (const id of collapsibleAssistantIds) {
+ if (allAssistantsCollapsed) next.delete(id)
+ else next.add(id)
+ }
+ return next
+ })
+ }, [allAssistantsCollapsed, collapsibleAssistantIds])
+ const rootStyle: ExplorerStyle = {
+ '--trajectory-bottom-inset': typeof bottomInset === 'number'
+ ? `${bottomInset}px`
+ : bottomInset,
+ }
+
+ return (
+ <TrajectoryThemeProvider colorMode={colorMode}>
+ <div
+ className={[css.root, 'jiuwenTrajectoryTheme', className].filter(Boolean).join(' ')}
+ data-trajectory-theme={colorMode}
+ style={rootStyle}
+ >
+ <TrajectoryToolbar
+ actualDuration={actualDuration}
+ onActualDurationChange={(value) => { setActualDuration(value); setTimelineRange(null) }}
+ actualTime={actualTime}
+ onActualTimeChange={(value) => { setActualTime(value); setTimelineRange(null) }}
+ allTurnsCollapsed={allTurnsCollapsed}
+ onToggleAllTurns={toggleAllTurns}
+ allAssistantsCollapsed={allAssistantsCollapsed}
+ onToggleAllAssistants={toggleAllAssistants}
+ searchQuery={searchQuery}
+ onSearchQueryChange={setSearchQuery}
+ t={t}
+ />
+ <TrajectoryTimeline
+ turns={turns}
+ mode={timelineMode}
+ range={timelineRange}
+ olderHistoryLoading={loadingEarlier}
+ hasEarlierRecords={hasEarlier}
+ {...(loadEarlier === undefined ? {} : { onLoadEarlier: loadEarlier })}
+ selectedIndex={selectedTimelineIndex}
+ searchMatchIndexes={searchMatchIndexes}
+ onRangeChange={setTimelineRange}
+ onRecordSelect={(index) => {
+ setTimelineRange(null)
+ setRecordSelection({ index })
+ setSelectedTimelineIndex(index)
+ }}
+ onRecordFocus={index => { setRecordFocus({ index }) }}
+ nowMilliseconds={liveNowMilliseconds}
+ />
+ {error !== null && (
+ <div className={css.error} role="status">{error}</div>
+ )}
+ <div className={css.ledger}>
+ <TrajectoryTable
+ turns={turns}
+ {...(requests === undefined ? {} : { requestNumbers: requests })}
+ {...(streamingCells === undefined ? {} : { streamingCells })}
+ timelineFocusIndexes={timelineFocusIndexes}
+ searchMatchIndexes={searchMatchIndexes}
+ onSelectedIndexChange={setSelectedTimelineIndex}
+ onRecordSelect={(index) => {
+ if (timelineFocusIndexes !== null && !timelineFocusIndexes.has(index)) {
+ setTimelineRange(null)
+ }
+ }}
+ recordSelection={recordSelection}
+ recordFocus={recordFocus}
+ historyLoading={loading}
+ olderHistoryLoading={loadingEarlier}
+ historyStartSeq={firstSourceSeq(turns)}
+ hasOlderRecords={hasEarlier}
+ {...(loadEarlier === undefined ? {} : { onLoadOlder: loadEarlier })}
+ onClearSelection={() => { setTimelineRange(null) }}
+ collapsedTurns={collapsedTurns}
+ onToggleTurn={toggleTurn}
+ collapsedAssistants={collapsedAssistants}
+ onToggleAssistant={toggleAssistant}
+ inspectCallId={inspectCallId}
+ nowMilliseconds={liveNowMilliseconds}
+ {...(onInspectApplied === undefined ? {} : { onInspectApplied })}
+ />
+ </div>
+ </div>
+ </TrajectoryThemeProvider>
+ )
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.module.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.module.css
new file mode 100644
index 0000000000..f4bfb537a1
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.module.css
@@ -0,0 +1,1871 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+/* Adapted from packages/client/ui-trajectory/src/client/TrajectoryTable.module.css under MIT. */
+.split {
+ --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);
+ --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);
+
+ position: relative;
+ display: flex;
+ flex: 1;
+ width: 100%;
+ min-height: 0;
+ overflow: hidden;
+ background: var(--dsw-alias-bg-layer-1);
+ container-type: inline-size;
+}
+
+.tablePane {
+ position: relative;
+ flex: 1;
+ min-width: 0;
+ overflow-x: hidden;
+ overflow-y: auto;
+ padding-bottom: var(--dsh-trajectory-bottom-clearance, 0px);
+ container: trajectory-table / inline-size;
+}
+
+.historyLoading {
+ position: sticky;
+ z-index: 5;
+ top: 0;
+ height: 0;
+ overflow: visible;
+ pointer-events: none;
+}
+
+.historyLoadingBar {
+ display: flex;
+ width: 100%;
+ height: 30px;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ box-sizing: border-box;
+ border-bottom: 1px solid var(--dsw-alias-border-l2);
+ background: var(--dsw-alias-bg-layer-1);
+ color: var(--dsw-alias-label-secondary);
+ font: var(--dsw-font-xxs-12);
+}
+
+.historyLoadingSpinner {
+ width: 10px;
+ height: 10px;
+ box-sizing: border-box;
+ border: 1.5px solid var(--dsw-alias-border-l2);
+ border-top-color: var(--dsw-alias-state-business-primary);
+ border-radius: 50%;
+ animation: history-loading-spin 700ms linear infinite;
+}
+
+.table tbody .historyLoadRow td {
+ height: 30px;
+ padding: 0;
+}
+
+/* The pagination control does not create a trajectory turn boundary. */
+.table tbody .historyLoadRow + tr[data-turn-start='true'] td::before {
+ content: none;
+}
+
+.historyLoadButton {
+ display: flex;
+ width: 100%;
+ height: 29px;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ border: 0;
+ background: var(--dsw-alias-bg-layer-1);
+ color: var(--dsw-alias-label-secondary);
+ cursor: pointer;
+ font: var(--dsw-font-xxs-12);
+}
+
+.historyLoadButton:hover:not(:disabled) {
+ background: var(--dsw-alias-interactive-bg-hover);
+ color: var(--dsw-alias-label-primary);
+}
+
+.historyLoadButton:focus-visible {
+ outline: 2px solid var(--dsw-alias-state-business-primary);
+ outline-offset: -2px;
+}
+
+.historyLoadButton:disabled {
+ cursor: default;
+}
+
+.visuallyHidden {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+}
+
+.table:not([data-scroll-ready='true']) {
+ visibility: hidden;
+}
+
+@keyframes history-loading-spin {
+ to { transform: rotate(360deg); }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .historyLoadingSpinner {
+ animation: none;
+ }
+}
+
+.table {
+ --trajectory-turn-accent: var(--dsw-alias-state-business-tertiary);
+}
+
+@supports (color: color-mix(in srgb, currentColor, transparent)) {
+ .table {
+ --trajectory-turn-accent: color-mix(
+ in srgb,
+ var(--dsw-static-blue-500) 22%,
+ var(--dsw-alias-bg-layer-1)
+ );
+ }
+}
+
+.table {
+ width: 100%;
+ min-width: 0;
+ border-spacing: 0;
+ table-layout: fixed;
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-bg-layer-1);
+ font: var(--dsw-font-xxs-12);
+}
+
+.eventColumn {
+ width: 122px;
+}
+
+.contentColumn {
+ width: auto;
+}
+
+.table th {
+ position: sticky;
+ top: 0;
+ z-index: 3;
+ box-sizing: border-box;
+ height: 30px;
+ padding: 0 8px;
+ overflow: hidden;
+ border-bottom: 1px solid var(--dsw-alias-border-l2);
+ color: var(--dsw-alias-label-tertiary);
+ background: var(--dsw-specific-sidebar-fill);
+ font: var(--dsw-font-xxs-12);
+ font-weight: 500;
+ text-align: left;
+ text-overflow: ellipsis;
+ user-select: none;
+ white-space: nowrap;
+}
+
+.eventHeader {
+ padding-right: 4px !important;
+ text-align: right !important;
+}
+
+.table td {
+ box-sizing: border-box;
+ height: 30px;
+ padding: 0 8px;
+ overflow: hidden;
+ border-bottom: 1px solid var(--dsw-alias-border-l1);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.table tbody .virtualSpacer {
+ pointer-events: none;
+}
+
+.table tbody .virtualSpacer td {
+ height: var(--trajectory-virtual-spacer-height);
+ padding: 0;
+ border: 0;
+}
+
+.table tbody tr:not([data-collapsed-summary]):not([data-virtual-spacer]):not([data-history-load]) {
+ cursor: default;
+ outline: none;
+ transition:
+ background-color 120ms var(--ds-ease-in-out),
+ opacity 120ms var(--ds-ease-in-out);
+}
+
+.table tbody tr[data-timeline-focus='outside'] {
+ opacity: 0.24;
+}
+
+.table tbody tr:not([data-collapsed-summary]):not([data-virtual-spacer]):not([data-history-load]):not([data-selected='true']):hover {
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.table tbody tr[data-request-only='true']:hover {
+ background: transparent;
+}
+
+.table tbody tr[data-request-only='true'] td {
+ height: 0;
+ padding-top: 0;
+ padding-bottom: 0;
+ border-bottom: 0;
+}
+
+.table tbody tr[data-terminal-request-boundary='true'] td {
+ /* Retain the lower half of the 16px boundary marker at the table's end. */
+ height: 9px;
+}
+
+.table tbody tr[data-request-only='true'] .turnRail {
+ top: -15px;
+ bottom: 0;
+}
+
+.table tbody tr:not([data-collapsed-summary]):focus-visible {
+ box-shadow: inset 0 0 0 1px var(--dsw-alias-state-business-primary);
+}
+
+.table tbody tr[data-selected='true'] {
+ background: var(--dsw-alias-interactive-bg-active);
+}
+
+.requestBoundaryControl {
+ --request-boundary-base-left: 12px;
+
+ position: absolute;
+ z-index: 6;
+ top: -8px;
+ left: calc(var(--request-boundary-base-left) + var(--request-boundary-offset, 0px));
+ width: 16px;
+ height: 16px;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ cursor: pointer;
+}
+
+.requestBoundaryControl::before {
+ position: absolute;
+ top: 5.5px;
+ left: 5.5px;
+ width: 5px;
+ height: 5px;
+ border-radius: 50%;
+ background: var(--dsw-alias-label-caption);
+ box-shadow:
+ 0 0 0 2px var(--dsw-alias-bg-layer-1),
+ 0 0 0 3px transparent;
+ content: '';
+ transition:
+ background 120ms var(--ds-ease-in-out),
+ box-shadow 120ms var(--ds-ease-in-out);
+}
+
+.requestBoundaryControl::after {
+ position: absolute;
+ top: 2px;
+ left: 17px;
+ width: max-content;
+ padding: 0 4px;
+ border: 1px solid var(--dsw-alias-border-l1);
+ border-radius: 2px;
+ color: var(--dsw-alias-label-secondary);
+ background: var(--dsw-alias-bg-layer-1);
+ box-shadow: var(--trajectory-shadow-request-boundary);
+ content: attr(data-label);
+ font: 9px/12px var(--ds-font-family-code);
+ opacity: 0;
+ pointer-events: none;
+ transform: translateX(-2px);
+ transition:
+ opacity 120ms var(--ds-ease-in-out),
+ transform 120ms var(--ds-ease-in-out);
+ user-select: none;
+ white-space: nowrap;
+}
+
+.requestBoundaryControl:hover::before,
+.requestBoundaryControl:focus-visible::before {
+ background: var(--dsw-alias-brand-primary-new-colorprimary-new-color);
+}
+
+.requestBoundaryControlActive::before,
+.requestBoundaryControlActive:hover::before,
+.requestBoundaryControlActive:focus-visible::before {
+ background: var(--dsw-alias-state-business-tertiary);
+ background: color-mix(
+ in srgb,
+ var(--dsw-alias-brand-primary-new-colorprimary-new-color) 18%,
+ var(--dsw-alias-bg-layer-1)
+ );
+ box-shadow: 0 0 0 1.5px var(--dsw-alias-brand-primary-new-colorprimary-new-color);
+}
+
+.requestBoundaryControl[data-request-status='error']::before,
+.requestBoundaryControl[data-request-status='error']:hover::before,
+.requestBoundaryControl[data-request-status='error']:focus-visible::before {
+ background: var(--dsw-alias-state-error-primary);
+}
+
+.requestBoundaryControl[data-request-status='running']::before {
+ background: var(--dsw-alias-brand-primary-new-colorprimary-new-color);
+ animation: trajectory-running-pulse 1.2s ease-in-out infinite;
+}
+
+.table tbody tr[data-running='true'] {
+ background: color-mix(
+ in srgb,
+ var(--dsw-alias-brand-primary-new-colorprimary-new-color) 4%,
+ transparent
+ );
+}
+
+.requestBoundaryControl:hover::after,
+.requestBoundaryControl:focus-visible::after {
+ opacity: 1;
+ transform: translateX(0);
+}
+
+.requestBoundaryControl:focus-visible {
+ outline: none;
+}
+
+.table tbody tr:has(.requestBoundaryControl:hover):not([data-selected='true']) {
+ background: transparent;
+}
+
+.event {
+ position: relative;
+}
+
+.turnRail,
+.selectionRail {
+ position: absolute;
+ left: 0;
+ background: var(--dsw-alias-brand-primary-new-colorprimary-new-color);
+ pointer-events: none;
+}
+
+.turnRail {
+ z-index: 4;
+ top: -1px;
+ bottom: -1px;
+ width: 2px;
+ background: var(--trajectory-turn-accent);
+}
+
+.table tbody tr[data-turn-end='true'] .turnRail {
+ bottom: 0;
+}
+
+.selectionRail {
+ z-index: 5;
+ top: 0;
+ bottom: 0;
+ width: 3px;
+}
+
+.table tbody tr[data-error='true'] .turnRail {
+ background: var(--dsw-alias-state-error-secondary);
+ background: color-mix(
+ in srgb,
+ var(--dsw-alias-state-error-primary) 22%,
+ var(--dsw-alias-bg-layer-1)
+ );
+}
+
+.table tbody tr[data-error='true'] .selectionRail {
+ background: var(--dsw-alias-state-error-primary);
+}
+
+.table tbody tr[data-turn-start='true'] td {
+ position: relative;
+ overflow: visible;
+}
+
+.table tbody tr[data-turn-start='true']:not(:first-child) td::before {
+ position: absolute;
+ z-index: 1;
+ top: 0;
+ right: 0;
+ left: 0;
+ height: 2px;
+ background: var(--dsw-alias-border-l1);
+ content: '';
+ pointer-events: none;
+ transform: translateY(-50%);
+}
+
+.event {
+ overflow: visible !important;
+ padding-right: 4px !important;
+ padding-left: 36px !important;
+}
+
+.turnLabel {
+ position: absolute;
+ z-index: 3;
+ top: 0;
+ left: 0;
+ display: inline-grid;
+ flex: none;
+ align-items: center;
+ box-sizing: border-box;
+ width: max-content;
+ padding: 1px 5px;
+ border-radius: 0 0 2px;
+ color: var(--dsw-alias-label-tertiary);
+ background: var(--dsw-alias-bg-module-platform);
+ font: 8px/10px var(--ds-font-family-code);
+ font-variant-numeric: tabular-nums;
+ user-select: none;
+ white-space: nowrap;
+}
+
+.turnLabelFull,
+.turnLabelCompact {
+ grid-area: 1 / 1;
+ max-width: 64px;
+ overflow: hidden;
+ opacity: 1;
+ white-space: nowrap;
+}
+
+.turnLabelCompact {
+ max-width: 0;
+ opacity: 0;
+}
+
+.turnLabelActive {
+ color: var(--dsw-static-blue-500);
+ color: color-mix(
+ in srgb,
+ var(--dsw-static-blue-500) 55%,
+ var(--dsw-alias-label-tertiary)
+ );
+ background: var(--trajectory-turn-accent);
+}
+
+.eventInner {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ min-width: 0;
+ height: 100%;
+}
+
+.kindSlot {
+ display: flex;
+ flex: none;
+ align-items: flex-end;
+ justify-content: flex-end;
+ width: 76px;
+}
+
+.kindSlot :global([role='tooltip']) {
+ border: 1px solid var(--dsw-alias-border-l2);
+ background: var(--dsw-alias-bg-layer-2);
+ box-shadow: var(--dsw-shadow-lv2);
+ color: var(--dsw-alias-label-primary);
+}
+
+.content {
+ padding-left: 4px !important;
+ color: var(--dsw-alias-label-primary);
+}
+
+.kindTag {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ box-sizing: border-box;
+ height: 19px;
+ padding: 0 5px;
+ border: 1px solid transparent;
+ border-radius: 4px;
+ font-size: 10px;
+ line-height: 16px;
+ font-weight: 650;
+ letter-spacing: 0.035em;
+ user-select: none;
+}
+
+.kindTagIcon {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+ width: 0;
+ height: 13px;
+ overflow: hidden;
+ opacity: 0;
+ transform: scale(0.8);
+}
+
+.kindTagLabel {
+ display: inline-block;
+ max-width: 72px;
+ overflow: hidden;
+ opacity: 1;
+ white-space: nowrap;
+}
+
+.table .kindSlot .message {
+ justify-content: center;
+ width: 100%;
+}
+
+@container trajectory-table (max-width: 620px) {
+ .eventColumn {
+ width: 50px;
+ }
+
+ .event {
+ padding-right: 3px !important;
+ padding-left: 28px !important;
+ }
+
+ .requestBoundaryControl {
+ --request-boundary-base-left: 6px;
+ }
+
+ .kindSlot {
+ width: 19px;
+ }
+
+ .kindTag,
+ .table .kindSlot .message {
+ justify-content: center;
+ width: 19px;
+ padding-right: 0;
+ padding-left: 0;
+ }
+
+ .kindTagIcon {
+ width: 13px;
+ opacity: 1;
+ transform: scale(1);
+ }
+
+ .kindTagLabel {
+ max-width: 0;
+ opacity: 0;
+ }
+
+ .turnLabelFull {
+ max-width: 0;
+ opacity: 0;
+ }
+
+ .turnLabelCompact {
+ max-width: 64px;
+ opacity: 1;
+ }
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ .eventColumn,
+ .event,
+ .requestBoundaryControl,
+ .kindSlot,
+ .kindTag,
+ .kindTagIcon,
+ .kindTagLabel,
+ .turnLabelFull,
+ .turnLabelCompact {
+ transition-duration: 180ms;
+ transition-timing-function: var(--ds-ease-in-out);
+ }
+
+ .eventColumn,
+ .kindSlot {
+ transition-property: width;
+ }
+
+ .event {
+ transition-property: padding-right, padding-left;
+ }
+
+ .requestBoundaryControl {
+ transition-property: left;
+ }
+
+ .kindTag {
+ transition-property: padding-right, padding-left;
+ }
+
+ .kindTagIcon {
+ transition-property: width, opacity, transform;
+ }
+
+ .kindTagLabel,
+ .turnLabelFull,
+ .turnLabelCompact {
+ transition-property: max-width, opacity;
+ }
+}
+
+.user {
+ color: var(--dsw-alias-state-business-primary);
+ background: var(--dsw-alias-state-business-tertiary);
+}
+
+.systemNeutral {
+ color: var(--dsw-alias-label-secondary);
+ background: var(--dsw-alias-bg-module-platform);
+}
+
+.contextGreen {
+ color: var(--dsw-alias-state-success-primary);
+ color: color-mix(
+ in srgb,
+ var(--dsw-alias-state-success-primary) 68%,
+ var(--dsw-alias-label-secondary)
+ );
+ background: var(--dsw-alias-state-success-tertiary);
+}
+
+.compacted {
+ color: var(--dsw-alias-label-secondary);
+ background: var(--dsw-alias-bg-module-platform);
+}
+
+.compactedSummary {
+ margin-top: 12px;
+ padding: 0 0 14px;
+ font: var(--dsw-font-xs-13);
+}
+
+.promptDiffSections {
+ display: flex;
+ max-height: 100%;
+ flex-direction: column;
+ padding: 10px 14px 14px;
+ gap: 14px;
+ overflow: auto;
+}
+
+.promptDiffSection {
+ min-width: 0;
+}
+
+.promptDiffTitle {
+ margin: 0 0 6px;
+ color: var(--dsw-alias-label-secondary);
+ font: var(--dsw-font-xs-strong-13);
+ user-select: none;
+}
+
+.promptDiff {
+ margin: 0;
+ overflow: auto;
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-bg-layer-1);
+ font: 11px/17px var(--ds-font-family-code);
+ white-space: pre;
+}
+
+.promptDiff span {
+ display: block;
+ min-width: max-content;
+ padding: 0 6px;
+}
+
+.promptDiffLinemeta {
+ color: var(--dsw-alias-label-caption);
+ background: var(--dsw-alias-bg-module-platform);
+ user-select: none;
+}
+
+.promptDiffLinecontext {
+ color: var(--dsw-alias-label-secondary);
+}
+
+.promptDiffLineadded {
+ color: var(--dsw-alias-state-success-primary);
+ color: color-mix(
+ in srgb,
+ var(--dsw-alias-state-success-primary) 72%,
+ var(--dsw-alias-label-primary)
+ );
+ background: var(--dsw-alias-state-success-tertiary);
+}
+
+.promptDiffLineremoved {
+ color: var(--dsw-alias-state-error-primary);
+ background: var(--dsw-alias-bg-module-platform);
+ background: color-mix(
+ in srgb,
+ var(--dsw-alias-state-error-primary) 12%,
+ var(--dsw-alias-bg-layer-1)
+ );
+}
+
+.assistantVioletBright {
+ color: var(--dsw-alias-brand-primary-new-colorprimary-new-color);
+ color: color-mix(
+ in srgb,
+ var(--dsw-alias-brand-primary-new-colorprimary-new-color) 60%,
+ var(--dsw-alias-state-error-secondary)
+ );
+ background: var(--dsw-alias-state-business-tertiary);
+ background: color-mix(
+ in srgb,
+ color-mix(
+ in srgb,
+ var(--dsw-alias-brand-primary-new-colorprimary-new-color) 55%,
+ var(--dsw-alias-state-error-secondary)
+ ) 15%,
+ var(--dsw-alias-bg-layer-1)
+ );
+}
+
+.toolAmber {
+ color: var(--dsw-alias-state-warn-label);
+ background: var(--dsw-alias-state-warn-tertiary);
+}
+
+.subtoolAmber {
+ color: var(--dsw-alias-state-warn-label);
+ color: color-mix(
+ in srgb,
+ var(--dsw-alias-state-warn-label) 62%,
+ var(--dsw-alias-label-tertiary)
+ );
+ background: var(--dsw-alias-state-warn-tertiary);
+ background: color-mix(
+ in srgb,
+ var(--dsw-alias-state-warn-tertiary) 58%,
+ var(--dsw-alias-bg-layer-1)
+ );
+}
+
+.contentText {
+ display: block;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.runningElapsed {
+ display: inline-flex;
+ align-items: center;
+ margin-left: 8px;
+ color: var(--dsw-alias-brand-primary-new-colorprimary-new-color);
+ font: 10px/14px var(--ds-font-family-code);
+ white-space: nowrap;
+}
+
+.runningDot {
+ width: 6px;
+ height: 6px;
+ margin-right: 4px;
+ border-radius: 50%;
+ background: currentColor;
+ animation: trajectory-running-pulse 1.2s ease-in-out infinite;
+}
+
+@keyframes trajectory-running-pulse {
+ 0%,
+ 100% {
+ opacity: 0.42;
+ transform: scale(0.82);
+ }
+
+ 50% {
+ opacity: 1;
+ transform: scale(1);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .runningDot,
+ .requestBoundaryControl[data-request-status='running']::before {
+ animation: none;
+ }
+}
+
+.toolCallOnly {
+ color: var(--dsw-alias-label-tertiary);
+}
+
+.table tbody tr[data-collapsed-summary='turn'] td,
+.table tbody tr[data-collapsed-summary='assistant'] td {
+ height: 20px;
+}
+
+.table tbody tr[data-collapsed-summary] {
+ cursor: pointer;
+ outline: none;
+ transition: background-color 120ms var(--ds-ease-in-out);
+}
+
+.table tbody tr[data-collapsed-summary]:hover {
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.table tbody tr[data-collapsed-summary]:focus-visible {
+ box-shadow: inset 0 0 0 1px var(--dsw-alias-state-business-primary);
+}
+
+.collapsedTurnContent {
+ display: flex;
+ align-items: center;
+ min-width: 0;
+ color: var(--dsw-alias-label-secondary);
+ font-size: 12px;
+ line-height: 16px;
+}
+
+.collapsedTurnEllipsis {
+ flex: none;
+ margin-right: 6px;
+ color: var(--dsw-alias-label-tertiary);
+ font-weight: 600;
+ user-select: none;
+}
+
+.collapsedTurnText {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.resultPreview {
+ display: grid;
+ grid-template-columns:
+ clamp(
+ 180px,
+ var(--trajectory-tool-request-width, calc(36cqw - 56px)),
+ 480px
+ )
+ minmax(0, 1fr);
+ align-items: center;
+ min-width: 0;
+ gap: 8px;
+}
+
+.resultRequest,
+.inlineResultText {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.toolCallNameTypeface {
+ color: var(--dsw-alias-label-primary);
+ font: 400 12px/18px Menlo, Consolas, 'Liberation Mono', 'PingFang SC',
+ 'Microsoft YaHei';
+}
+
+.toolCallPayload {
+ margin-left: 7px;
+ color: var(--dsw-alias-label-secondary);
+ font: 400 12px/18px var(--ds-font-family-code);
+}
+
+.table tbody tr[data-kind='tool'] .contentText,
+.table tbody tr[data-kind='subtool'] .contentText,
+.table tbody tr[data-kind='tool'] .resultPreview,
+.table tbody tr[data-kind='subtool'] .resultPreview {
+ font-family: var(--ds-font-family-code);
+ font-size: 12px;
+}
+
+.table tbody tr[data-kind='subtool'] .content {
+ padding-left: 26px;
+}
+
+.inlineResult {
+ display: flex;
+ align-items: center;
+ min-width: 0;
+ color: var(--dsw-alias-label-secondary);
+}
+
+.noOutputText {
+ color: var(--dsw-alias-label-caption);
+}
+
+.arrow {
+ flex: none;
+ margin-right: 8px;
+ color: var(--dsw-alias-label-caption);
+}
+
+.error {
+ color: var(--dsw-alias-state-error-primary);
+}
+
+.overview dd.error {
+ color: var(--dsw-alias-state-error-primary);
+}
+
+.details .errorPayload {
+ color: var(--dsw-alias-state-error-primary);
+}
+
+.details .errorPayload .resultBlockText {
+ color: inherit;
+}
+
+.details .jsonPayload.errorPayload,
+.details .jsonPreview.errorPayload {
+ --json-tree-property: var(--dsw-alias-state-error-primary);
+ --json-tree-string: var(--dsw-alias-state-error-primary);
+ --json-tree-number: var(--dsw-alias-state-error-primary);
+ --json-tree-keyword: var(--dsw-alias-state-error-primary);
+ --json-tree-punctuation: var(--dsw-alias-state-error-primary);
+ --json-tree-icon: var(--dsw-alias-state-error-primary);
+}
+
+.details {
+ position: relative;
+ display: flex;
+ flex: none;
+ flex-direction: column;
+ width: clamp(320px, 38%, 440px);
+ max-width: calc(100% - 280px);
+ min-width: 0;
+ min-height: 0;
+ border-left: 1px solid var(--dsw-alias-border-l2);
+ background: var(--dsw-alias-bg-layer-1);
+}
+
+.detailsResizeHandle {
+ position: absolute;
+ z-index: 6;
+ top: 0;
+ bottom: 0;
+ left: -4px;
+ width: 8px;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ cursor: col-resize;
+ touch-action: none;
+ user-select: none;
+}
+
+.detailsResizeHandle:focus-visible {
+ outline: none;
+}
+
+.detailsHeader {
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: space-between;
+ box-sizing: border-box;
+ height: 42px;
+ padding: 0 8px 0 12px;
+ border-bottom: 1px solid var(--dsw-alias-border-l2);
+}
+
+.detailsTitle {
+ display: flex;
+ align-items: center;
+ min-width: 0;
+ gap: 8px;
+ color: var(--dsw-alias-label-primary);
+}
+
+.requestDetailsDot {
+ flex: none;
+ width: 5px;
+ height: 5px;
+ border-radius: 50%;
+ background: var(--dsw-alias-label-secondary);
+}
+
+.requestDetailsName {
+ flex: none;
+ font: 500 12px/16px var(--ds-font-family-code);
+}
+
+.detailsLocation {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--dsw-alias-label-tertiary);
+ font: 11px/16px var(--ds-font-family-code);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.close {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ padding: 0;
+ border: 0;
+ border-radius: 6px;
+ color: var(--dsw-alias-label-secondary);
+ background: transparent;
+ cursor: pointer;
+ font-size: 18px;
+ line-height: 18px;
+}
+
+.close:hover {
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.detailTabs {
+ display: flex;
+ flex: none;
+ box-sizing: border-box;
+ width: 100%;
+ min-width: 0;
+ max-width: 100%;
+ height: 34px;
+ padding: 0 8px;
+ overflow-x: auto;
+ overflow-y: hidden;
+ gap: 1px;
+ border-bottom: 1px solid var(--dsw-alias-border-l2);
+ overscroll-behavior-x: contain;
+ scrollbar-width: none;
+ white-space: nowrap;
+}
+
+.detailTabs::-webkit-scrollbar {
+ display: none;
+}
+
+.detailTab {
+ position: relative;
+ flex: none;
+ padding: 0 9px;
+ border: 0;
+ color: var(--dsw-alias-label-tertiary);
+ background: transparent;
+ cursor: pointer;
+ font: var(--dsw-font-xs-13);
+}
+
+.detailTab:hover {
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.detailTabActive {
+ color: var(--dsw-alias-state-business-primary);
+}
+
+.detailTabActive::after {
+ position: absolute;
+ right: 9px;
+ bottom: 0;
+ left: 9px;
+ height: 2px;
+ border-radius: 1px 1px 0 0;
+ background: var(--dsw-alias-state-business-primary);
+ content: '';
+}
+
+.close:focus-visible,
+.detailTab:focus-visible {
+ outline: 1px solid var(--dsw-alias-state-business-primary);
+ outline-offset: -1px;
+}
+
+.detailBody {
+ flex: 1;
+ min-height: 0;
+ overflow-x: hidden;
+ overflow-y: auto;
+ padding-bottom: var(--dsh-trajectory-bottom-clearance, 0px);
+ scrollbar-gutter: stable;
+}
+
+.detailBodySummary {
+ display: flex;
+ box-sizing: border-box;
+ flex-direction: column;
+ padding-bottom: calc(12px + var(--dsh-trajectory-bottom-clearance, 0px));
+ overflow: hidden;
+}
+
+.detailBodySummary > .overview {
+ flex: 0 1 auto;
+ min-height: 0;
+ overflow: auto;
+ overscroll-behavior: contain;
+}
+
+.detailBodySummary > .compactedSummary {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+}
+
+.summaryScrollRegion {
+ --dsh-scrollbar-thumb: transparent;
+ --dsh-scrollbar-thumb-hover: transparent;
+}
+
+.summaryScrollRegion:hover,
+.summaryScrollRegion:focus-within {
+ --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);
+ --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);
+}
+
+.compactedSummary .markdownPayload {
+ padding-right: 18px;
+}
+
+.overview {
+ margin: 0;
+ padding: 8px 0;
+ font: var(--dsw-font-xs-13);
+}
+
+.overviewParentLinks {
+ display: flex;
+ gap: 14px;
+}
+
+.overviewHierarchyNavLink {
+ all: unset;
+ display: inline-flex;
+ align-items: center;
+ color: var(--dsw-alias-label-secondary);
+ cursor: pointer;
+ font: inherit;
+ gap: 1px;
+ opacity: 1;
+}
+
+.overviewHierarchyNavLink:hover {
+ color: var(--dsw-alias-label-primary);
+}
+
+.overviewHierarchyJumpIconTight {
+ flex: none;
+ color: var(--dsw-alias-label-caption);
+}
+
+.overviewHierarchyNavLink:hover .overviewHierarchyJumpIconTight,
+.overviewHierarchyNavLink:focus-visible .overviewHierarchyJumpIconTight {
+ color: var(--dsw-alias-label-primary);
+}
+
+.overviewHierarchyNavLink:focus-visible {
+ color: var(--dsw-alias-label-primary);
+ outline: 1px solid var(--dsw-alias-state-business-primary);
+ outline-offset: 2px;
+}
+
+.overview > div {
+ display: grid;
+ grid-template-columns: 94px minmax(0, 1fr);
+ min-height: 22px;
+ padding: 0 14px;
+ align-items: center;
+}
+
+.overview > .requestTokenDetail dt {
+ padding-left: 12px;
+}
+
+.usagePanel {
+ padding: 4px 0 10px;
+}
+
+.usageGroup + .usageGroup {
+ margin-top: 8px;
+}
+
+.usageHeading {
+ margin: 0;
+ padding: 4px 14px 1px;
+ color: var(--dsw-alias-label-secondary);
+ font: var(--dsw-font-xs-strong-13);
+ user-select: none;
+}
+
+.usageGroup .overview {
+ padding: 0;
+}
+
+.overview dt {
+ color: var(--dsw-alias-label-tertiary);
+}
+
+.overview dd {
+ min-width: 0;
+ margin: 0;
+ overflow: hidden;
+ color: var(--dsw-alias-label-primary);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.timestampToggle {
+ all: unset;
+ color: inherit;
+ cursor: pointer;
+ font: inherit;
+ user-select: text;
+}
+
+.timestampToggle:focus-visible {
+ outline: 1px solid var(--dsw-alias-state-business-primary);
+ outline-offset: 2px;
+}
+
+.overviewSections {
+ display: flex;
+ flex: 1;
+ min-height: min-content;
+ flex-direction: column;
+ overflow: hidden;
+ border-top: 0;
+}
+
+.overviewSection {
+ display: flex;
+ flex: 1 1 0;
+ max-height: max-content;
+ min-height: 28px;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+.overviewSection + .overviewSection {
+ padding-top: 8px;
+}
+
+.overviewHeading {
+ display: flex;
+ flex: none;
+ align-items: flex-end;
+ box-sizing: border-box;
+ width: 100%;
+ height: 28px;
+ margin: 0;
+ padding: 0 0 3px 14px;
+ color: var(--dsw-alias-label-secondary);
+ background: var(--dsw-alias-bg-layer-1);
+ font: var(--dsw-font-xs-strong-13);
+ user-select: none;
+}
+
+.overviewTitle {
+ display: inline-flex;
+ flex: none;
+ width: max-content;
+ height: auto;
+ align-items: center;
+ padding: 0;
+ border: 0;
+ color: inherit;
+ background: transparent;
+ cursor: pointer;
+ font: inherit;
+ gap: 3px;
+ line-height: 1;
+ user-select: none;
+}
+
+.overviewTitleIcon {
+ flex: none;
+ color: var(--dsw-alias-label-caption);
+}
+
+.overviewTitle:hover .overviewTitleIcon {
+ color: var(--dsw-alias-label-primary);
+}
+
+.overviewTitle:focus-visible {
+ outline: 1px solid var(--dsw-alias-state-business-primary);
+ outline-offset: 2px;
+}
+
+.overviewTitle:focus-visible .overviewTitleIcon {
+ color: var(--dsw-alias-state-business-primary);
+}
+
+.overviewPreview {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ overscroll-behavior: contain;
+ background: var(--dsw-alias-bg-layer-1);
+}
+
+.overviewPreview > :last-child {
+ margin-bottom: 0;
+ padding-bottom: 0;
+}
+
+.overviewPreview .jsonPreview > :first-child,
+.overviewPreview .schemaTree > :first-child {
+ padding-bottom: 0;
+}
+
+.overviewPreview .schemaTree {
+ margin-bottom: 0;
+}
+
+.overviewPreview .overview {
+ padding: 2px 0 0;
+}
+
+.overviewPreview .overview > div {
+ min-height: 22px;
+}
+
+.markdownPreview,
+.markdownPayload {
+ color: var(--dsw-alias-label-primary);
+}
+
+.markdownPreview > div,
+.markdownPayload > div {
+ gap: 8px;
+ font: var(--dsw-font-xs-13);
+}
+
+.markdownPreview > div h1,
+.markdownPayload > div h1 {
+ font: 600 16px/22px var(--dsw-font-family);
+}
+
+.markdownPreview > div h2,
+.markdownPayload > div h2 {
+ font: 600 15px/22px var(--dsw-font-family);
+}
+
+.markdownPreview > div :where(h3, h4, h5, h6),
+.markdownPayload > div :where(h3, h4, h5, h6) {
+ font: 600 14px/20px var(--dsw-font-family);
+}
+
+.markdownPreview > div :not(pre) > code,
+.markdownPayload > div :not(pre) > code {
+ font: 12px/18px var(--ds-font-family-code);
+}
+
+.markdownPreview > div table,
+.markdownPayload > div table {
+ font: var(--dsw-font-xs-13);
+}
+
+.markdownPreview > div > :first-child {
+ margin-top: 0;
+}
+
+.markdownPreview > div > :last-child {
+ margin-bottom: 0;
+}
+
+.markdownPreview > div :where(h1, h2, h3) {
+ margin: 12px 0 6px;
+}
+
+.markdownPreview > div :where(h4, h5, h6) {
+ margin: 10px 0 5px;
+}
+
+.markdownPreview > div :where(p, ul, ol) {
+ margin: 8px 0;
+}
+
+.markdownPreview > div li:not(:first-child) {
+ margin-top: 3px;
+}
+
+.markdownPreview > div blockquote {
+ margin-top: 8px;
+}
+
+.markdownPreview > div hr {
+ margin: 14px 0;
+}
+
+.markdownPreview > div > :global(.md-code-block) {
+ margin: 10px 0;
+}
+
+.assistantContent .markdownPayload,
+.assistantContent .payload {
+ min-height: 0;
+}
+
+.thinkingQuote {
+ margin: 6px 14px 0 12px;
+ padding-left: 6px;
+ border-left: 2px solid var(--dsw-alias-markdown-citation);
+ color: var(--dsw-alias-label-secondary);
+ background: transparent;
+}
+
+.thinkingQuoteOnlyPreview {
+ margin-bottom: 8px;
+}
+
+.detailBody > .assistantContentRendered .thinkingQuote {
+ margin-top: 14px;
+}
+
+.thinkingToggle {
+ display: flex;
+ align-items: center;
+ width: max-content;
+ height: 18px;
+ padding: 0;
+ border: 0;
+ color: var(--dsw-alias-label-tertiary);
+ background: transparent;
+ cursor: pointer;
+ font: 600 12px/18px var(--dsw-font-family);
+ gap: 2px;
+ user-select: none;
+}
+
+.thinkingChevron {
+ flex: none;
+ transition: transform 120ms var(--ds-ease-in-out);
+}
+
+.thinkingToggle[aria-expanded='true'] .thinkingChevron {
+ transform: rotate(90deg);
+}
+
+.thinkingToggle:hover {
+ color: var(--dsw-alias-label-secondary);
+}
+
+.thinkingToggle:focus-visible {
+ outline: 1px solid var(--dsw-alias-state-business-primary);
+ outline-offset: 2px;
+}
+
+.thinkingQuote .markdownPreview,
+.thinkingQuote .markdownPayload,
+.thinkingQuote .payload {
+ min-height: 0;
+ padding: 2px 0;
+ color: var(--dsw-alias-label-secondary);
+ background: transparent;
+}
+
+.assistantOutput {
+ background: var(--dsw-alias-bg-layer-1);
+}
+
+.markdownPreview {
+ padding: 6px 14px 8px;
+}
+
+.markdownPayload {
+ min-height: 100%;
+ padding: 14px;
+}
+
+.jsonPayload {
+ min-height: 100%;
+}
+
+.jsonPreview {
+ min-height: 0;
+}
+
+.schema {
+ min-height: 100%;
+ background: var(--dsw-alias-bg-layer-1);
+}
+
+.schemaPreview {
+ min-height: 0;
+}
+
+.schemaIntro {
+ padding: 12px 14px 6px;
+}
+
+.schemaPreview .schemaIntro {
+ padding-top: 6px;
+}
+
+.schemaName {
+ margin: 0;
+ color: var(--dsw-alias-label-primary);
+ font: 600 12px/18px var(--ds-font-family-code);
+}
+
+.schemaDescription {
+ margin: 2px 0 0;
+ color: var(--dsw-alias-label-secondary);
+ font: var(--dsw-font-xs-13);
+ white-space: pre-wrap;
+}
+
+.schemaParameters {
+ min-width: 0;
+}
+
+.schemaParametersTitle {
+ margin: 0;
+ padding: 4px 14px 2px;
+ color: var(--dsw-alias-label-tertiary);
+ font: 600 11px/16px var(--dsw-font-family);
+ user-select: none;
+}
+
+.schemaTree {
+ margin: 0 6px 8px 0;
+}
+
+.payload {
+ box-sizing: border-box;
+ min-height: 100%;
+ margin: 0;
+ padding: 14px;
+ overflow-wrap: anywhere;
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-markdown-code-block);
+ font: 12px/19px var(--ds-font-family-code);
+ tab-size: 2;
+ white-space: pre-wrap;
+}
+
+.payloadPreview {
+ min-height: 0;
+ padding: 6px 14px 8px;
+}
+
+.sourceBlocks {
+ box-sizing: border-box;
+ min-height: 100%;
+ padding: 12px 14px;
+}
+
+.sourceBlock + .sourceBlock {
+ margin-top: 14px;
+}
+
+.sourceBlockHeader,
+.sourceBlockJumpTarget {
+ display: flex;
+ align-items: center;
+ width: max-content;
+ margin-bottom: 3px;
+ gap: 3px;
+ user-select: none;
+}
+
+.sourceBlockJumpTarget {
+ all: unset;
+ display: flex;
+ align-items: center;
+ width: max-content;
+ margin-bottom: 3px;
+ gap: 3px;
+ cursor: pointer;
+ user-select: none;
+}
+
+.sourceBlockLabel {
+ color: var(--dsw-alias-label-tertiary);
+ font: 11px/16px var(--ds-font-family-code);
+}
+
+.sourceBlockJumpIcon {
+ flex: none;
+ color: var(--dsw-alias-label-caption);
+}
+
+.sourceBlockJumpTarget:hover .sourceBlockJumpIcon {
+ color: var(--dsw-alias-label-primary);
+}
+
+.sourceBlockJumpTarget:focus-visible {
+ outline: none;
+}
+
+.sourceBlockJumpTarget:focus-visible .sourceBlockJumpIcon {
+ color: var(--dsw-alias-state-business-primary);
+}
+
+.sourceBlockContent {
+ margin: 0;
+ overflow-wrap: anywhere;
+ color: var(--dsw-alias-label-primary);
+ background: transparent;
+ font: 12px/19px var(--ds-font-family-code);
+ tab-size: 2;
+ white-space: pre-wrap;
+}
+
+.panelImageLink {
+ display: block;
+ width: auto;
+ max-width: 100%;
+ overflow: hidden;
+ border-radius: 4px;
+ cursor: zoom-in;
+}
+
+.panelImageLinkPreview {
+ max-height: 140px;
+}
+
+.panelImage {
+ display: block;
+ width: auto;
+ max-width: 100%;
+ height: auto;
+ max-height: 320px;
+ margin: 0;
+ border-radius: inherit;
+ background: var(--dsw-alias-bg-base);
+ object-fit: contain;
+}
+
+.panelImageLinkPreview .panelImage {
+ max-height: 140px;
+}
+
+.messageImages {
+ display: flex;
+ flex-direction: column;
+ margin: 8px 14px 14px;
+ gap: 8px;
+}
+
+.messageImagesPreview {
+ margin: 6px 14px 8px;
+ gap: 6px;
+}
+
+.assistantToolCalls {
+ box-sizing: border-box;
+ max-width: 100%;
+ margin: 2px 14px 12px;
+ padding: 0;
+ color: var(--dsw-alias-label-secondary);
+ font: 11px/17px var(--ds-font-family-code);
+ list-style: none;
+}
+
+.assistantToolCallsPreview {
+ margin-top: 2px;
+ margin-bottom: 8px;
+}
+
+.assistantToolCalls li {
+ min-width: 0;
+}
+
+.assistantToolCallButton {
+ all: unset;
+ display: flex;
+ box-sizing: border-box;
+ width: calc(100% + 4px);
+ min-width: 0;
+ height: 19px;
+ align-items: center;
+ margin-left: -4px;
+ padding: 0 4px;
+ border-radius: 3px;
+ cursor: pointer;
+}
+
+.assistantToolCallButton:hover {
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.assistantToolCallButton:focus-visible {
+ background: var(--dsw-alias-interactive-bg-hover);
+ outline: 1px solid var(--dsw-alias-state-business-primary);
+ outline-offset: -1px;
+}
+
+.assistantToolCallIcon {
+ flex: none;
+ margin-right: 5px;
+ color: var(--dsw-alias-label-caption);
+}
+
+.assistantToolCallButton:hover .assistantToolCallIcon,
+.assistantToolCallButton:focus-visible .assistantToolCallIcon {
+ color: var(--dsw-alias-label-secondary);
+}
+
+.assistantToolCallText {
+ display: flex;
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ white-space: nowrap;
+}
+
+.assistantToolCallName {
+ flex: none;
+ margin-right: 5px;
+ color: var(--dsw-alias-label-secondary);
+ font-weight: 500;
+}
+
+.assistantToolCallArgs {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--dsw-alias-label-tertiary);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.systemPrompt {
+ box-sizing: border-box;
+}
+
+.toolCatalog {
+ min-height: 100%;
+ padding: 8px 0 16px;
+}
+
+.toolCatalogItem {
+ border-bottom: 1px solid var(--dsw-alias-border-l1);
+}
+
+.toolCatalogSummary {
+ display: grid;
+ grid-template-columns: 12px 12px max-content minmax(0, 1fr);
+ align-items: center;
+ box-sizing: border-box;
+ min-height: 30px;
+ padding: 4px 12px;
+ gap: 5px;
+ cursor: pointer;
+ list-style: none;
+ user-select: none;
+}
+
+.toolCatalogSummary::-webkit-details-marker {
+ display: none;
+}
+
+.toolCatalogSummary:hover {
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.toolCatalogSummary:focus-visible {
+ background: var(--dsw-alias-interactive-bg-hover);
+ outline: 1px solid var(--dsw-alias-state-business-primary);
+ outline-offset: -1px;
+}
+
+.toolCatalogChevron,
+.toolCatalogIcon {
+ color: var(--dsw-alias-label-caption);
+}
+
+.toolCatalogChevron {
+ transition: transform 100ms var(--ds-ease-in-out);
+}
+
+.toolCatalogItem[open] .toolCatalogChevron {
+ transform: rotate(90deg);
+}
+
+.toolCatalogName {
+ color: var(--dsw-alias-label-primary);
+ font: 500 12px/18px var(--ds-font-family-code);
+}
+
+.toolCatalogDescription {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--dsw-alias-label-tertiary);
+ font: var(--dsw-font-xs-13);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.toolCatalogDefinition {
+ padding: 0 0 8px 29px;
+ background: var(--dsw-alias-bg-base);
+}
+
+.toolCatalogFullDescription {
+ margin: 0;
+ padding: 7px 14px 4px 0;
+ color: var(--dsw-alias-label-secondary);
+ font: var(--dsw-font-xs-13);
+ white-space: pre-wrap;
+}
+
+.toolCatalogTree {
+ margin-left: -14px;
+ margin-right: 6px;
+}
+
+.resultBlocks {
+ display: flex;
+ min-height: 100%;
+ flex-direction: column;
+ box-sizing: border-box;
+ padding: 14px;
+ gap: 10px;
+}
+
+.resultBlocksPreview {
+ min-height: 0;
+ padding: 6px 14px 8px;
+ gap: 6px;
+}
+
+.resultBlockText {
+ margin: 0;
+ overflow-wrap: anywhere;
+ color: var(--dsw-alias-label-primary);
+ background: transparent;
+ font: 12px/19px var(--ds-font-family-code);
+ tab-size: 2;
+ white-space: pre-wrap;
+}
+
+.overviewPreview .noPayload {
+ padding: 6px 14px 8px;
+}
+
+.noPayload {
+ margin: 0;
+ padding: 18px 14px;
+ color: var(--dsw-alias-label-tertiary);
+ font: var(--dsw-font-xs-13);
+}
+
+@media (max-width: 760px) {
+ .details {
+ position: absolute;
+ z-index: 5;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ width: min(92%, 420px);
+ max-width: 92%;
+ border-left-color: var(--dsw-alias-border-l3);
+ box-shadow: var(--trajectory-shadow-mobile-details);
+ }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.tsx
new file mode 100644
index 0000000000..3846c21bcf
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTable.tsx
@@ -0,0 +1,3128 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Turn-aware trajectory event ledger with a local record inspector.
+ * Adapted mechanically from `packages/client/ui-trajectory/src/client/TrajectoryTable.tsx`
+ * under the repository MIT license.
+ */
+
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
+import type { CSSProperties, ReactNode } from 'react'
+import { useVirtualizer } from '@tanstack/react-virtual'
+import {
+ IconChevronRightOutline14,
+ IconSettingsOutline16,
+ IconSparkle16,
+ IconUserOutline16,
+ JsonTree,
+ MarkdownText,
+ Tooltip,
+} from '../primitives/index.ts'
+import { structuredPatch } from 'diff'
+import type {
+ AssistantMetricDetail, TrajectoryCellKind, TrajectoryCellProps, TrajectorySourceBlock,
+} from '../trajectory/record.ts'
+import {
+ formatElapsedSeconds, liveElapsedSeconds, trajectoryRecordId,
+} from '../trajectory/record.ts'
+import type {
+ TrajectoryPromptSnapshot,
+ TrajectoryRecordedFacts,
+ TrajectoryRequest as TrajectoryRequestNumber,
+ TrajectoryRequestConfig as AssistantRequestConfig,
+ TrajectoryTurnModel,
+ TrajectoryUsage,
+} from '../trajectory/model.ts'
+import {
+ groupTrajectoryVirtualRows, trajectoryVirtualRecordKey,
+} from '../trajectory/virtual-rows.ts'
+import type { TrajectoryVirtualRow } from '../trajectory/virtual-rows.ts'
+import { trajectoryPreviewText } from '../trajectory/preview.ts'
+import css from './TrajectoryTable.module.css'
+
+const BOTTOM_FOLLOW_THRESHOLD_PX = 2
+const OLDER_LOAD_THRESHOLD_PX = 48
+const HISTORY_LOAD_ROW_HEIGHT_PX = 30
+const VIRTUALIZATION_THRESHOLD = 100
+const VIRTUAL_OVERSCAN_ROWS = 12
+const VIRTUAL_INITIAL_VIEWPORT_HEIGHT_PX = 600
+
+const KIND_LABEL: Record<TrajectoryCellKind, string> = {
+ system: 'SYSTEM',
+ user: 'USER',
+ context: 'CONTEXT',
+ compacted: 'COMPACTED',
+ message: 'ASSISTANT',
+ tool: 'TOOL',
+ subtool: 'SUBTOOL',
+}
+
+function ToolWrenchIcon(): ReactNode {
+ return (
+ <svg
+ width="13"
+ height="13"
+ viewBox="0 0 16 16"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ data-role-icon="wrench"
+ aria-hidden="true"
+ >
+ <path d="M14 3.3a3.8 3.8 0 0 1-4.8 4.8l-5.1 5.1a1.6 1.6 0 1 1-2.3-2.3l5.1-5.1A3.8 3.8 0 0 1 11.7 1l-2.3 2.3 2.3 2.3L14 3.3Z" />
+ </svg>
+ )
+}
+
+function InformationIcon(): ReactNode {
+ return (
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 16 16"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.4"
+ strokeLinecap="round"
+ data-role-icon="information"
+ aria-hidden="true"
+ >
+ <circle cx="8" cy="8" r="6.7" />
+ <circle cx="8" cy="5.5" r=".85" fill="currentColor" stroke="none" />
+ <path d="M8 7.75v3.4" strokeWidth="1.8" />
+ </svg>
+ )
+}
+
+function CompactedIcon(): ReactNode {
+ return (
+ <svg
+ width="13"
+ height="13"
+ viewBox="0 0 16 16"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ data-role-icon="compacted"
+ aria-hidden="true"
+ >
+ <path d="m2.5 2.5 3.75 3.75M3 6.25h3.25V3" />
+ <path d="m13.5 2.5-3.75 3.75M13 6.25H9.75V3" />
+ <path d="m2.5 13.5 3.75-3.75M3 9.75h3.25V13" />
+ <path d="m13.5 13.5-3.75-3.75M13 9.75H9.75V13" />
+ </svg>
+ )
+}
+
+const KIND_ICON: Record<TrajectoryCellKind, ReactNode> = {
+ system: <IconSettingsOutline16 size={13} />,
+ user: <IconUserOutline16 size={13} />,
+ context: <InformationIcon />,
+ compacted: <CompactedIcon />,
+ message: <IconSparkle16 size={13} />,
+ tool: <ToolWrenchIcon />,
+ subtool: <ToolWrenchIcon />,
+}
+
+interface TableRecord {
+ turn: number | null
+ section: number
+ group: string
+ groupStart: boolean
+ turnStart: boolean
+ cell: TrajectoryCellProps
+ turnEnd: boolean
+ collapsedSummary?: string
+ collapsedSummaryKind?: 'turn' | 'assistant'
+}
+
+interface VirtualRowStructure {
+ height: number
+ key: string
+}
+
+function useStableVirtualRowStructure(
+ rows: readonly TrajectoryVirtualRow<TableRecord>[],
+): readonly VirtualRowStructure[] {
+ const cache = useRef<{
+ rows: readonly TrajectoryVirtualRow<TableRecord>[]
+ structure: readonly VirtualRowStructure[]
+ }>({ rows: [], structure: [] })
+ if (cache.current.rows === rows) return cache.current.structure
+ const structure = cache.current.structure.length === rows.length
+ && rows.every((row, index) => {
+ const previous = cache.current.structure[index]
+ return previous?.key === row.key && previous.height === row.height
+ })
+ ? cache.current.structure
+ : rows.map(row => ({ key: row.key, height: row.height }))
+ cache.current = { rows, structure }
+ return structure
+}
+
+type DetailTab =
+ | 'system-prompt'
+ | 'tools'
+ | 'overview'
+ | 'rendered'
+ | 'raw'
+ | 'source'
+ | 'otel'
+ | 'input'
+ | 'output'
+ | 'schema'
+ | 'options'
+ | 'facts'
+ | 'usage'
+ | 'timing'
+ | 'diff'
+type RecordState = 'complete' | 'running' | 'error'
+
+interface DetailTabItem {
+ id: DetailTab
+ label: string
+}
+
+interface ParentRecords {
+ message?: TableRecord
+ tool?: TableRecord
+}
+
+interface ToolCallTextParts {
+ name: string
+ args?: string
+}
+
+interface SelectedRequest {
+ recordId: string
+ turn: number | null
+ group: string
+ seq?: number
+}
+
+interface DetailsResizeDrag {
+ pointerId: number
+ startX: number
+ startWidth: number
+ splitWidth: number
+ startToolRequestOffset: number
+}
+
+const DETAILS_MIN_WIDTH = 320
+const DETAILS_MAX_WIDTH = 720
+const TABLE_MIN_WIDTH = 280
+const DETAILS_RESIZE_STEP = 16
+const TOOL_REQUEST_SHARE = 0.58
+const TOOL_REQUEST_MIN_WIDTH = 180
+const TOOL_REQUEST_MAX_WIDTH = 480
+const DEFAULT_TOOL_REQUEST_SHARE = 0.36
+const DEFAULT_TOOL_REQUEST_OFFSET = 56
+const SYSTEM_PROMPT_TABS: readonly DetailTabItem[] = [
+ { id: 'system-prompt', label: 'System Prompt' },
+ { id: 'tools', label: 'Tools' },
+]
+const SYSTEM_UPDATE_TABS: readonly DetailTabItem[] = [
+ { id: 'diff', label: 'Diff' },
+ ...SYSTEM_PROMPT_TABS,
+]
+const REQUEST_TABS: readonly DetailTabItem[] = [
+ { id: 'overview', label: 'Summary' },
+ { id: 'options', label: 'Options' },
+ { id: 'facts', label: 'Facts' },
+ { id: 'usage', label: 'Usage' },
+ { id: 'timing', label: 'Timing' },
+]
+
+type TrajectorySplitStyle = CSSProperties & {
+ '--trajectory-tool-request-width': string
+}
+
+type RequestBoundaryStyle = CSSProperties & {
+ '--request-boundary-offset': string
+}
+
+type VirtualSpacerStyle = CSSProperties & {
+ '--trajectory-virtual-spacer-height': string
+}
+
+interface OlderLoadAnchor {
+ readonly historyStartSeq: number | undefined
+ readonly scrollHeight: number
+ readonly scrollTop: number
+}
+
+function clampDetailsWidth(width: number, splitWidth: number): number {
+ const maxWidth = Math.max(
+ DETAILS_MIN_WIDTH,
+ Math.min(DETAILS_MAX_WIDTH, splitWidth - TABLE_MIN_WIDTH),
+ )
+ return Math.round(Math.min(Math.max(width, DETAILS_MIN_WIDTH), maxWidth))
+}
+
+function defaultToolRequestWidth(splitWidth: number): number {
+ return Math.min(
+ Math.max(
+ splitWidth * DEFAULT_TOOL_REQUEST_SHARE - DEFAULT_TOOL_REQUEST_OFFSET,
+ TOOL_REQUEST_MIN_WIDTH,
+ ),
+ TOOL_REQUEST_MAX_WIDTH,
+ )
+}
+
+function formatDurationMs(milliseconds: number): string {
+ if (milliseconds < 1_000) return `${Math.round(milliseconds)} ms`
+ return `${(milliseconds / 1_000).toFixed(milliseconds < 10_000 ? 2 : 1)} s`
+}
+
+function formatStartedAt(timestamp: number | null): string {
+ if (timestamp === null || !Number.isFinite(timestamp)) return 'Not available'
+ const date = new Date(timestamp)
+ const two = (value: number) => String(value).padStart(2, '0')
+ const three = (value: number) => String(value).padStart(3, '0')
+ const time = `${two(date.getHours())}:${two(date.getMinutes())}:${two(date.getSeconds())}.${three(date.getMilliseconds())}`
+ const day = `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())}`
+ return `${day} ${time}`
+}
+
+/** Whether a click lands on an active text selection and should keep it. */
+function clickSelectsText(target: Node): boolean {
+ const selection = window.getSelection()
+ return selection !== null
+ && !selection.isCollapsed
+ && selection.rangeCount > 0
+ && selection.getRangeAt(0).intersectsNode(target)
+}
+
+function StartedAtValue({ timestamp }: { timestamp: number | null }) {
+ const [showUnix, setShowUnix] = useState(false)
+ if (timestamp === null || !Number.isFinite(timestamp)) return <dd>Not available</dd>
+ return (
+ <dd>
+ <button
+ type="button"
+ className={css.timestampToggle}
+ title={showUnix ? 'Show local time' : 'Show Unix timestamp'}
+ onClick={(event) => {
+ if (clickSelectsText(event.currentTarget)) return
+ setShowUnix(current => !current)
+ }}
+ >
+ {showUnix ? (timestamp / 1_000).toFixed(3) : formatStartedAt(timestamp)}
+ </button>
+ </dd>
+ )
+}
+
+function totalTime(metrics: AssistantMetricDetail): string {
+ if (!metrics.timingRecorded) return 'Not recorded'
+ if (metrics.stepStartTime === null) return 'Step start unavailable'
+ if (metrics.completedTime === null) return 'Pending'
+ return formatDurationMs(Math.max(0, metrics.completedTime - metrics.stepStartTime))
+}
+
+function ttft(metrics: AssistantMetricDetail): string {
+ if (!metrics.timingRecorded) return 'Not recorded'
+ if (metrics.stepStartTime === null) return 'Step start unavailable'
+ if (metrics.firstTokenTime === null) return 'First token unavailable'
+ return formatDurationMs(Math.max(0, metrics.firstTokenTime - metrics.stepStartTime))
+}
+
+function generationTime(metrics: AssistantMetricDetail): string {
+ if (!metrics.timingRecorded || metrics.firstTokenTime === null) return 'First token unavailable'
+ if (metrics.completedTime === null) return 'Pending'
+ return formatDurationMs(Math.max(0, metrics.completedTime - metrics.firstTokenTime))
+}
+
+function throughput(metrics: AssistantMetricDetail): string {
+ if (!metrics.usageProvided) return 'Usage unavailable'
+ if (metrics.outputTokens === null) return 'Output tokens unavailable'
+ if (!metrics.timingRecorded || metrics.firstTokenTime === null) return 'First token unavailable'
+ if (metrics.completedTime === null) return 'Pending'
+ const generationSeconds = (metrics.completedTime - metrics.firstTokenTime) / 1_000
+ if (generationSeconds <= 0) return 'Duration too short'
+ return `${(metrics.outputTokens / generationSeconds).toFixed(1)} tok/s`
+}
+
+function AssistantTimingPanel({ metrics }: { metrics: AssistantMetricDetail }) {
+ return (
+ <dl className={css.overview}>
+ <div><dt>Started</dt><StartedAtValue timestamp={metrics.stepStartTime} /></div>
+ <div><dt>Total duration</dt><dd>{totalTime(metrics)}</dd></div>
+ <div><dt>TTFT</dt><dd>{ttft(metrics)}</dd></div>
+ <div><dt>Generation</dt><dd>{generationTime(metrics)}</dd></div>
+ <div><dt>Throughput</dt><dd>{throughput(metrics)}</dd></div>
+ </dl>
+ )
+}
+
+/** Props for the trajectory ledger. */
+export interface TrajectoryTableProps {
+ /** Request numbers for the request groups visible in this loaded window. */
+ requestNumbers?: readonly TrajectoryRequestNumber[]
+ /** Grouped records in display order. */
+ turns: readonly TrajectoryTurnModel[]
+ /** In-flight cells whose content replaces the matching structural record index. */
+ streamingCells?: readonly TrajectoryCellProps[]
+ /** Record indexes emphasized by the active timeline focus. */
+ timelineFocusIndexes?: ReadonlySet<number> | null
+ /** Record indexes retained by the active live search, or null without a query. */
+ searchMatchIndexes?: ReadonlySet<number> | null
+ /** Report the record currently selected in the local inspector. */
+ onSelectedIndexChange?: (index: number | null) => void
+ /** Report a direct user selection from a ledger row. */
+ onRecordSelect?: (index: number) => void
+ /** One externally requested record selection; a new object repeats the request. */
+ recordSelection?: { readonly index: number } | null
+ /** One externally requested record focus without changing inspector selection. */
+ recordFocus?: { readonly index: number } | null
+ /** Whether the initial history tail is still loading. */
+ historyLoading?: boolean
+ /** Whether one older history page request is pending anywhere. */
+ olderHistoryLoading?: boolean
+ /** First loaded raw event, used to preserve scroll position after prepending a page. */
+ historyStartSeq?: number | undefined
+ /** Whether one older history page can be requested. */
+ hasOlderRecords?: boolean
+ /** Load one older history page. */
+ onLoadOlder?: () => Promise<boolean>
+ /** Clear selection state owned by the ledger host. */
+ onClearSelection?: () => void
+ /** Turn ids whose rows after the first are folded into a summary. */
+ collapsedTurns: ReadonlySet<number>
+ /** Toggle one turn between folded and expanded. */
+ onToggleTurn: (turn: number) => void
+ /** Stable Assistant record ids whose tool calls are folded. */
+ collapsedAssistants: ReadonlySet<string>
+ /** Toggle tool calls under one assistant record. */
+ onToggleAssistant: (id: string) => void
+ /** One-shot cross-view inspect: open and scroll to this call's record. */
+ inspectCallId?: string | null
+ /** Acknowledge a consumed (or unresolvable) inspect request. */
+ onInspectApplied?: (() => void) | undefined
+ /** Shared presentation clock for running elapsed labels. */
+ nowMilliseconds?: number
+}
+
+export type { TrajectoryRequest as TrajectoryRequestNumber, TrajectoryUsage } from '../trajectory/model.ts'
+
+function flattenRecords(turns: readonly TrajectoryTurnModel[]): TableRecord[] {
+ return turns.flatMap((turn, section) => {
+ let firstInSection = true
+ const records = turn.groups.flatMap((group) => {
+ return group.cells.map((cell, index) => {
+ const turnStart = firstInSection
+ && cell.requestOnly !== true
+ && cell.kind !== 'system'
+ && (cell.kind !== 'compacted' || turn.turn === null)
+ if (turnStart) firstInSection = false
+ return {
+ turn: turn.turn,
+ section,
+ group: group.title,
+ groupStart: index === 0,
+ turnStart,
+ cell,
+ turnEnd: false,
+ }
+ })
+ })
+ const last = records.at(-1)
+ if (last !== undefined) last.turnEnd = true
+ return records
+ })
+}
+
+function filterRecords(
+ records: readonly TableRecord[],
+ matches: ReadonlySet<number>,
+): TableRecord[] {
+ const filtered = records
+ .filter(record =>
+ record.cell.requestOnly !== true && matches.has(record.cell.index),
+ )
+ .map(record => ({ ...record, groupStart: false, turnStart: false, turnEnd: false }))
+ const startedSections = new Set<number>()
+ for (const [index, record] of filtered.entries()) {
+ const previous = filtered[index - 1]
+ const next = filtered[index + 1]
+ record.groupStart = previous === undefined
+ || previous.section !== record.section
+ || previous.group !== record.group
+ record.turnStart = !startedSections.has(record.section)
+ && record.cell.kind !== 'system'
+ && (record.cell.kind !== 'compacted' || record.turn === null)
+ if (record.turnStart) startedSections.add(record.section)
+ record.turnEnd = next === undefined || next.section !== record.section
+ }
+ return filtered
+}
+
+function requestStep(group: string): number | undefined {
+ if (!group.startsWith('Step ')) return undefined
+ const value = Number(group.slice('Step '.length))
+ return Number.isInteger(value) && value > 0 ? value : undefined
+}
+
+function requestKey(turn: number | null, group: string): string {
+ return `${turn}\u0000${group}`
+}
+
+function recordRequestKey(record: TableRecord): string {
+ return record.cell.requestRecordId ?? requestKey(record.turn, record.group)
+}
+
+function indexRequestBoundaries(records: readonly TableRecord[]): ReadonlyMap<string, number> {
+ const boundaries = new Map<string, number>()
+ for (const record of records) {
+ const key = recordRequestKey(record)
+ if (boundaries.has(key)) continue
+ if (requestStep(record.group) === undefined) {
+ if (record.groupStart) boundaries.set(key, record.cell.index)
+ continue
+ }
+ if (
+ record.cell.kind === 'system'
+ || record.cell.kind === 'user'
+ || record.cell.kind === 'context'
+ ) continue
+ boundaries.set(key, record.cell.index)
+ }
+ return boundaries
+}
+
+function sectionLabel(turn: number | null): string {
+ return turn === null ? 'Between turns' : `Turn ${turn}`
+}
+
+function indexRequestNumbers(
+ records: readonly TableRecord[],
+ sessionNumbers: readonly TrajectoryRequestNumber[] | undefined,
+ boundaries: ReadonlyMap<string, number>,
+): ReadonlyMap<string, number> {
+ const numbers = new Map<string, number>()
+ for (const request of sessionNumbers ?? []) {
+ numbers.set(request.recordId ?? requestKey(request.turn, request.group), request.number)
+ }
+ let next = Math.max(0, ...numbers.values()) + 1
+ const boundaryRecords = records
+ .filter(record => boundaries.get(recordRequestKey(record)) === record.cell.index
+ && requestStep(record.group) !== undefined)
+ .sort((left, right) => left.cell.index - right.cell.index)
+ for (const record of boundaryRecords) {
+ const key = recordRequestKey(record)
+ if (!numbers.has(key)) numbers.set(key, next++)
+ }
+ return numbers
+}
+
+function indexRequestBoundaryRuns(records: readonly TableRecord[]): ReadonlyMap<number, number> {
+ const indexes = new Map<number, number>()
+ let runLength = 0
+ for (const record of records) {
+ if (record.cell.requestOnly === true) {
+ indexes.set(record.cell.index, runLength++)
+ continue
+ }
+ if (runLength > 0 && record.groupStart && requestStep(record.group) !== undefined) {
+ indexes.set(record.cell.index, runLength)
+ }
+ runLength = 0
+ }
+ return indexes
+}
+
+function summarizeTurn(records: readonly TableRecord[]): string {
+ const steps = new Set(
+ records
+ .map(record => record.group)
+ .filter(group => group.startsWith('Step ')),
+ ).size
+ const toolCalls = records.filter(record =>
+ record.cell.kind === 'tool' || record.cell.kind === 'subtool',
+ ).length
+ return [
+ `${steps} ${steps === 1 ? 'step' : 'steps'}`,
+ `${toolCalls} tool ${toolCalls === 1 ? 'call' : 'calls'}`,
+ ].join(' · ')
+}
+
+function collapseTurnRecords(
+ records: readonly TableRecord[],
+ collapsedTurns: ReadonlySet<number>,
+): TableRecord[] {
+ const recordsByTurn = new Map<number, TableRecord[]>()
+ for (const record of records) {
+ if (record.turn === null) continue
+ const turnRecords = recordsByTurn.get(record.turn) ?? []
+ turnRecords.push(record)
+ recordsByTurn.set(record.turn, turnRecords)
+ }
+ return records.flatMap((record) => {
+ if (record.turn === null || !collapsedTurns.has(record.turn)) return [record]
+ const turnRecords = recordsByTurn.get(record.turn) ?? [record]
+ if (record.cell.requestOnly === true || record.cell.kind === 'system') return [record]
+ const contentRecords = turnRecords.filter(candidate =>
+ candidate.cell.requestOnly !== true && candidate.cell.kind !== 'system')
+ if (contentRecords.length <= 1) return [record]
+ if (record.cell.index !== contentRecords[0]?.cell.index) return []
+ return [
+ { ...record, turnEnd: false },
+ {
+ ...record,
+ groupStart: false,
+ turnStart: false,
+ turnEnd: true,
+ collapsedSummary: summarizeTurn(contentRecords.slice(1)),
+ collapsedSummaryKind: 'turn',
+ },
+ ]
+ })
+}
+
+function assistantToolCalls(
+ records: readonly TableRecord[],
+ assistantIndex: number,
+): readonly TableRecord[] {
+ const at = records.findIndex(record => record.cell.index === assistantIndex)
+ if (at === -1 || records[at]?.cell.kind !== 'message') return []
+ const calls: TableRecord[] = []
+ for (let i = at + 1; i < records.length; i++) {
+ const record = records[i]
+ if (record === undefined) break
+ if (record.cell.kind !== 'tool' && record.cell.kind !== 'subtool') break
+ calls.push(record)
+ }
+ return calls
+}
+
+function summarizeAssistantTools(records: readonly TableRecord[]): string {
+ const names = [...new Set(records.map((record) => {
+ const separator = record.cell.text.indexOf(' · ')
+ return separator === -1 ? record.cell.text : record.cell.text.slice(0, separator)
+ }).filter(name => name !== ''))]
+ const count = records.length
+ const summary = `${count} tool ${count === 1 ? 'call' : 'calls'}`
+ return names.length > 0 ? `${summary} · ${names.join(', ')}` : summary
+}
+
+function collapseAssistantRecords(
+ records: readonly TableRecord[],
+ collapsedAssistants: ReadonlySet<string>,
+): TableRecord[] {
+ const out: TableRecord[] = []
+ for (let i = 0; i < records.length; i++) {
+ const record = records[i]
+ if (record === undefined) continue
+ out.push(record)
+ if (
+ record.cell.kind !== 'message'
+ || !collapsedAssistants.has(trajectoryRecordId(record.cell))
+ ) continue
+ const calls: TableRecord[] = []
+ for (let j = i + 1; j < records.length; j++) {
+ const candidate = records[j]
+ if (
+ candidate === undefined
+ || candidate.collapsedSummary !== undefined
+ || (candidate.cell.kind !== 'tool' && candidate.cell.kind !== 'subtool')
+ ) break
+ calls.push(candidate)
+ }
+ if (calls.length === 0) continue
+ const last = calls.at(-1)
+ out[out.length - 1] = { ...record, turnEnd: false }
+ out.push({
+ ...record,
+ groupStart: false,
+ turnStart: false,
+ turnEnd: last?.turnEnd ?? false,
+ collapsedSummary: summarizeAssistantTools(calls),
+ collapsedSummaryKind: 'assistant',
+ })
+ i += calls.length
+ }
+ return out
+}
+
+function stateOf(record: TableRecord): RecordState {
+ if (record.cell.status !== undefined) return record.cell.status
+ if (record.cell.isError) return 'error'
+ if (record.cell.kind === 'compacted' && record.cell.timeSeconds === null) return 'running'
+ if (
+ (record.cell.kind === 'tool' || record.cell.kind === 'subtool')
+ && record.cell.outputDetail === undefined
+ ) return 'running'
+ return 'complete'
+}
+
+function statusLabel(state: RecordState): string {
+ if (state === 'error') return 'Failed'
+ if (state === 'running') return 'Pending'
+ return 'Completed'
+}
+
+function TokenRows({ cell }: { cell: TrajectoryCellProps }) {
+ const content = cell.output !== undefined && cell.think !== undefined
+ ? Math.max(0, cell.output - cell.think)
+ : undefined
+ return (
+ <>
+ <div>
+ <dt>Tokens</dt>
+ <dd>{cell.output === undefined ? '—' : `${cell.output} tok`}</dd>
+ </div>
+ {cell.think !== undefined && (
+ <div className={css.requestTokenDetail}>
+ <dt>Reasoning</dt>
+ <dd>{cell.think} tok</dd>
+ </div>
+ )}
+ {content !== undefined && (
+ <div className={css.requestTokenDetail}>
+ <dt>Content</dt>
+ <dd>{content} tok</dd>
+ </div>
+ )}
+ </>
+ )
+}
+
+function inputTotal(usage: TrajectoryUsage): number | undefined {
+ return usage.input
+}
+
+function UsageRows({ usage }: { usage: TrajectoryUsage | undefined }) {
+ if (usage === undefined) return <p className={css.noPayload}>Usage not reported</p>
+ const totalInput = inputTotal(usage)
+ const uncachedInput = usage.input === undefined
+ ? undefined
+ : Math.max(0, usage.input - (usage.cacheRead ?? 0) - (usage.cacheWrite ?? 0))
+ const otherOutput = usage.output !== undefined && usage.reasoning !== undefined
+ ? usage.output - usage.reasoning
+ : undefined
+ return (
+ <dl className={css.overview}>
+ {totalInput !== undefined && (
+ <div><dt>Input</dt><dd>{totalInput} tok</dd></div>
+ )}
+ {usage.cacheRead !== undefined && (
+ <div className={css.requestTokenDetail}>
+ <dt>Cached</dt>
+ <dd>{usage.cacheRead} tok</dd>
+ </div>
+ )}
+ {usage.cacheWrite !== undefined && (
+ <div className={css.requestTokenDetail}>
+ <dt>Cache created</dt>
+ <dd>{usage.cacheWrite} tok</dd>
+ </div>
+ )}
+ {uncachedInput !== undefined && (
+ <div className={css.requestTokenDetail}>
+ <dt>Uncached</dt>
+ <dd>{uncachedInput} tok</dd>
+ </div>
+ )}
+ {usage.output !== undefined && (
+ <div><dt>Output</dt><dd>{usage.output} tok</dd></div>
+ )}
+ {usage.total !== undefined && (
+ <div><dt>Total</dt><dd>{usage.total} tok</dd></div>
+ )}
+ {usage.reasoning !== undefined && (
+ <div className={css.requestTokenDetail}>
+ <dt>Reasoning</dt>
+ <dd>{usage.reasoning} tok</dd>
+ </div>
+ )}
+ {otherOutput !== undefined && (
+ <div className={css.requestTokenDetail}>
+ <dt>Content</dt>
+ <dd>{otherOutput} tok</dd>
+ </div>
+ )}
+ </dl>
+ )
+}
+
+function RequestUsagePanel({
+ usage,
+ cumulative,
+}: {
+ usage: TrajectoryUsage | undefined
+ cumulative: TrajectoryUsage | undefined
+}) {
+ return (
+ <div className={css.usagePanel}>
+ <section className={css.usageGroup}>
+ <h4 className={css.usageHeading}>This request</h4>
+ <UsageRows usage={usage} />
+ </section>
+ <section className={css.usageGroup}>
+ <h4 className={css.usageHeading}>Window cumulative</h4>
+ <UsageRows usage={cumulative} />
+ </section>
+ </div>
+ )
+}
+
+function RequestOptions({
+ options,
+ preview = false,
+}: {
+ options: AssistantRequestConfig | undefined
+ preview?: boolean
+}) {
+ if (options === undefined) {
+ return <p className={css.noPayload}>Options not recorded</p>
+ }
+ return (
+ <JsonTree
+ data={options}
+ label="Request options JSON"
+ className={preview ? css.jsonPreview : css.jsonPayload}
+ />
+ )
+}
+
+function RecordedFacts({
+ facts,
+ preview = false,
+}: {
+ facts: TrajectoryRecordedFacts | undefined
+ preview?: boolean
+}) {
+ if (facts === undefined) {
+ return <p className={css.noPayload}>Recorded facts not available</p>
+ }
+ return (
+ <JsonTree
+ data={facts}
+ label="Recorded trajectory facts JSON"
+ className={preview ? css.jsonPreview : css.jsonPayload}
+ />
+ )
+}
+
+function messageSourceLabel(source: unknown): string {
+ if (typeof source !== 'object' || source === null || Array.isArray(source)) {
+ return 'Unknown'
+ }
+ const properties = source as Record<string, unknown>
+ const kind = properties.kind
+ if (kind === 'user') return 'User'
+ if (kind === 'plugin') {
+ const plugin = properties.plugin
+ return typeof plugin === 'string' && plugin !== ''
+ ? `Plugin · ${plugin}`
+ : 'Plugin'
+ }
+ if (kind === 'goal') {
+ const round = properties.round
+ return typeof round === 'number' && round > 0
+ ? `Goal · Round ${round}`
+ : 'Goal'
+ }
+ if (typeof kind !== 'string' || kind === '') return 'Unknown'
+ return `${kind[0]?.toUpperCase() ?? ''}${kind.slice(1)}`
+}
+
+function MessageSource({ record }: { record: TableRecord }) {
+ const source = record.cell.messageSource
+ if (source === undefined) return <p className={css.noPayload}>Source not recorded</p>
+ const data = typeof source === 'object' && source !== null
+ ? source
+ : { value: source }
+ return (
+ <JsonTree
+ data={data}
+ label="Message source JSON"
+ className={css.jsonPayload}
+ />
+ )
+}
+
+function isMarkdownRecord(record: TableRecord): boolean {
+ return record.cell.kind === 'user'
+ || record.cell.kind === 'context'
+ || record.cell.kind === 'message'
+}
+
+function parentRecords(
+ records: readonly TableRecord[],
+ record: TableRecord,
+): ParentRecords {
+ if (record.cell.kind !== 'tool' && record.cell.kind !== 'subtool') return {}
+ const at = records.findIndex(candidate => candidate.cell.index === record.cell.index)
+ if (at === -1) return {}
+ let tool: TableRecord | undefined
+ if (record.cell.kind === 'subtool') {
+ for (let i = at - 1; i >= 0; i--) {
+ const candidate = records[i]
+ if (
+ candidate === undefined
+ || candidate.turn !== record.turn
+ || candidate.group !== record.group
+ ) break
+ if (candidate.cell.kind === 'tool') {
+ tool = candidate
+ break
+ }
+ }
+ }
+ const parentCallId = tool?.cell.callId ?? record.cell.callId
+ let message: TableRecord | undefined
+ if (parentCallId !== undefined) {
+ message = records.find(candidate =>
+ candidate.turn === record.turn
+ && candidate.cell.kind === 'message'
+ && candidate.cell.sourceBlocks?.some(block => block.callId === parentCallId) === true,
+ )
+ }
+ return { ...(message === undefined ? {} : { message }), ...(tool === undefined ? {} : { tool }) }
+}
+
+function markdownSource(record: TableRecord): string | undefined {
+ if (record.cell.kind === 'user' || record.cell.kind === 'context') {
+ return record.cell.inputDetail
+ }
+ if (record.cell.kind === 'message' || record.cell.kind === 'compacted') {
+ return record.cell.outputDetail
+ }
+ return undefined
+}
+
+function detailTabs(record: TableRecord): readonly DetailTabItem[] {
+ const otel = record.cell.traceDetail === undefined
+ ? []
+ : [{ id: 'otel', label: 'OTel' } as const]
+ if (record.cell.kind === 'system') {
+ const promptTabs = record.cell.previousPromptDetail === undefined
+ ? SYSTEM_PROMPT_TABS
+ : SYSTEM_UPDATE_TABS
+ return [...promptTabs, ...otel]
+ }
+ if (record.cell.kind === 'compacted') {
+ return [
+ { id: 'overview', label: 'Summary' },
+ { id: 'raw', label: 'Raw Output' },
+ ...otel,
+ ]
+ }
+ if (isMarkdownRecord(record)) {
+ return [
+ { id: 'overview', label: 'Summary' },
+ { id: 'rendered', label: 'Preview' },
+ { id: 'raw', label: 'Raw' },
+ ...(record.cell.messageSource === undefined
+ ? []
+ : [{ id: 'source', label: 'Source' } as const]),
+ ...otel,
+ ]
+ }
+ return [
+ { id: 'overview', label: 'Summary' },
+ ...(record.cell.inputDetail ? [{ id: 'input', label: 'Payload' } as const] : []),
+ ...(record.cell.outputDetail ? [{ id: 'output', label: 'Result' } as const] : []),
+ { id: 'schema', label: 'Schema' },
+ { id: 'timing', label: 'Timing' },
+ ...otel,
+ ]
+}
+
+function recordDisplayText(cell: TrajectoryCellProps): string {
+ if (isToolCallOnly(cell)) return ''
+ if (cell.previewMarkdown !== undefined) {
+ const preview = trajectoryPreviewText(cell.previewMarkdown)
+ if (cell.text === '') return preview
+ return preview === '' ? cell.text : `${cell.text} · ${preview}`
+ }
+ if (cell.text !== '') return cell.text
+ const markdown = cell.kind === 'user' || cell.kind === 'context'
+ ? cell.inputDetail
+ : cell.kind === 'message'
+ ? cell.outputDetail ?? cell.thinkingDetail
+ : undefined
+ return markdown === undefined ? '' : trajectoryPreviewText(markdown)
+}
+
+function recordResultText(cell: TrajectoryCellProps): string | undefined {
+ return cell.resultPreviewMarkdown === undefined
+ ? cell.result
+ : trajectoryPreviewText(cell.resultPreviewMarkdown)
+}
+
+function toolCallTextParts(
+ kind: TrajectoryCellKind,
+ text: string,
+): ToolCallTextParts | undefined {
+ if (kind !== 'tool' && kind !== 'subtool') return undefined
+ const separator = text.indexOf(' · ')
+ if (separator === -1) return { name: text }
+ return {
+ name: text.slice(0, separator),
+ args: text.slice(separator + 3),
+ }
+}
+
+function isToolCallOnly(cell: TrajectoryCellProps): boolean {
+ return cell.kind === 'message'
+ && !cell.outputDetail
+ && !cell.thinkingDetail
+ && cell.text === 'Tool call only'
+}
+
+interface RecordPresentationValue {
+ displayText: string
+ listDisplayText: string
+ resultText: string | undefined
+ toolCallOnly: boolean
+ toolCallText: ToolCallTextParts | undefined
+}
+
+function RecordPresentation({
+ cell,
+ children,
+}: {
+ cell: TrajectoryCellProps
+ children: (value: RecordPresentationValue) => ReactNode
+}) {
+ const displayText = useMemo(
+ () => recordDisplayText(cell),
+ [
+ cell.kind, cell.text, cell.previewMarkdown,
+ cell.inputDetail, cell.outputDetail, cell.thinkingDetail,
+ ],
+ )
+ const resultText = useMemo(
+ () => recordResultText(cell),
+ [cell.result, cell.resultPreviewMarkdown],
+ )
+ const toolCallOnly = isToolCallOnly(cell)
+ const toolCallText = toolCallTextParts(cell.kind, displayText)
+ const listDisplayText = toolCallOnly
+ ? '(tool call only)'
+ : toolCallText === undefined
+ ? displayText
+ : [toolCallText.name, toolCallText.args].filter(Boolean).join(' ')
+ return children({
+ displayText,
+ listDisplayText,
+ resultText,
+ toolCallOnly,
+ toolCallText,
+ })
+}
+
+function RecordListText({
+ displayText,
+ toolCallOnly,
+ toolCallText,
+}: Pick<RecordPresentationValue, 'displayText' | 'toolCallOnly' | 'toolCallText'>) {
+ if (toolCallOnly) {
+ return <span className={css.toolCallOnly}>(tool call only)</span>
+ }
+ if (toolCallText === undefined) return displayText || '—'
+ return (
+ <>
+ <span className={css.toolCallNameTypeface}>
+ {toolCallText.name || '—'}
+ </span>
+ {toolCallText.args !== undefined && (
+ <span className={css.toolCallPayload}>
+ {toolCallText.args}
+ </span>
+ )}
+ </>
+ )
+}
+
+function MarkdownFragment({
+ text,
+ rendered,
+ preview,
+}: {
+ text: string
+ rendered: boolean
+ preview: boolean
+}) {
+ if (rendered) {
+ return (
+ <div className={preview ? css.markdownPreview : css.markdownPayload}>
+ <MarkdownText text={text} />
+ </div>
+ )
+ }
+ return (
+ <pre className={`${css.payload} ${preview ? css.payloadPreview : ''}`}>
+ {text}
+ </pre>
+ )
+}
+
+function SourceBlocks({
+ blocks,
+ onOpenCall,
+}: {
+ blocks: readonly TrajectorySourceBlock[]
+ onOpenCall: (callId: string) => void
+}) {
+ return (
+ <div className={css.sourceBlocks}>
+ {blocks.map((block, index) => (
+ <section className={css.sourceBlock} key={index}>
+ {block.callId !== undefined
+ ? (
+ <button
+ type="button"
+ className={css.sourceBlockJumpTarget}
+ aria-label={`Open Block #${index + 1} tool call summary`}
+ title="Open tool call summary"
+ onClick={() => {
+ if (block.callId !== undefined) onOpenCall(block.callId)
+ }}
+ >
+ <span className={css.sourceBlockLabel}>
+ {`Block #${index + 1} ${block.type}`}
+ </span>
+ <IconChevronRightOutline14 className={css.sourceBlockJumpIcon} size={12} />
+ </button>
+ )
+ : (
+ <div className={css.sourceBlockHeader}>
+ <span className={css.sourceBlockLabel}>
+ {`Block #${index + 1} ${block.type}`}
+ </span>
+ </div>
+ )}
+ {block.imageSrc !== undefined
+ ? <PanelImage block={block} />
+ : <pre className={css.sourceBlockContent}>{block.content}</pre>}
+ </section>
+ ))}
+ </div>
+ )
+}
+
+function PanelImage({
+ block,
+ preview = false,
+}: {
+ block: TrajectorySourceBlock
+ preview?: boolean
+}) {
+ if (block.imageSrc === undefined) return null
+ return (
+ <a
+ className={preview ? `${css.panelImageLink} ${css.panelImageLinkPreview}` : css.panelImageLink}
+ href={block.imageSrc}
+ target="_blank"
+ rel="noopener noreferrer"
+ title="Open image"
+ >
+ <img
+ className={css.panelImage}
+ src={block.imageSrc}
+ alt={block.imageAlt ?? ''}
+ />
+ </a>
+ )
+}
+
+function MessageImages({
+ blocks,
+ preview,
+}: {
+ blocks: readonly TrajectorySourceBlock[] | undefined
+ preview: boolean
+}) {
+ const images = blocks?.filter(block => block.imageSrc !== undefined) ?? []
+ if (images.length === 0) return null
+ return (
+ <div className={preview ? `${css.messageImages} ${css.messageImagesPreview}` : css.messageImages}>
+ {images.map((block, index) => <PanelImage block={block} preview={preview} key={index} />)}
+ </div>
+ )
+}
+
+function AssistantToolCalls({
+ blocks,
+ preview,
+ onOpenCall,
+}: {
+ blocks: readonly TrajectorySourceBlock[] | undefined
+ preview: boolean
+ onOpenCall: (callId: string) => void
+}) {
+ const calls = blocks?.filter(block => block.type === 'tool-call') ?? []
+ if (calls.length === 0) return null
+ return (
+ <ul className={preview
+ ? `${css.assistantToolCalls} ${css.assistantToolCallsPreview}`
+ : css.assistantToolCalls}
+ >
+ {calls.map((call, index) => (
+ <li key={call.callId ?? index}>
+ <button
+ type="button"
+ className={css.assistantToolCallButton}
+ title="Open tool call summary"
+ onClick={() => {
+ if (call.callId !== undefined) onOpenCall(call.callId)
+ }}
+ >
+ <svg
+ className={css.assistantToolCallIcon}
+ width="12"
+ height="12"
+ viewBox="0 0 24 24"
+ fill="none"
+ aria-hidden="true"
+ >
+ <path
+ d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94z"
+ stroke="currentColor"
+ strokeWidth="1.8"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ <span className={css.assistantToolCallText}>
+ <span className={css.assistantToolCallName}>
+ {call.toolName ?? 'tool-call'}
+ </span>
+ {call.content !== '' && (
+ <span className={css.assistantToolCallArgs}>{call.content}</span>
+ )}
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ )
+}
+
+function ToolGlyph() {
+ return (
+ <svg
+ className={css.toolCatalogIcon}
+ width="12"
+ height="12"
+ viewBox="0 0 24 24"
+ fill="none"
+ aria-hidden="true"
+ >
+ <path
+ d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94z"
+ stroke="currentColor"
+ strokeWidth="1.8"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ )
+}
+
+function ToolCatalog({ tools }: { tools: TrajectoryPromptSnapshot['tools'] }) {
+ if (tools.length === 0) return <p className={css.noPayload}>No tools in this request</p>
+ return (
+ <div className={css.toolCatalog}>
+ {tools.map((tool, index) => (
+ <details className={css.toolCatalogItem} key={`${tool.name}:${index}`}>
+ <summary className={css.toolCatalogSummary}>
+ <IconChevronRightOutline14 className={css.toolCatalogChevron} size={12} />
+ <ToolGlyph />
+ <span className={css.toolCatalogName}>{tool.name}</span>
+ <span className={css.toolCatalogDescription}>{tool.description}</span>
+ </summary>
+ <div className={css.toolCatalogDefinition}>
+ {tool.description !== '' && (
+ <p className={css.toolCatalogFullDescription}>{tool.description}</p>
+ )}
+ <JsonTree
+ data={tool.parameters}
+ label={`${tool.name} parameters JSON`}
+ className={css.toolCatalogTree}
+ />
+ </div>
+ </details>
+ ))}
+ </div>
+ )
+}
+
+interface PromptDiffLine {
+ kind: 'meta' | 'context' | 'added' | 'removed'
+ text: string
+}
+
+function promptDiffLines(before: string, after: string): readonly PromptDiffLine[] {
+ const patch = structuredPatch('', '', before, after, undefined, undefined, { context: 3 })
+ return patch.hunks.flatMap((hunk, hunkIndex) => [
+ ...(hunkIndex === 0 ? [] : [{ kind: 'meta' as const, text: '' }]),
+ {
+ kind: 'meta' as const,
+ text: `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`,
+ },
+ ...hunk.lines.flatMap((line): PromptDiffLine[] => {
+ if (line.startsWith('\\')) return []
+ if (line.startsWith('+')) return [{ kind: 'added', text: line }]
+ if (line.startsWith('-')) return [{ kind: 'removed', text: line }]
+ return [{ kind: 'context', text: line }]
+ }),
+ ])
+}
+
+function PromptDiffSection({
+ title,
+ before,
+ after,
+}: {
+ title: string
+ before: string
+ after: string
+}) {
+ const lines = promptDiffLines(before, after)
+ if (lines.length === 0) return null
+ return (
+ <section className={css.promptDiffSection}>
+ <h3 className={css.promptDiffTitle}>{title}</h3>
+ <pre className={css.promptDiff}>
+ {lines.map((line, index) => (
+ <span className={css[`promptDiffLine${line.kind}`]} key={index}>
+ {line.text || ' '}
+ {'\n'}
+ </span>
+ ))}
+ </pre>
+ </section>
+ )
+}
+
+function SystemPromptDiff({
+ before,
+ after,
+}: {
+ before: TrajectoryPromptSnapshot
+ after: TrajectoryPromptSnapshot
+}) {
+ const toolsBefore = JSON.stringify(before.tools, null, 2)
+ const toolsAfter = JSON.stringify(after.tools, null, 2)
+ return (
+ <div className={css.promptDiffSections}>
+ {before.system !== after.system && (
+ <PromptDiffSection
+ title="System Prompt"
+ before={before.system}
+ after={after.system}
+ />
+ )}
+ {toolsBefore !== toolsAfter && (
+ <PromptDiffSection
+ title="Tools"
+ before={toolsBefore}
+ after={toolsAfter}
+ />
+ )}
+ </div>
+ )
+}
+
+function ToolOutputBlocks({
+ blocks,
+ error,
+ preview,
+}: {
+ blocks: readonly TrajectorySourceBlock[]
+ error: boolean
+ preview: boolean
+}) {
+ return (
+ <div className={[
+ css.resultBlocks,
+ preview ? css.resultBlocksPreview : undefined,
+ error ? css.errorPayload : undefined,
+ ].filter((value): value is string => value !== undefined).join(' ')}
+ >
+ {blocks.map((block, index) => (
+ block.imageSrc !== undefined
+ ? <PanelImage block={block} preview={preview} key={index} />
+ : block.content !== ''
+ ? <pre className={css.resultBlockText} key={index}>{block.content}</pre>
+ : null
+ ))}
+ </div>
+ )
+}
+
+function MarkdownRecordContent({
+ record,
+ rendered,
+ preview = false,
+ thinkingExpanded,
+ onThinkingExpandedChange,
+ onOpenCall,
+}: {
+ record: TableRecord
+ rendered: boolean
+ preview?: boolean
+ thinkingExpanded: boolean
+ onThinkingExpandedChange: (expanded: boolean) => void
+ onOpenCall: (callId: string) => void
+}) {
+ if (!rendered && record.cell.sourceBlocks && record.cell.sourceBlocks.length > 0) {
+ return <SourceBlocks blocks={record.cell.sourceBlocks} onOpenCall={onOpenCall} />
+ }
+ if (record.cell.thinkingDetail) {
+ if (!rendered) {
+ const source = [
+ record.cell.thinkingDetail,
+ record.cell.outputDetail,
+ ].filter((value): value is string => value !== undefined && value !== '').join('\n\n')
+ return <MarkdownFragment text={source} rendered={false} preview={preview} />
+ }
+ return (
+ <div className={`${css.assistantContent} ${css.assistantContentRendered}`}>
+ <div className={
+ preview && !record.cell.outputDetail
+ ? `${css.thinkingQuote} ${css.thinkingQuoteOnlyPreview}`
+ : css.thinkingQuote
+ }
+ >
+ <button
+ type="button"
+ className={css.thinkingToggle}
+ aria-expanded={thinkingExpanded}
+ onClick={() => { onThinkingExpandedChange(!thinkingExpanded) }}
+ >
+ Thinking
+ <IconChevronRightOutline14 className={css.thinkingChevron} size={12} />
+ </button>
+ {thinkingExpanded && (
+ <MarkdownFragment
+ text={record.cell.thinkingDetail}
+ rendered={rendered}
+ preview={preview}
+ />
+ )}
+ </div>
+ {record.cell.outputDetail && (
+ <div className={css.assistantOutput}>
+ <MarkdownFragment
+ text={record.cell.outputDetail}
+ rendered={rendered}
+ preview={preview}
+ />
+ </div>
+ )}
+ <AssistantToolCalls
+ blocks={record.cell.sourceBlocks}
+ preview={preview}
+ onOpenCall={onOpenCall}
+ />
+ <MessageImages
+ blocks={record.cell.sourceBlocks}
+ preview={preview}
+ />
+ </div>
+ )
+ }
+ const source = markdownSource(record)
+ const hasImages = record.cell.sourceBlocks?.some(block => block.imageSrc !== undefined) === true
+ const hasToolCalls = record.cell.kind === 'message'
+ && record.cell.sourceBlocks?.some(block => block.type === 'tool-call') === true
+ if (!source && !hasImages && !hasToolCalls) {
+ const emptyLabel = isToolCallOnly(record.cell)
+ ? 'Tool call only'
+ : record.cell.text || 'No content'
+ return <p className={css.noPayload}>{emptyLabel}</p>
+ }
+ if (!rendered || (!hasImages && !hasToolCalls)) {
+ return <MarkdownFragment text={source ?? ''} rendered={rendered} preview={preview} />
+ }
+ return (
+ <div>
+ {source && <MarkdownFragment text={source} rendered preview={preview} />}
+ {record.cell.kind === 'message' && (
+ <AssistantToolCalls
+ blocks={record.cell.sourceBlocks}
+ preview={preview}
+ onOpenCall={onOpenCall}
+ />
+ )}
+ <MessageImages blocks={record.cell.sourceBlocks} preview={preview} />
+ </div>
+ )
+}
+
+function RecordTiming({ record }: { record: TableRecord }) {
+ return record.cell.kind === 'message' && record.cell.assistantMetrics !== undefined
+ ? <AssistantTimingPanel metrics={record.cell.assistantMetrics} />
+ : (
+ <dl className={css.overview}>
+ <div><dt>Started</dt><StartedAtValue timestamp={record.cell.startedAt ?? null} /></div>
+ <div><dt>Duration</dt><dd>{formatElapsedSeconds(record.cell.timeSeconds)}</dd></div>
+ <div><dt>Timing source</dt><dd>{record.cell.timeSeconds === null ? 'Not available' : 'Recorded timestamps'}</dd></div>
+ </dl>
+ )
+}
+
+function RequestTiming({
+ assistant,
+ anchor,
+ request,
+}: {
+ assistant: TableRecord | undefined
+ anchor: TableRecord | undefined
+ request: TrajectoryRequestNumber | undefined
+}) {
+ if (assistant !== undefined) return <RecordTiming record={assistant} />
+ if (request?.startedAt !== undefined) {
+ const duration = request.completedAt === null || request.completedAt === undefined
+ ? null
+ : Math.max(0, (request.completedAt - request.startedAt) / 1000)
+ return (
+ <dl className={css.overview}>
+ <div><dt>Started</dt><StartedAtValue timestamp={request.startedAt} /></div>
+ <div><dt>Duration</dt><dd>{formatElapsedSeconds(duration)}</dd></div>
+ <div>
+ <dt>Timing source</dt>
+ <dd>{duration === null ? 'Recorded timestamps (running)' : 'Recorded timestamps'}</dd>
+ </div>
+ </dl>
+ )
+ }
+ return (
+ <dl className={css.overview}>
+ <div>
+ <dt>Started</dt>
+ <StartedAtValue timestamp={anchor?.cell.startedAt ?? null} />
+ </div>
+ <div><dt>Duration</dt><dd>{formatElapsedSeconds(null)}</dd></div>
+ </dl>
+ )
+}
+
+function RecordPayload({
+ record,
+ direction,
+ preview = false,
+}: {
+ record: TableRecord
+ direction: 'input' | 'output'
+ preview?: boolean
+}) {
+ const value = direction === 'input' ? record.cell.inputDetail : record.cell.outputDetail
+ const missing = direction === 'input'
+ ? 'No payload captured'
+ : 'No result captured'
+ if (!value) return <p className={css.noPayload}>{missing}</p>
+ const error = direction === 'output' && record.cell.isError === true
+ const payloadClass = preview ? css.jsonPreview : css.jsonPayload
+ const payloadClassName = error ? `${payloadClass} ${css.errorPayload}` : payloadClass
+
+ const json = parseJsonContainer(value)
+ const singleTextResult = direction === 'output'
+ && record.cell.outputBlocks?.length === 1
+ && record.cell.outputBlocks[0]?.type === 'text'
+ if (singleTextResult && json !== undefined) {
+ return (
+ <JsonTree
+ data={json}
+ label="Result JSON"
+ className={payloadClassName}
+ />
+ )
+ }
+
+ if (
+ direction === 'output'
+ && record.cell.outputBlocks?.some(block =>
+ block.imageSrc !== undefined || block.content !== '') === true
+ ) {
+ return (
+ <ToolOutputBlocks
+ blocks={record.cell.outputBlocks}
+ error={error}
+ preview={preview}
+ />
+ )
+ }
+
+ const markdown = (
+ direction === 'input'
+ && (record.cell.kind === 'user' || record.cell.kind === 'context')
+ ) || (
+ direction === 'output' && record.cell.kind === 'message'
+ )
+ if (markdown) {
+ return (
+ <div className={[
+ preview ? css.markdownPreview : css.markdownPayload,
+ error ? css.errorPayload : undefined,
+ ].filter((className): className is string => className !== undefined).join(' ')}
+ >
+ <MarkdownText text={value} />
+ </div>
+ )
+ }
+ if (json !== undefined) {
+ return (
+ <JsonTree
+ data={json}
+ label={`${direction === 'input' ? 'Payload' : 'Result'} JSON`}
+ className={payloadClassName}
+ />
+ )
+ }
+ return (
+ <pre className={[
+ css.payload,
+ preview ? css.payloadPreview : undefined,
+ error ? css.errorPayload : undefined,
+ value === 'No output' ? css.noOutputText : undefined,
+ ].filter((value): value is string => value !== undefined).join(' ')}
+ >
+ {value}
+ </pre>
+ )
+}
+
+function RecordSchema({
+ record,
+ preview = false,
+}: {
+ record: TableRecord
+ preview?: boolean
+}) {
+ if (!record.cell.schemaDetail) {
+ return <p className={css.noPayload}>Schema unavailable</p>
+ }
+ const schema = parseToolSchema(record.cell.schemaDetail)
+ if (schema !== undefined) {
+ return (
+ <div className={preview ? `${css.schema} ${css.schemaPreview}` : css.schema}>
+ <header className={css.schemaIntro}>
+ <h3 className={css.schemaName}>{schema.name}</h3>
+ <p className={css.schemaDescription}>{schema.description}</p>
+ </header>
+ <section className={css.schemaParameters}>
+ <h4 className={css.schemaParametersTitle}>Parameters</h4>
+ <JsonTree
+ data={schema.parameters}
+ label={`${schema.name} parameters JSON`}
+ className={css.schemaTree}
+ />
+ </section>
+ </div>
+ )
+ }
+ return (
+ <pre className={`${css.payload} ${preview ? css.payloadPreview : ''}`}>
+ {record.cell.schemaDetail}
+ </pre>
+ )
+}
+
+interface ParsedToolSchema {
+ name: string
+ description: string
+ parameters: object
+}
+
+function parseToolSchema(value: string): ParsedToolSchema | undefined {
+ try {
+ const parsed: unknown = JSON.parse(value)
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined
+ const schema = parsed as Record<string, unknown>
+ if (
+ typeof schema.name !== 'string'
+ || typeof schema.description !== 'string'
+ || typeof schema.parameters !== 'object'
+ || schema.parameters === null
+ || Array.isArray(schema.parameters)
+ ) return undefined
+ return {
+ name: schema.name,
+ description: schema.description,
+ parameters: schema.parameters,
+ }
+ } catch {
+ return undefined
+ }
+}
+
+function parseJsonContainer(value: string): object | undefined {
+ try {
+ const parsed: unknown = JSON.parse(value)
+ return typeof parsed === 'object' && parsed !== null ? parsed : undefined
+ } catch {
+ return undefined
+ }
+}
+
+function OverviewSection({
+ label,
+ onOpen,
+ children,
+}: {
+ label: string
+ onOpen: () => void
+ children: ReactNode
+}) {
+ return (
+ <section className={css.overviewSection}>
+ <h3 className={css.overviewHeading}>
+ <button
+ type="button"
+ className={css.overviewTitle}
+ onClick={onOpen}
+ >
+ <span>{label}</span>
+ <IconChevronRightOutline14 className={css.overviewTitleIcon} size={12} />
+ </button>
+ </h3>
+ <div
+ className={`${css.overviewPreview} ${css.summaryScrollRegion}`}
+ data-summary-scroll-region=""
+ >
+ {children}
+ </div>
+ </section>
+ )
+}
+
+/**
+ * Render trajectory events as a dense ledger with turn and step separators.
+ * Clicking ledger whitespace clears the active record or request selection.
+ * @param props - Grouped trajectory data and whole-ledger fold state.
+ * @returns The ledger and an optional local record inspector.
+ */
+export function TrajectoryTable({
+ requestNumbers: sessionRequestNumbers,
+ turns,
+ streamingCells = [],
+ timelineFocusIndexes = null,
+ searchMatchIndexes = null,
+ onSelectedIndexChange,
+ onRecordSelect,
+ recordSelection = null,
+ recordFocus = null,
+ historyLoading = false,
+ olderHistoryLoading = false,
+ historyStartSeq,
+ hasOlderRecords = false,
+ onLoadOlder,
+ onClearSelection,
+ collapsedTurns,
+ onToggleTurn,
+ collapsedAssistants,
+ onToggleAssistant,
+ inspectCallId = null,
+ onInspectApplied,
+ nowMilliseconds = Date.now(),
+}: TrajectoryTableProps) {
+ const [selectedRecordId, setSelectedRecordId] = useState<string | null>(null)
+ const [selectedRequest, setSelectedRequest] = useState<SelectedRequest | null>(null)
+ const [activeTab, setActiveTab] = useState<DetailTab>('overview')
+ const [thinkingExpanded, setThinkingExpanded] = useState(false)
+ const [detailsWidth, setDetailsWidth] = useState<number | null>(null)
+ const [toolRequestOffset, setToolRequestOffset] = useState<number | null>(null)
+ const detailsResizeDrag = useRef<DetailsResizeDrag | null>(null)
+ const appliedRecordSelection = useRef<TrajectoryTableProps['recordSelection']>(null)
+ const appliedRecordFocus = useRef<TrajectoryTableProps['recordFocus']>(null)
+ const tabHistory = useRef<Set<DetailTab>>(new Set(['overview']))
+ const rootRef = useRef<HTMLDivElement>(null)
+ const tablePaneRef = useRef<HTMLDivElement>(null)
+ const followsTableTail = useRef(false)
+ const tableScrollInitialized = useRef(false)
+ const [tableScrollReady, setTableScrollReady] = useState(false)
+ const pendingScrollRecordId = useRef<string | null>(null)
+ const loadingOlder = useRef<Promise<boolean> | null>(null)
+ const [olderLoading, setOlderLoading] = useState(false)
+ const olderLoadAnchor = useRef<OlderLoadAnchor | null>(null)
+ useEffect(() => {
+ loadingOlder.current = null
+ olderLoadAnchor.current = null
+ setOlderLoading(false)
+ }, [onLoadOlder])
+ const allRecords = useMemo(() => flattenRecords(turns), [turns])
+ const streamingCellsByIndex = useMemo(
+ () => new Map(streamingCells.map(cell => [cell.index, cell])),
+ [streamingCells],
+ )
+ const currentRecord = useCallback((record: TableRecord): TableRecord => {
+ const cell = streamingCellsByIndex.get(record.cell.index)
+ return cell === undefined ? record : { ...record, cell }
+ }, [streamingCellsByIndex])
+ const selectedTemplate = useMemo(() => selectedRecordId === null
+ ? undefined
+ : allRecords.find(record => trajectoryRecordId(record.cell) === selectedRecordId),
+ [allRecords, selectedRecordId])
+ const selected = selectedTemplate === undefined
+ ? undefined
+ : currentRecord(selectedTemplate)
+ const selectedIndex = selected?.cell.index ?? null
+ useEffect(() => {
+ onSelectedIndexChange?.(selectedIndex)
+ }, [onSelectedIndexChange, selectedIndex])
+ const requestBoundaries = useMemo(() => indexRequestBoundaries(allRecords), [allRecords])
+ const requestNumbers = useMemo(
+ () => indexRequestNumbers(allRecords, sessionRequestNumbers, requestBoundaries),
+ [allRecords, requestBoundaries, sessionRequestNumbers],
+ )
+ const records = useMemo(() => {
+ if (searchMatchIndexes !== null) return filterRecords(allRecords, searchMatchIndexes)
+ const turnRecords = collapsedTurns.size === 0
+ ? allRecords
+ : collapseTurnRecords(allRecords, collapsedTurns)
+ return collapsedAssistants.size === 0
+ ? turnRecords
+ : collapseAssistantRecords(turnRecords, collapsedAssistants)
+ }, [allRecords, collapsedAssistants, collapsedTurns, searchMatchIndexes])
+ const projectedVirtualRows = useMemo(
+ () => groupTrajectoryVirtualRows(records),
+ [records],
+ )
+ const virtualRowStructure = useStableVirtualRowStructure(projectedVirtualRows)
+ const virtualizationEnabled = hasOlderRecords
+ || records.length > VIRTUALIZATION_THRESHOLD
+ const virtualScrollMargin = hasOlderRecords ? HISTORY_LOAD_ROW_HEIGHT_PX : 0
+ const estimateVirtualRowSize = useCallback(
+ (index: number) => virtualRowStructure[index]?.height ?? 30,
+ [virtualRowStructure],
+ )
+ const getVirtualRowKey = useCallback(
+ (index: number) => virtualRowStructure[index]?.key ?? index,
+ [virtualRowStructure],
+ )
+ const getTableScrollElement = useCallback(() => tablePaneRef.current, [])
+ const rowVirtualizer = useVirtualizer<HTMLDivElement, HTMLTableRowElement>({
+ count: virtualizationEnabled ? virtualRowStructure.length : 0,
+ enabled: virtualizationEnabled,
+ estimateSize: estimateVirtualRowSize,
+ getItemKey: getVirtualRowKey,
+ getScrollElement: getTableScrollElement,
+ initialRect: { width: 0, height: VIRTUAL_INITIAL_VIEWPORT_HEIGHT_PX },
+ anchorTo: 'end',
+ overscan: VIRTUAL_OVERSCAN_ROWS,
+ scrollMargin: virtualScrollMargin,
+ scrollEndThreshold: BOTTOM_FOLLOW_THRESHOLD_PX,
+ })
+ const virtualIndexByRecordId = useMemo(() => {
+ const indexes = new Map<string, number>()
+ for (const [virtualIndex, row] of projectedVirtualRows.entries()) {
+ for (const entry of row.entries) {
+ if (entry.record.collapsedSummary === undefined) {
+ indexes.set(trajectoryRecordId(entry.record.cell), virtualIndex)
+ }
+ }
+ }
+ return indexes
+ }, [projectedVirtualRows])
+ const virtualItems = virtualizationEnabled ? rowVirtualizer.getVirtualItems() : []
+ const virtualTop = Math.max(0, (virtualItems[0]?.start ?? 0) - virtualScrollMargin)
+ const virtualBottom = virtualItems.length === 0
+ ? 0
+ : Math.max(
+ 0,
+ rowVirtualizer.getTotalSize()
+ + virtualScrollMargin
+ - (virtualItems.at(-1)?.end ?? 0),
+ )
+ const renderedRecords = virtualizationEnabled
+ ? virtualItems.flatMap((item) => {
+ const row = projectedVirtualRows[item.index]
+ if (row === undefined) return []
+ return row.entries.map((entry, entryIndex) => ({
+ record: currentRecord(entry.record),
+ position: entry.logicalIndex,
+ terminalRequestBoundary:
+ entry.record.cell.requestOnly === true
+ && row.entries.at(-1)?.record.cell.requestOnly === true
+ && entryIndex === row.entries.length - 1,
+ }))
+ })
+ : records.map((record, position) => ({
+ record: currentRecord(record),
+ position,
+ terminalRequestBoundary:
+ record.cell.requestOnly === true && position === records.length - 1,
+ }))
+ const requestBoundaryRuns = useMemo(
+ () => indexRequestBoundaryRuns(records),
+ [records],
+ )
+ const selectedPrompt = selected?.cell.kind === 'system'
+ ? selected.cell.promptDetail
+ : undefined
+ const selectedPreviousPrompt = selected?.cell.kind === 'system'
+ ? selected.cell.previousPromptDetail
+ : undefined
+ const promptSelected = selectedPrompt !== undefined
+ const selectedState = selected === undefined ? undefined : stateOf(selected)
+ const selectedRequestRecordTemplates = useMemo(() => selectedRequest === null
+ ? []
+ : allRecords.filter(record =>
+ recordRequestKey(record) === selectedRequest.recordId,
+ ), [allRecords, selectedRequest])
+ const selectedRequestRecords = selectedRequestRecordTemplates.map(currentRecord)
+ const selectedRequestAssistant = selectedRequestRecords.find(
+ record => record.cell.kind === 'message',
+ )
+ const selectedRequestAnchor = selectedRequestAssistant ?? selectedRequestRecords[0]
+ const selectedRequestNumber = selectedRequest === null
+ ? undefined
+ : requestNumbers.get(selectedRequest.recordId)
+ const selectedRequestInfo = selectedRequest === null
+ ? undefined
+ : sessionRequestNumbers?.find(request => selectedRequest.seq === undefined
+ ? (request.recordId ?? requestKey(request.turn, request.group)) === selectedRequest.recordId
+ : request.seq === selectedRequest.seq)
+ const selectedRequestState: RecordState | undefined = selectedRequest === null
+ ? undefined
+ : selectedRequestInfo?.status
+ ?? (selectedRequestAssistant?.cell.assistantMetrics?.completedTime === null
+ ? 'running'
+ : selectedRequestAssistant === undefined
+ && selectedRequestRecords.some(record => stateOf(record) === 'running')
+ ? 'running'
+ : 'complete')
+ const selectedRequestToolCalls = selectedRequestRecords.filter(
+ record => record.cell.kind === 'tool',
+ ).length
+ const selectedRequestSubtoolCalls = selectedRequestRecords.filter(
+ record => record.cell.kind === 'subtool',
+ ).length
+ const selectedRequestResultTemplate = selectedRequestInfo?.resultSeq === undefined
+ ? selectedRequestAssistant
+ : allRecords.find(record => record.cell.sourceSeq === selectedRequestInfo.resultSeq)
+ const selectedRequestResult = selectedRequestResultTemplate === undefined
+ ? undefined
+ : currentRecord(selectedRequestResultTemplate)
+ const selectedRequestUsage = selectedRequestInfo?.usage ?? (
+ selectedRequestAssistant === undefined
+ ? undefined
+ : {
+ ...(selectedRequestAssistant.cell.input === undefined
+ ? {}
+ : { input: selectedRequestAssistant.cell.input }),
+ ...(selectedRequestAssistant.cell.cacheRead === undefined
+ ? {}
+ : { cacheRead: selectedRequestAssistant.cell.cacheRead }),
+ ...(selectedRequestAssistant.cell.cacheWrite === undefined
+ ? {}
+ : { cacheWrite: selectedRequestAssistant.cell.cacheWrite }),
+ ...(selectedRequestAssistant.cell.output === undefined
+ ? {}
+ : { output: selectedRequestAssistant.cell.output }),
+ ...(selectedRequestAssistant.cell.think === undefined
+ ? {}
+ : { reasoning: selectedRequestAssistant.cell.think }),
+ ...(selectedRequestAssistant.cell.total === undefined
+ ? {}
+ : { total: selectedRequestAssistant.cell.total }),
+ }
+ )
+ const selectedRequestCumulativeUsage =
+ selectedRequestInfo?.cumulativeUsage ?? selectedRequestUsage
+ const selectedRequestOptions = selectedRequestInfo?.requestConfig
+ const selectedRequestFacts = selectedRequestInfo?.recordedFacts
+ const activeTurn = selectedRequest === null ? selected?.turn : selectedRequest.turn
+ const activeSection = selectedRequest === null
+ ? selected?.section
+ : selectedRequestRecords[0]?.section
+ const selectedTabs = selectedRequest !== null
+ ? REQUEST_TABS.filter(tab => (
+ (tab.id !== 'options' || selectedRequestOptions !== undefined)
+ && (tab.id !== 'facts' || selectedRequestFacts !== undefined)
+ ))
+ : selected === undefined ? [] : detailTabs(selected)
+ const selectedParents: ParentRecords = selected === undefined
+ ? {}
+ : parentRecords(allRecords, selected)
+ const selectedParentMessage = selectedParents.message
+ const selectedParentTool = selectedParents.tool
+ const selectedAssistantRequest = selected?.cell.kind === 'message'
+ ? requestNumbers.get(recordRequestKey(selected))
+ : undefined
+ const selectedAssistantRequestInfo = selectedAssistantRequest === undefined
+ ? undefined
+ : sessionRequestNumbers?.find(request => (
+ request.recordId ?? requestKey(request.turn, request.group)
+ ) === (selected === undefined ? '' : recordRequestKey(selected)))
+ const selectedAssistantRequestTarget: SelectedRequest | undefined =
+ selected !== undefined && selectedAssistantRequest !== undefined
+ ? {
+ recordId: recordRequestKey(selected),
+ turn: selected.turn,
+ group: selected.group,
+ ...(selectedAssistantRequestInfo?.seq === undefined
+ ? {}
+ : { seq: selectedAssistantRequestInfo.seq }),
+ }
+ : undefined
+ const hasSelectedHierarchy = selectedAssistantRequestTarget !== undefined
+ || selectedParents.message !== undefined
+ || selectedParents.tool !== undefined
+ const splitStyle: TrajectorySplitStyle | undefined = toolRequestOffset === null
+ ? undefined
+ : {
+ '--trajectory-tool-request-width': `calc(58cqw - ${toolRequestOffset}px)`,
+ }
+
+ const activateTab = (tab: DetailTab) => {
+ tabHistory.current.delete(tab)
+ tabHistory.current.add(tab)
+ setActiveTab(tab)
+ }
+
+ const clearInspectorSelection = () => {
+ setSelectedRecordId(null)
+ setSelectedRequest(null)
+ }
+
+ const clearAllSelections = () => {
+ clearInspectorSelection()
+ onClearSelection?.()
+ }
+
+ const selectRecord = useCallback((index: number) => {
+ const record = allRecords.find(candidate => candidate.cell.index === index)
+ onRecordSelect?.(index)
+ setSelectedRequest(null)
+ setSelectedRecordId(record === undefined ? null : trajectoryRecordId(record.cell))
+ if (record === undefined) return
+ const tabs = detailTabs(record)
+ const available = new Set(tabs.map(tab => tab.id))
+ const recent = [...tabHistory.current].reverse().find(tab => available.has(tab))
+ setActiveTab(recent ?? tabs[0]?.id ?? 'overview')
+ }, [allRecords, onRecordSelect])
+ useEffect(() => {
+ if (
+ recordSelection === null
+ || appliedRecordSelection.current === recordSelection
+ ) return
+ appliedRecordSelection.current = recordSelection
+ selectRecord(recordSelection.index)
+ const record = allRecords.find(candidate => candidate.cell.index === recordSelection.index)
+ pendingScrollRecordId.current = record === undefined
+ ? null
+ : trajectoryRecordId(record.cell)
+ }, [allRecords, recordSelection, selectRecord])
+ useEffect(() => {
+ if (recordFocus === null || appliedRecordFocus.current === recordFocus) return
+ appliedRecordFocus.current = recordFocus
+ const record = allRecords.find(candidate => candidate.cell.index === recordFocus.index)
+ pendingScrollRecordId.current = record === undefined
+ ? null
+ : trajectoryRecordId(record.cell)
+ }, [allRecords, recordFocus])
+
+ const selectRequest = (
+ request: SelectedRequest,
+ tab: 'overview' | 'timing' = 'overview',
+ ) => {
+ setSelectedRecordId(null)
+ setSelectedRequest(request)
+ activateTab(tab)
+ }
+
+ const openRecordSummary = (target: TableRecord) => {
+ const targetAt = allRecords.findIndex(record => record.cell.index === target.cell.index)
+ if (target.turn !== null && collapsedTurns.has(target.turn)) onToggleTurn(target.turn)
+ if (target.cell.kind === 'tool' || target.cell.kind === 'subtool') {
+ for (let i = targetAt - 1; i >= 0; i--) {
+ const candidate = allRecords[i]
+ if (candidate === undefined || candidate.turn !== target.turn) break
+ if (candidate.cell.kind !== 'message') continue
+ const assistantId = trajectoryRecordId(candidate.cell)
+ if (collapsedAssistants.has(assistantId)) onToggleAssistant(assistantId)
+ break
+ }
+ }
+ setSelectedRequest(null)
+ setSelectedRecordId(trajectoryRecordId(target.cell))
+ activateTab('overview')
+ }
+
+ const openCallSummary = (callId: string) => {
+ const target = allRecords.find(record => record.cell.callId === callId)
+ if (target !== undefined) openRecordSummary(target)
+ }
+
+ // Cross-view inspect handoff: resolve the requested call to its record,
+ // open its summary, and remember the row to scroll once the un-collapsed
+ // ledger has rendered. Not-found leaves the request pending (`turns` in the
+ // deps retries as history pages in); the ack clears the store field.
+ const openRecordSummaryRef = useRef(openRecordSummary)
+ openRecordSummaryRef.current = openRecordSummary
+ useEffect(() => {
+ if (inspectCallId === null) return
+ const target = flattenRecords(turns).find(record => record.cell.callId === inspectCallId)
+ if (target === undefined) return
+ openRecordSummaryRef.current(target)
+ pendingScrollRecordId.current = trajectoryRecordId(target.cell)
+ onInspectApplied?.()
+ }, [inspectCallId, turns, onInspectApplied])
+ useEffect(() => {
+ const id = pendingScrollRecordId.current
+ if (id === null) return
+ const position = records.findIndex(record =>
+ trajectoryRecordId(record.cell) === id && record.collapsedSummary === undefined)
+ if (position === -1) return
+ if (virtualizationEnabled) {
+ const virtualIndex = virtualIndexByRecordId.get(id)
+ if (virtualIndex === undefined) return
+ pendingScrollRecordId.current = null
+ followsTableTail.current = false
+ rowVirtualizer.scrollToIndex(virtualIndex, { behavior: 'smooth', align: 'center' })
+ return
+ }
+ pendingScrollRecordId.current = null
+ followsTableTail.current = false
+ const recordIndex = records[position]?.cell.index
+ const row = recordIndex === undefined
+ ? null
+ : rootRef.current?.querySelector<HTMLElement>(`tr[data-record-index="${recordIndex}"]`)
+ /* v8 ignore next -- jsdom lacks scrollIntoView; browsers always have it. */
+ if (row !== undefined && row !== null && typeof row.scrollIntoView === 'function') {
+ row.scrollIntoView({ behavior: 'smooth', block: 'center' })
+ }
+ }, [records, rowVirtualizer, virtualIndexByRecordId, virtualizationEnabled])
+ useEffect(() => {
+ if (timelineFocusIndexes === null || timelineFocusIndexes.size === 0) return
+ const focusedPositions = records.flatMap((record, position) =>
+ record.collapsedSummary === undefined
+ && record.cell.requestOnly !== true
+ && timelineFocusIndexes.has(record.cell.index)
+ ? [position]
+ : [])
+ const first = focusedPositions.at(0)
+ const last = focusedPositions.at(-1)
+ if (first === undefined || last === undefined) return
+ if (!virtualizationEnabled) {
+ const ledger = rootRef.current
+ if (ledger === null) return
+ const focusedRows = [
+ ...ledger.querySelectorAll<HTMLElement>('tr[data-timeline-focus="inside"]'),
+ ]
+ const firstRow = focusedRows.at(0)
+ const lastRow = focusedRows.at(-1)
+ if (firstRow === undefined || lastRow === undefined) return
+ const focusHeight =
+ lastRow.getBoundingClientRect().bottom - firstRow.getBoundingClientRect().top
+ const target = focusHeight > ledger.clientHeight
+ ? firstRow
+ : focusedRows[Math.floor((focusedRows.length - 1) / 2)]
+ /* v8 ignore next -- jsdom lacks scrollIntoView; browsers always have it. */
+ if (target !== undefined && typeof target.scrollIntoView === 'function') {
+ followsTableTail.current = false
+ target.scrollIntoView({
+ behavior: 'smooth',
+ block: focusHeight > ledger.clientHeight ? 'start' : 'center',
+ })
+ }
+ return
+ }
+ const focusedVirtualIndexes = [...new Set(focusedPositions.flatMap((position) => {
+ const record = records[position]
+ if (record === undefined) return []
+ const virtualIndex = virtualIndexByRecordId.get(trajectoryRecordId(record.cell))
+ return virtualIndex === undefined ? [] : [virtualIndex]
+ }))].sort((left, right) => left - right)
+ const firstVirtual = focusedVirtualIndexes.at(0)
+ const lastVirtual = focusedVirtualIndexes.at(-1)
+ if (firstVirtual === undefined || lastVirtual === undefined) return
+ const paneHeight = tablePaneRef.current?.clientHeight ?? 0
+ const focusHeight = projectedVirtualRows
+ .slice(firstVirtual, lastVirtual + 1)
+ .reduce((height, row) => height + row.height, 0)
+ followsTableTail.current = false
+ rowVirtualizer.scrollToIndex(
+ focusHeight > paneHeight
+ ? firstVirtual
+ : focusedVirtualIndexes[Math.floor((focusedVirtualIndexes.length - 1) / 2)]
+ ?? firstVirtual,
+ {
+ behavior: 'smooth',
+ align: focusHeight > paneHeight ? 'start' : 'center',
+ },
+ )
+ }, [
+ projectedVirtualRows,
+ records,
+ rowVirtualizer,
+ timelineFocusIndexes,
+ virtualIndexByRecordId,
+ virtualizationEnabled,
+ ])
+ const requestOlder = useCallback((pane: HTMLDivElement, requireTop: boolean) => {
+ if (
+ !hasOlderRecords
+ || onLoadOlder === undefined
+ || loadingOlder.current !== null
+ || olderHistoryLoading
+ || (requireTop && pane.scrollTop > OLDER_LOAD_THRESHOLD_PX)
+ ) return
+ olderLoadAnchor.current = {
+ historyStartSeq,
+ scrollHeight: pane.scrollHeight,
+ scrollTop: pane.scrollTop,
+ }
+ const operation = onLoadOlder()
+ loadingOlder.current = operation
+ setOlderLoading(true)
+ void operation.then((advanced) => {
+ if (loadingOlder.current !== operation) return
+ if (!advanced) olderLoadAnchor.current = null
+ }).finally(() => {
+ if (loadingOlder.current !== operation) return
+ loadingOlder.current = null
+ setOlderLoading(false)
+ })
+ }, [hasOlderRecords, historyStartSeq, olderHistoryLoading, onLoadOlder])
+ useLayoutEffect(() => {
+ const pane = tablePaneRef.current
+ if (pane === null) return
+ const anchor = olderLoadAnchor.current
+ if (anchor !== null && anchor.historyStartSeq !== historyStartSeq) {
+ if (!virtualizationEnabled) {
+ pane.scrollTop = anchor.scrollTop + pane.scrollHeight - anchor.scrollHeight
+ }
+ olderLoadAnchor.current = null
+ followsTableTail.current = false
+ return
+ }
+ if (!tableScrollInitialized.current) {
+ if (historyLoading) return
+ tableScrollInitialized.current = true
+ followsTableTail.current = true
+ if (virtualizationEnabled) rowVirtualizer.scrollToEnd({ behavior: 'auto' })
+ else pane.scrollTop = pane.scrollHeight
+ setTableScrollReady(true)
+ return
+ }
+ if (!followsTableTail.current) return
+ if (virtualizationEnabled) rowVirtualizer.scrollToEnd({ behavior: 'auto' })
+ else pane.scrollTop = pane.scrollHeight
+ }, [
+ historyLoading,
+ historyStartSeq,
+ rowVirtualizer,
+ virtualRowStructure,
+ virtualizationEnabled,
+ ])
+
+ const olderBusy = olderHistoryLoading || olderLoading
+ const showInitialLoading = historyLoading || !tableScrollReady
+ const historyRowOffset = hasOlderRecords ? 1 : 0
+
+ return (
+ <div ref={rootRef} className={css.split} style={splitStyle}>
+ <div
+ ref={tablePaneRef}
+ className={css.tablePane}
+ data-trajectory-scroll=""
+ onScroll={(event) => {
+ const pane = event.currentTarget
+ followsTableTail.current =
+ pane.scrollHeight - pane.clientHeight - pane.scrollTop
+ <= BOTTOM_FOLLOW_THRESHOLD_PX
+ requestOlder(pane, true)
+ }}
+ onClick={(event) => {
+ if (event.target === event.currentTarget) clearAllSelections()
+ }}
+ >
+ {showInitialLoading && (
+ <div className={css.historyLoading} role="status" aria-live="polite">
+ <span className={css.historyLoadingBar}>
+ <span className={css.historyLoadingSpinner} aria-hidden="true" />
+ Loading trajectory…
+ </span>
+ </div>
+ )}
+ <table
+ className={css.table}
+ data-scroll-ready={tableScrollReady || undefined}
+ aria-rowcount={records.length + historyRowOffset}
+ >
+ <colgroup>
+ <col className={css.eventColumn} />
+ <col className={css.contentColumn} />
+ </colgroup>
+ <tbody>
+ {hasOlderRecords && (
+ <tr
+ className={css.historyLoadRow}
+ data-history-load=""
+ aria-rowindex={1}
+ >
+ <td colSpan={2}>
+ <button
+ type="button"
+ className={css.historyLoadButton}
+ disabled={olderBusy || onLoadOlder === undefined}
+ aria-label={olderBusy
+ ? 'Loading earlier history…'
+ : 'Load earlier history'}
+ onClick={() => {
+ const pane = tablePaneRef.current
+ if (pane !== null) requestOlder(pane, false)
+ }}
+ >
+ {olderBusy && (
+ <span className={css.historyLoadingSpinner} aria-hidden="true" />
+ )}
+ <span aria-hidden="true">
+ {olderBusy ? 'Loading earlier history…' : 'Load earlier history'}
+ </span>
+ <span className={css.visuallyHidden} role="status" aria-live="polite">
+ {olderBusy ? 'Loading earlier history…' : ''}
+ </span>
+ </button>
+ </td>
+ </tr>
+ )}
+ {virtualTop > 0 && (
+ <tr className={css.virtualSpacer} data-virtual-spacer="top" aria-hidden="true">
+ <td
+ colSpan={2}
+ style={{
+ '--trajectory-virtual-spacer-height': `${virtualTop}px`,
+ } as VirtualSpacerStyle}
+ />
+ </tr>
+ )}
+ {renderedRecords.map(({ record, position, terminalRequestBoundary }) => (
+ <RecordPresentation
+ key={trajectoryVirtualRecordKey(record)}
+ cell={record.cell}
+ >
+ {({ displayText, listDisplayText, resultText, toolCallOnly, toolCallText }) => {
+ const isCollapsedSummary = record.collapsedSummary !== undefined
+ const isRequestOnly = record.cell.requestOnly === true
+ const isInitialSystem = record.cell.kind === 'system'
+ && record.cell.index === allRecords[0]?.cell.index
+ const key = recordRequestKey(record)
+ const request = requestBoundaries.get(key) === record.cell.index
+ && !isCollapsedSummary
+ && (record.turn === null || !collapsedTurns.has(record.turn))
+ ? requestNumbers.get(key)
+ : undefined
+ const requestInfo = request === undefined
+ ? undefined
+ : sessionRequestNumbers?.find(candidate => (
+ candidate.recordId ?? requestKey(candidate.turn, candidate.group)
+ ) === key)
+ const requestStatus = requestInfo?.status
+ ?? (record.cell.isError === true ? 'error' : undefined)
+ const requestRunIndex = requestBoundaryRuns.get(record.cell.index) ?? 0
+ const requestBoundaryStyle: RequestBoundaryStyle = {
+ '--request-boundary-offset': `${requestRunIndex * 8}px`,
+ }
+ const requestLabel = request === undefined
+ ? undefined
+ : `Request #${request}${requestInfo?.purpose === 'compaction' ? ' · Compaction' : ''}`
+ const requestSelected = request !== undefined
+ && selectedRequest?.recordId === key
+ const sectionActive = record.turn === null
+ ? activeSection === record.section
+ : activeTurn === record.turn
+ return (
+ <tr
+ tabIndex={isRequestOnly ? -1 : 0}
+ aria-rowindex={position + 1 + historyRowOffset}
+ aria-label={isCollapsedSummary
+ ? `Collapsed ${record.collapsedSummaryKind} summary, ${record.collapsedSummary}`
+ : isRequestOnly
+ ? `Request ${request ?? ''}, compaction`
+ : `${request === undefined ? '' : `Request ${request}, `}${KIND_LABEL[record.cell.kind]}, ${listDisplayText || 'no content'}`}
+ aria-selected={!isCollapsedSummary && !isRequestOnly && selectedIndex === record.cell.index}
+ data-kind={record.cell.kind}
+ data-trajectory-row-key={trajectoryVirtualRecordKey(record)}
+ data-virtual-position={virtualizationEnabled ? position : undefined}
+ data-record-index={!isCollapsedSummary && !isRequestOnly
+ ? record.cell.index
+ : undefined}
+ data-request-only={isRequestOnly || undefined}
+ data-terminal-request-boundary={terminalRequestBoundary || undefined}
+ data-group-start={record.groupStart || undefined}
+ data-turn-start={record.turnStart || undefined}
+ data-error={record.cell.isError || undefined}
+ data-running={stateOf(record) === 'running' || undefined}
+ data-turn-end={record.turnEnd || undefined}
+ data-collapsed-summary={record.collapsedSummaryKind}
+ data-selected={!isCollapsedSummary && selectedIndex === record.cell.index || undefined}
+ data-timeline-focus={isCollapsedSummary || timelineFocusIndexes === null
+ ? undefined
+ : timelineFocusIndexes.has(record.cell.index) ? 'inside' : 'outside'}
+ onClick={isRequestOnly
+ ? undefined
+ : isCollapsedSummary
+ ? () => {
+ if (record.collapsedSummaryKind === 'turn' && record.turn !== null) {
+ onToggleTurn(record.turn)
+ } else onToggleAssistant(trajectoryRecordId(record.cell))
+ }
+ : () => { selectRecord(record.cell.index) }}
+ onDoubleClick={(event) => {
+ if (isCollapsedSummary || isRequestOnly) return
+ if (record.turn !== null && collapsedTurns.has(record.turn)) {
+ event.preventDefault()
+ onToggleTurn(record.turn)
+ return
+ }
+ if (
+ record.cell.kind === 'message'
+ && assistantToolCalls(allRecords, record.cell.index).length > 0
+ ) {
+ event.preventDefault()
+ onToggleAssistant(trajectoryRecordId(record.cell))
+ return
+ }
+ if (!record.turnStart) return
+ if (record.turn === null) return
+ if (allRecords.filter(candidate =>
+ candidate.turn === record.turn
+ && candidate.cell.requestOnly !== true
+ && candidate.cell.kind !== 'system').length <= 1) return
+ event.preventDefault()
+ onToggleTurn(record.turn)
+ }}
+ onKeyDown={(event) => {
+ if (isRequestOnly) return
+ if (event.key !== 'Enter' && event.key !== ' ') return
+ event.preventDefault()
+ if (isCollapsedSummary) {
+ if (record.collapsedSummaryKind === 'turn' && record.turn !== null) {
+ onToggleTurn(record.turn)
+ } else onToggleAssistant(trajectoryRecordId(record.cell))
+ return
+ }
+ selectRecord(record.cell.index)
+ }}
+ >
+ <td className={css.event}>
+ {request !== undefined && (
+ <button
+ type="button"
+ className={requestSelected
+ ? `${css.requestBoundaryControl} ${css.requestBoundaryControlActive}`
+ : css.requestBoundaryControl}
+ aria-label={requestLabel}
+ aria-pressed={requestSelected}
+ data-label={requestLabel}
+ data-request-run-index={requestRunIndex}
+ data-request-status={requestStatus}
+ style={requestBoundaryStyle}
+ onClick={(event) => {
+ event.stopPropagation()
+ selectRequest({
+ recordId: key,
+ turn: record.turn,
+ group: record.group,
+ ...(requestInfo?.seq === undefined ? {} : { seq: requestInfo.seq }),
+ })
+ }}
+ onDoubleClick={(event) => { event.stopPropagation() }}
+ />
+ )}
+ {record.turn !== null
+ && activeTurn === record.turn
+ && !isInitialSystem && (
+ <span className={css.turnRail} aria-hidden="true" />
+ )}
+ {!isCollapsedSummary && selectedIndex === record.cell.index && (
+ <span className={css.selectionRail} aria-hidden="true" />
+ )}
+ {!isCollapsedSummary
+ && !isRequestOnly
+ && record.turnStart && (
+ <span
+ className={sectionActive
+ ? `${css.turnLabel} ${css.turnLabelActive}`
+ : css.turnLabel}
+ aria-label={sectionLabel(record.turn)}
+ >
+ {record.turn === null
+ ? sectionLabel(record.turn)
+ : (
+ <>
+ <span className={css.turnLabelFull} aria-hidden="true">
+ {sectionLabel(record.turn)}
+ </span>
+ <span className={css.turnLabelCompact} aria-hidden="true">
+ #{record.turn}
+ </span>
+ </>
+ )}
+ </span>
+ )}
+ <div className={css.eventInner}>
+ {!isCollapsedSummary && !isRequestOnly && (
+ <span
+ className={css.kindSlot}
+ >
+ <span
+ className={`${css.kindTag} ${
+ record.cell.kind === 'system'
+ ? css.systemNeutral
+ : record.cell.kind === 'context'
+ ? css.contextGreen
+ : record.cell.kind === 'compacted'
+ ? css.compacted
+ : record.cell.kind === 'tool'
+ ? css.toolAmber
+ : record.cell.kind === 'message'
+ ? css.assistantVioletBright
+ : record.cell.kind === 'subtool'
+ ? css.subtoolAmber
+ : css[record.cell.kind]
+ }`}
+ data-role-kind={record.cell.kind}
+ >
+ <Tooltip
+ label={KIND_LABEL[record.cell.kind]}
+ side="right"
+ >
+ <span className={css.kindTagIcon} aria-hidden="true">
+ {KIND_ICON[record.cell.kind]}
+ </span>
+ </Tooltip>
+ <span className={css.kindTagLabel}>
+ {KIND_LABEL[record.cell.kind]}
+ </span>
+ </span>
+ </span>
+ )}
+ </div>
+ </td>
+ <td className={css.content}>
+ {isRequestOnly
+ ? null
+ : record.collapsedSummary !== undefined
+ ? (
+ <span className={css.collapsedTurnContent} title={record.collapsedSummary}>
+ <span className={css.collapsedTurnEllipsis}>…</span>
+ <span className={css.collapsedTurnText}>{record.collapsedSummary}</span>
+ </span>
+ )
+ : (
+ <span
+ className={resultText === undefined ? css.contentText : css.resultPreview}
+ title={resultText === undefined
+ ? listDisplayText
+ : `${listDisplayText} → ${resultText}`}
+ >
+ <span className={resultText === undefined ? undefined : css.resultRequest}>
+ <RecordListText
+ displayText={displayText}
+ toolCallOnly={toolCallOnly}
+ toolCallText={toolCallText}
+ />
+ </span>
+ {resultText !== undefined && (
+ <span className={record.cell.isError ? `${css.inlineResult} ${css.error}` : css.inlineResult}>
+ <span className={css.arrow}>→</span>
+ <span className={resultText === 'No output'
+ ? `${css.inlineResultText} ${css.noOutputText}`
+ : css.inlineResultText}
+ >
+ {resultText}
+ </span>
+ </span>
+ )}
+ {stateOf(record) === 'running' && (
+ <span className={css.runningElapsed} aria-label="Running">
+ <span className={css.runningDot} aria-hidden="true" />
+ {formatElapsedSeconds(liveElapsedSeconds(
+ record.cell,
+ nowMilliseconds,
+ ))}
+ </span>
+ )}
+ </span>
+ )}
+ </td>
+ </tr>
+ )
+ }}
+ </RecordPresentation>
+ ))}
+ {virtualBottom > 0 && (
+ <tr className={css.virtualSpacer} data-virtual-spacer="bottom" aria-hidden="true">
+ <td
+ colSpan={2}
+ style={{
+ '--trajectory-virtual-spacer-height': `${virtualBottom}px`,
+ } as VirtualSpacerStyle}
+ />
+ </tr>
+ )}
+ </tbody>
+ </table>
+ </div>
+ {(selectedRequest !== null
+ || promptSelected
+ || (selected !== undefined && selectedState !== undefined)) && (
+ <aside
+ className={css.details}
+ aria-label="Event details"
+ style={detailsWidth === null ? undefined : { width: detailsWidth }}
+ >
+ <div
+ className={css.detailsResizeHandle}
+ role="separator"
+ aria-label="Resize event details"
+ aria-controls="trajectory-detail-panel"
+ aria-orientation="vertical"
+ tabIndex={0}
+ title="Drag to resize. Double-click to reset."
+ onDoubleClick={() => {
+ setDetailsWidth(null)
+ setToolRequestOffset(null)
+ }}
+ onPointerDown={(event) => {
+ if (event.button !== 0) return
+ const details = event.currentTarget.parentElement
+ if (details === null) return
+ const split = details.parentElement
+ if (split === null) return
+ const splitWidth = split.getBoundingClientRect().width
+ detailsResizeDrag.current = {
+ pointerId: event.pointerId,
+ startX: event.clientX,
+ startWidth: details.getBoundingClientRect().width,
+ splitWidth,
+ startToolRequestOffset: toolRequestOffset ?? (
+ splitWidth * TOOL_REQUEST_SHARE - defaultToolRequestWidth(splitWidth)
+ ),
+ }
+ event.currentTarget.setPointerCapture(event.pointerId)
+ event.preventDefault()
+ }}
+ onPointerMove={(event) => {
+ const drag = detailsResizeDrag.current
+ if (drag === null || drag.pointerId !== event.pointerId) return
+ const nextDetailsWidth = clampDetailsWidth(
+ drag.startWidth + drag.startX - event.clientX,
+ drag.splitWidth,
+ )
+ setDetailsWidth(nextDetailsWidth)
+ setToolRequestOffset(
+ drag.startToolRequestOffset
+ + (nextDetailsWidth - drag.startWidth) * TOOL_REQUEST_SHARE,
+ )
+ }}
+ onPointerUp={(event) => {
+ if (detailsResizeDrag.current?.pointerId !== event.pointerId) return
+ detailsResizeDrag.current = null
+ event.currentTarget.releasePointerCapture(event.pointerId)
+ }}
+ onPointerCancel={() => {
+ detailsResizeDrag.current = null
+ }}
+ onKeyDown={(event) => {
+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return
+ const details = event.currentTarget.parentElement
+ if (details === null) return
+ const split = details.parentElement
+ if (split === null) return
+ const direction = event.key === 'ArrowLeft' ? 1 : -1
+ const currentDetailsWidth = details.getBoundingClientRect().width
+ const splitWidth = split.getBoundingClientRect().width
+ const nextDetailsWidth = clampDetailsWidth(
+ currentDetailsWidth + direction * DETAILS_RESIZE_STEP,
+ splitWidth,
+ )
+ const currentToolRequestOffset = toolRequestOffset ?? (
+ splitWidth * TOOL_REQUEST_SHARE - defaultToolRequestWidth(splitWidth)
+ )
+ setDetailsWidth(nextDetailsWidth)
+ setToolRequestOffset(
+ currentToolRequestOffset
+ + (nextDetailsWidth - currentDetailsWidth) * TOOL_REQUEST_SHARE,
+ )
+ event.preventDefault()
+ }}
+ />
+ <div className={css.detailsHeader}>
+ <div className={css.detailsTitle}>
+ {selectedRequest !== null
+ ? (
+ <>
+ <span className={css.requestDetailsDot} aria-hidden="true" />
+ <span className={css.requestDetailsName}>
+ Request #{selectedRequestNumber ?? '—'}
+ </span>
+ <span className={css.detailsLocation}>
+ {selectedRequestInfo?.purpose === 'compaction'
+ ? `Compaction · ${sectionLabel(selectedRequest.turn)}`
+ : sectionLabel(selectedRequest.turn)}
+ </span>
+ </>
+ )
+ : promptSelected
+ ? (
+ <>
+ <span className={`${css.kindTag} ${css.systemNeutral}`}>SYSTEM</span>
+ <span className={css.detailsLocation}>{selected?.cell.text}</span>
+ </>
+ )
+ : selected !== undefined && (
+ <>
+ <span className={`${css.kindTag} ${
+ selected.cell.kind === 'context'
+ ? css.contextGreen
+ : selected.cell.kind === 'compacted'
+ ? css.compacted
+ : selected.cell.kind === 'tool'
+ ? css.toolAmber
+ : selected.cell.kind === 'message'
+ ? css.assistantVioletBright
+ : selected.cell.kind === 'subtool'
+ ? css.subtoolAmber
+ : css[selected.cell.kind]
+ }`}
+ >
+ {KIND_LABEL[selected.cell.kind]}
+ </span>
+ <span className={css.detailsLocation}>
+ {selected.cell.kind === 'compacted'
+ ? sectionLabel(selected.turn)
+ : `${sectionLabel(selected.turn)} · ${selected.group}`}
+ </span>
+ </>
+ )}
+ </div>
+ <button
+ type="button"
+ className={css.close}
+ aria-label="Close details"
+ onClick={clearInspectorSelection}
+ >
+ <span aria-hidden="true">×</span>
+ </button>
+ </div>
+ <div className={css.detailTabs} role="tablist" aria-label="Event details">
+ {selectedTabs.map(tab => (
+ <button
+ key={tab.id}
+ id={`trajectory-detail-${tab.id}`}
+ type="button"
+ role="tab"
+ aria-controls="trajectory-detail-panel"
+ aria-selected={activeTab === tab.id}
+ className={activeTab === tab.id ? `${css.detailTab} ${css.detailTabActive}` : css.detailTab}
+ onClick={() => { activateTab(tab.id) }}
+ >
+ {tab.label}
+ </button>
+ ))}
+ </div>
+ <div
+ id="trajectory-detail-panel"
+ className={activeTab === 'overview'
+ ? `${css.detailBody} ${css.detailBodySummary}`
+ : css.detailBody}
+ role="tabpanel"
+ aria-labelledby={`trajectory-detail-${activeTab}`}
+ >
+ {selectedRequest !== null
+ && selectedRequestState !== undefined
+ && activeTab === 'overview' && (
+ <>
+ <dl
+ className={`${css.overview} ${css.summaryScrollRegion}`}
+ data-summary-scroll-region=""
+ >
+ <div>
+ <dt>Status</dt>
+ <dd className={selectedRequestState === 'error' ? css.error : undefined}>
+ {statusLabel(selectedRequestState)}
+ </dd>
+ </div>
+ {selectedRequestInfo?.purpose === 'compaction' && (
+ <div>
+ <dt>Purpose</dt>
+ <dd>Compaction</dd>
+ </div>
+ )}
+ {(selectedRequestInfo?.provider
+ ?? selectedRequestInfo?.requestConfig?.provider) !== undefined && (
+ <div>
+ <dt>Provider</dt>
+ <dd>
+ {selectedRequestInfo?.provider
+ ?? selectedRequestInfo?.requestConfig?.provider}
+ </dd>
+ </div>
+ )}
+ {(selectedRequestInfo?.model
+ ?? selectedRequestInfo?.requestConfig?.model) !== undefined && (
+ <div>
+ <dt>Model</dt>
+ <dd>
+ {selectedRequestInfo?.model
+ ?? selectedRequestInfo?.requestConfig?.model}
+ </dd>
+ </div>
+ )}
+ <div>
+ <dt>Tool calls</dt>
+ <dd>{selectedRequestToolCalls}</dd>
+ </div>
+ {selectedRequestSubtoolCalls > 0 && (
+ <div>
+ <dt>Subtool calls</dt>
+ <dd>{selectedRequestSubtoolCalls}</dd>
+ </div>
+ )}
+ {selectedRequestInfo?.error !== undefined && (
+ <div>
+ <dt>Error</dt>
+ <dd className={css.error}>{selectedRequestInfo.error}</dd>
+ </div>
+ )}
+ {selectedRequestInfo?.retry !== undefined && (
+ <div>
+ <dt>Retry</dt>
+ <dd>
+ Scheduled {selectedRequestInfo.retry}
+ {selectedRequestInfo.maxRetries === undefined
+ ? ''
+ : ` of ${selectedRequestInfo.maxRetries}`}
+ </dd>
+ </div>
+ )}
+ {selectedRequestInfo?.retryDelayMs !== undefined && (
+ <div>
+ <dt>Retry delay</dt>
+ <dd>{formatDurationMs(selectedRequestInfo.retryDelayMs)}</dd>
+ </div>
+ )}
+ {selectedRequestResult !== undefined && (
+ <div>
+ <dt>Result</dt>
+ <dd className={css.overviewParentLinks}>
+ <button
+ type="button"
+ className={css.overviewHierarchyNavLink}
+ onClick={() => {
+ openRecordSummary(selectedRequestResult)
+ }}
+ >
+ <span>
+ {selectedRequestInfo?.purpose === 'compaction'
+ ? 'Compacted'
+ : 'Assistant Message'}
+ </span>
+ <IconChevronRightOutline14
+ className={css.overviewHierarchyJumpIconTight}
+ size={11}
+ />
+ </button>
+ </dd>
+ </div>
+ )}
+ </dl>
+ <div className={css.overviewSections}>
+ {selectedRequestOptions !== undefined && (
+ <OverviewSection label="Options" onOpen={() => { activateTab('options') }}>
+ <RequestOptions options={selectedRequestOptions} preview />
+ </OverviewSection>
+ )}
+ {selectedRequestFacts !== undefined && (
+ <OverviewSection label="Facts" onOpen={() => { activateTab('facts') }}>
+ <RecordedFacts facts={selectedRequestFacts} preview />
+ </OverviewSection>
+ )}
+ <OverviewSection label="Usage" onOpen={() => { activateTab('usage') }}>
+ <UsageRows usage={selectedRequestUsage} />
+ </OverviewSection>
+ <OverviewSection label="Timing" onOpen={() => { activateTab('timing') }}>
+ <RequestTiming
+ assistant={selectedRequestAssistant}
+ anchor={selectedRequestAnchor}
+ request={selectedRequestInfo}
+ />
+ </OverviewSection>
+ </div>
+ </>
+ )}
+ {selectedRequest !== null && activeTab === 'options' && (
+ <RequestOptions options={selectedRequestOptions} />
+ )}
+ {selectedRequest !== null && activeTab === 'facts' && (
+ <RecordedFacts facts={selectedRequestFacts} />
+ )}
+ {selectedRequest !== null && activeTab === 'usage' && (
+ <RequestUsagePanel
+ usage={selectedRequestUsage}
+ cumulative={selectedRequestCumulativeUsage}
+ />
+ )}
+ {selectedRequest !== null && activeTab === 'timing' && (
+ <RequestTiming
+ assistant={selectedRequestAssistant}
+ anchor={selectedRequestAnchor}
+ request={selectedRequestInfo}
+ />
+ )}
+ {promptSelected
+ && selectedPreviousPrompt !== undefined
+ && activeTab === 'diff' && (
+ <SystemPromptDiff
+ before={selectedPreviousPrompt}
+ after={selectedPrompt}
+ />
+ )}
+ {promptSelected && activeTab === 'system-prompt' && (
+ selectedPrompt.system === ''
+ ? <p className={css.noPayload}>No system prompt in this request</p>
+ : (
+ <div className={`${css.markdownPayload} ${css.systemPrompt}`}>
+ <MarkdownText text={selectedPrompt.system} />
+ </div>
+ )
+ )}
+ {promptSelected && activeTab === 'tools' && (
+ <ToolCatalog tools={selectedPrompt.tools} />
+ )}
+ {!promptSelected
+ && selected?.cell.kind === 'compacted'
+ && selectedState !== undefined
+ && activeTab === 'overview' && (
+ <>
+ <dl
+ className={`${css.overview} ${css.summaryScrollRegion}`}
+ data-summary-scroll-region=""
+ >
+ <div>
+ <dt>Status</dt>
+ <dd className={selectedState === 'error' ? css.error : undefined}>
+ {statusLabel(selectedState)}
+ </dd>
+ </div>
+ <div>
+ <dt>Duration</dt>
+ <dd>{formatElapsedSeconds(selected.cell.timeSeconds)}</dd>
+ </div>
+ <div>
+ <dt>Tokens</dt>
+ <dd>—</dd>
+ </div>
+ </dl>
+ {selected.cell.outputDetail !== undefined && (
+ <div
+ className={`${css.compactedSummary} ${css.summaryScrollRegion}`}
+ data-summary-scroll-region=""
+ >
+ <MarkdownRecordContent
+ record={selected}
+ rendered
+ thinkingExpanded={thinkingExpanded}
+ onThinkingExpandedChange={setThinkingExpanded}
+ onOpenCall={openCallSummary}
+ />
+ </div>
+ )}
+ </>
+ )}
+ {!promptSelected
+ && selected !== undefined
+ && selected.cell.kind !== 'compacted'
+ && selectedState !== undefined
+ && activeTab === 'overview' && (
+ <>
+ <dl
+ className={`${css.overview} ${css.summaryScrollRegion}`}
+ data-summary-scroll-region=""
+ >
+ {selected.cell.messageSource !== undefined && (
+ <div>
+ <dt>Source</dt>
+ <dd className={css.overviewParentLinks}>
+ <button
+ type="button"
+ className={css.overviewHierarchyNavLink}
+ onClick={() => { activateTab('source') }}
+ >
+ <span>{messageSourceLabel(selected.cell.messageSource)}</span>
+ <IconChevronRightOutline14
+ className={css.overviewHierarchyJumpIconTight}
+ size={11}
+ />
+ </button>
+ </dd>
+ </div>
+ )}
+ {hasSelectedHierarchy && (
+ <div>
+ <dt>
+ {selectedAssistantRequestTarget !== undefined
+ ? 'Source'
+ : 'Hierarchy'}
+ </dt>
+ <dd className={css.overviewParentLinks}>
+ {selectedAssistantRequestTarget !== undefined && (
+ <button
+ type="button"
+ className={css.overviewHierarchyNavLink}
+ onClick={() => {
+ selectRequest(selectedAssistantRequestTarget)
+ }}
+ >
+ <span>Request #{selectedAssistantRequest ?? '—'}</span>
+ <IconChevronRightOutline14
+ className={css.overviewHierarchyJumpIconTight}
+ size={11}
+ />
+ </button>
+ )}
+ {selectedParentMessage !== undefined && (
+ <button
+ type="button"
+ className={css.overviewHierarchyNavLink}
+ onClick={() => { openRecordSummary(selectedParentMessage) }}
+ >
+ <span>Assistant Message</span>
+ <IconChevronRightOutline14
+ className={css.overviewHierarchyJumpIconTight}
+ size={11}
+ />
+ </button>
+ )}
+ {selectedParentTool !== undefined && (
+ <button
+ type="button"
+ className={css.overviewHierarchyNavLink}
+ onClick={() => { openRecordSummary(selectedParentTool) }}
+ >
+ <span>Tool Call</span>
+ <IconChevronRightOutline14
+ className={css.overviewHierarchyJumpIconTight}
+ size={11}
+ />
+ </button>
+ )}
+ </dd>
+ </div>
+ )}
+ <div>
+ <dt>Status</dt>
+ <dd className={selectedState === 'error' ? css.error : undefined}>
+ {statusLabel(selectedState)}
+ </dd>
+ </div>
+ {selected.cell.kind === 'message' && (
+ <TokenRows cell={selected.cell} />
+ )}
+ {(selected.cell.kind === 'user' || selected.cell.kind === 'context') && (
+ <div>
+ <dt>Duration</dt>
+ <dd>{formatElapsedSeconds(selected.cell.timeSeconds)}</dd>
+ </div>
+ )}
+ </dl>
+ <div className={css.overviewSections}>
+ {isMarkdownRecord(selected)
+ ? (
+ <>
+ <OverviewSection label="Preview" onOpen={() => { activateTab('rendered') }}>
+ <MarkdownRecordContent
+ record={selected}
+ rendered
+ preview
+ thinkingExpanded={thinkingExpanded}
+ onThinkingExpandedChange={setThinkingExpanded}
+ onOpenCall={openCallSummary}
+ />
+ </OverviewSection>
+ </>
+ )
+ : (
+ <>
+ {selected.cell.inputDetail && (
+ <OverviewSection label="Payload" onOpen={() => { activateTab('input') }}>
+ <RecordPayload record={selected} direction="input" preview />
+ </OverviewSection>
+ )}
+ {selected.cell.outputDetail && (
+ <OverviewSection label="Result" onOpen={() => { activateTab('output') }}>
+ <RecordPayload record={selected} direction="output" preview />
+ </OverviewSection>
+ )}
+ <OverviewSection label="Schema" onOpen={() => { activateTab('schema') }}>
+ <RecordSchema record={selected} preview />
+ </OverviewSection>
+ </>
+ )}
+ {selectedAssistantRequestTarget !== undefined && (
+ <OverviewSection
+ label="Request Timing"
+ onOpen={() => {
+ selectRequest(selectedAssistantRequestTarget, 'timing')
+ }}
+ >
+ <RecordTiming record={selected} />
+ </OverviewSection>
+ )}
+ {(selected.cell.kind === 'tool' || selected.cell.kind === 'subtool') && (
+ <OverviewSection label="Timing" onOpen={() => { activateTab('timing') }}>
+ <RecordTiming record={selected} />
+ </OverviewSection>
+ )}
+ </div>
+ </>
+ )}
+ {!promptSelected && selected !== undefined && activeTab === 'rendered' && (
+ <MarkdownRecordContent
+ record={selected}
+ rendered
+ thinkingExpanded={thinkingExpanded}
+ onThinkingExpandedChange={setThinkingExpanded}
+ onOpenCall={openCallSummary}
+ />
+ )}
+ {!promptSelected && selected !== undefined && activeTab === 'raw' && (
+ <MarkdownRecordContent
+ record={selected}
+ rendered={false}
+ thinkingExpanded={thinkingExpanded}
+ onThinkingExpandedChange={setThinkingExpanded}
+ onOpenCall={openCallSummary}
+ />
+ )}
+ {!promptSelected && selected !== undefined && activeTab === 'source' && (
+ <MessageSource record={selected} />
+ )}
+ {!promptSelected && selected !== undefined && activeTab === 'input' && (
+ <RecordPayload record={selected} direction="input" />
+ )}
+ {!promptSelected && selected !== undefined && activeTab === 'output' && (
+ <RecordPayload record={selected} direction="output" />
+ )}
+ {!promptSelected && selected !== undefined && activeTab === 'schema' && (
+ <RecordSchema record={selected} />
+ )}
+ {!promptSelected && selected !== undefined && activeTab === 'timing' && (
+ <RecordTiming record={selected} />
+ )}
+ {typeof selected?.cell.traceDetail === 'object'
+ && selected.cell.traceDetail !== null
+ && activeTab === 'otel' && (
+ <JsonTree data={selected.cell.traceDetail} label="OTLP export request" />
+ )}
+ </div>
+ </aside>
+ )}
+ </div>
+ )
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTimeline.module.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTimeline.module.css
new file mode 100644
index 0000000000..add96709e1
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTimeline.module.css
@@ -0,0 +1,348 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+/* Adapted from packages/client/ui-trajectory/src/client/TrajectoryTimeline.module.css under MIT. */
+.root {
+ position: relative;
+ z-index: 1;
+ isolation: isolate;
+ flex: none;
+ border-bottom: 1px solid var(--dsw-alias-border-l2);
+ user-select: none;
+}
+
+.root :global([role='tooltip']) {
+ font: var(--dsw-font-xxxs-11);
+}
+
+.plot {
+ display: grid;
+ grid-template-columns: 44px minmax(0, 1fr);
+ height: 50px;
+ overflow: hidden;
+ background: var(--dsw-alias-bg-layer-2);
+}
+
+.labels {
+ position: relative;
+ border-right: 1px solid var(--dsw-alias-border-l1);
+ color: var(--dsw-alias-label-caption);
+ font: var(--dsw-font-xs-13);
+ font-size: 10px;
+ line-height: 1;
+}
+
+.labels span {
+ position: absolute;
+ right: 3px;
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ height: 8px;
+ text-align: right;
+}
+
+.labels span:nth-child(1) {
+ top: 7px;
+}
+
+.labels span:nth-child(2) {
+ top: 21px;
+}
+
+.labels span:nth-child(3) {
+ top: 35px;
+}
+
+.track {
+ position: relative;
+ overflow: hidden;
+ cursor: crosshair;
+ touch-action: none;
+}
+
+.track[data-panning='true'] {
+ cursor: grabbing;
+}
+
+.earlierHistory {
+ position: absolute;
+ z-index: 5;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ display: flex;
+ width: 28px;
+ align-items: center;
+ justify-content: flex-start;
+ appearance: none;
+ box-sizing: border-box;
+ padding-left: 3px;
+ border: 0;
+ outline: none;
+ background: linear-gradient(
+ to right,
+ var(--dsw-alias-bg-layer-2) 0,
+ var(--dsw-alias-bg-layer-2) 38%,
+ transparent 100%
+ );
+ color: var(--dsw-alias-label-secondary);
+ font: var(--dsw-font-xs-13);
+ line-height: 1;
+ opacity: 0.72;
+ cursor: pointer;
+}
+
+.earlierHistory:hover {
+ opacity: 1;
+}
+
+.earlierHistory[aria-disabled='true'] {
+ cursor: default;
+}
+
+.earlierHistory:focus-visible {
+ box-shadow: inset 0 0 0 1px var(--dsw-alias-border-l2);
+}
+
+.empty {
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ color: var(--dsw-alias-label-caption);
+ font: var(--dsw-font-xs-13);
+}
+
+.track:focus-visible {
+ outline: 1px solid var(--dsw-alias-state-business-primary);
+ outline-offset: -1px;
+}
+
+.lanes {
+ position: absolute;
+ z-index: 2;
+ top: 7px;
+ bottom: 7px;
+ left: var(--trajectory-domain-left);
+ width: var(--trajectory-domain-width);
+}
+
+.turnBoundaries {
+ position: absolute;
+ z-index: 3;
+ top: 0;
+ bottom: 0;
+ left: var(--trajectory-domain-left);
+ width: var(--trajectory-domain-width);
+ pointer-events: none;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ .lanes[data-animate-viewport='true'],
+ .turnBoundaries[data-animate-viewport='true'] {
+ transition: left 180ms ease-out;
+ }
+}
+
+.turnBoundary {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: var(--trajectory-turn-left);
+ width: 1px;
+ background: var(--dsw-alias-border-l2);
+}
+
+.span {
+ position: absolute;
+ top: calc(var(--trajectory-span-lane) * 14px);
+ left: calc(var(--trajectory-span-left) + var(--trajectory-span-gap));
+ width: max(
+ 2px,
+ calc(
+ var(--trajectory-span-width)
+ - var(--trajectory-span-gap)
+ - var(--trajectory-span-gap)
+ )
+ );
+ height: 8px;
+ min-width: 2px;
+ border-radius: 1px;
+ background: var(--dsw-alias-label-secondary);
+ opacity: 0.78;
+}
+
+.span[data-timeline-span='user'] {
+ background: var(--dsw-alias-state-business-primary);
+}
+
+.span[data-timeline-span='context'] {
+ background: var(--dsw-alias-state-success-primary);
+ background: color-mix(
+ in srgb,
+ var(--dsw-alias-state-success-primary) 68%,
+ var(--dsw-alias-label-secondary)
+ );
+}
+
+.span[data-timeline-span='message'] {
+ --trajectory-assistant-decoding-color: var(--dsw-alias-brand-primary-new-colorprimary-new-color);
+ --trajectory-assistant-ttft-color: var(--dsw-alias-state-business-tertiary);
+}
+
+@supports (color: color-mix(in srgb, currentColor, transparent)) {
+ .span[data-timeline-span='message'] {
+ --trajectory-assistant-decoding-color: color-mix(
+ in srgb,
+ var(--dsw-alias-brand-primary-new-colorprimary-new-color) 60%,
+ var(--dsw-alias-state-error-secondary)
+ );
+ --trajectory-assistant-ttft-color: color-mix(
+ in srgb,
+ var(--trajectory-assistant-decoding-color) 54%,
+ var(--dsw-alias-bg-layer-2)
+ );
+ }
+}
+
+.span[data-timeline-span='message'] {
+ background: var(--trajectory-assistant-decoding-color);
+ opacity: 1;
+}
+
+.span[data-timeline-span='message'][data-assistant-timing='true'] {
+ background: linear-gradient(
+ to right,
+ var(--trajectory-assistant-ttft-color) 0,
+ var(--trajectory-assistant-ttft-color) var(--trajectory-assistant-ttft),
+ var(--trajectory-assistant-decoding-color) var(--trajectory-assistant-ttft),
+ var(--trajectory-assistant-decoding-color) 100%
+ );
+}
+
+.span[data-timeline-span='tool'],
+.span[data-timeline-span='subtool'] {
+ background: var(--dsw-alias-state-warn-label);
+ opacity: 1;
+}
+
+.span[data-error='true'] {
+ background: var(--dsw-alias-state-error-primary);
+}
+
+.span[data-equal-duration='true'] {
+ width: 8px;
+ min-width: 8px;
+}
+
+.span[data-selected='false'] {
+ opacity: 0.2;
+}
+
+.span[data-hovered='true']:not([data-current='true']) {
+ z-index: 1;
+ opacity: 1;
+ box-shadow:
+ 0 0 0 1px var(--dsw-alias-bg-layer-2),
+ 0 0 0 2px var(--dsw-alias-state-business-primary);
+ box-shadow:
+ 0 0 0 1px var(--dsw-alias-bg-layer-2),
+ 0 0 0 2px color-mix(
+ in srgb,
+ var(--dsw-alias-state-business-primary) 80%,
+ transparent
+ );
+}
+
+.span[data-current='true'] {
+ z-index: 1;
+ opacity: 1;
+ box-shadow:
+ 0 0 0 1px var(--dsw-alias-bg-layer-2),
+ 0 0 0 2px var(--dsw-alias-state-business-primary);
+}
+
+.span[data-search-match='false'] {
+ opacity: 0.14;
+}
+
+.selection {
+ position: absolute;
+ z-index: 1;
+ top: 0;
+ bottom: 0;
+ left: var(--trajectory-selection-left);
+ width: var(--trajectory-selection-width);
+ min-width: 1px;
+ background: var(--dsw-alias-state-business-tertiary);
+ background: color-mix(
+ in srgb,
+ var(--dsw-alias-state-business-primary) 12%,
+ transparent
+ );
+ box-shadow:
+ -100vw 0 0 100vw var(--dsw-alias-bg-layer-1),
+ 100vw 0 0 100vw var(--dsw-alias-bg-layer-1);
+ box-shadow:
+ -100vw 0 0 100vw color-mix(in srgb, var(--dsw-alias-bg-layer-1) 58%, transparent),
+ 100vw 0 0 100vw color-mix(in srgb, var(--dsw-alias-bg-layer-1) 58%, transparent);
+ pointer-events: none;
+}
+
+.selectionEdges {
+ position: absolute;
+ z-index: 4;
+ top: 0;
+ bottom: 0;
+ left: var(--trajectory-selection-left);
+ width: var(--trajectory-selection-width);
+ min-width: 1px;
+ pointer-events: none;
+}
+
+.hoverLine {
+ position: absolute;
+ z-index: 4;
+ top: 0;
+ bottom: 0;
+ left: clamp(
+ 0px,
+ calc(var(--trajectory-hover-left) - 1px),
+ calc(100% - 2px)
+ );
+ width: 2px;
+ background: var(--dsw-alias-state-business-primary);
+ pointer-events: none;
+}
+
+.selectionEdges::before,
+.selectionEdges::after {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ width: 3px;
+ background: var(--dsw-alias-state-business-primary);
+ content: '';
+}
+
+.selectionEdges::before {
+ left: 0;
+}
+
+.selectionEdges::after {
+ right: 0;
+}
+
+.selectionEdges[data-dragging='true']::before,
+.selectionEdges[data-dragging='true']::after {
+ width: 2px;
+}
+
+.selection[data-dragging='true'] {
+ background: var(--dsw-alias-state-business-tertiary);
+ background: color-mix(
+ in srgb,
+ var(--dsw-alias-state-business-primary) 18%,
+ transparent
+ );
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTimeline.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTimeline.tsx
new file mode 100644
index 0000000000..e029e7f77b
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTimeline.tsx
@@ -0,0 +1,764 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Chrome-Network-style overview timeline for focusing the trajectory ledger.
+ * Adapted mechanically from `packages/client/ui-trajectory/src/client/TrajectoryTimeline.tsx`
+ * under the repository MIT license.
+ */
+
+import {
+ memo, useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent,
+ type PointerEvent,
+} from 'react'
+import { Tooltip } from '../primitives/index.ts'
+import type { TrajectoryTurnModel } from '../trajectory/model.ts'
+import type { AssistantMetricDetail, TrajectoryCellKind, TrajectoryCellProps } from '../trajectory/record.ts'
+import { liveElapsedSeconds } from '../trajectory/record.ts'
+import {
+ deriveTrajectoryTimeline,
+ formatTimelineOffset,
+ type TrajectoryTimelineMode,
+ type TrajectoryTimeRange,
+} from '../trajectory/timeline.ts'
+import css from './TrajectoryTimeline.module.css'
+
+const MINIMUM_DRAG_PX = 3
+const MINIMUM_ZOOM_OPERATIONS = 4
+const EDGE_PAN_ZONE_FRACTION = 0.08
+const EDGE_PAN_STEP_FRACTION = 0.025
+const MAXIMUM_EDGE_PAN_PX = 32
+const TIMELINE_TOOLTIP_DELAY_MS = 500
+
+interface TimelineRecordDetail {
+ decodingMs?: number
+ durationMs?: number
+ startedAt?: number
+ ttftMs?: number
+}
+
+interface FractionRange {
+ start: number
+ end: number
+}
+
+interface HoverPoint {
+ fraction: number
+ recordIndex: number | null
+}
+
+interface PanGesture {
+ anchorClientX: number
+ anchorStart: number
+ moved: boolean
+ pannable: boolean
+ pointerId: number
+}
+
+function assistantTimingDetail(
+ metrics: AssistantMetricDetail | undefined,
+): Pick<TimelineRecordDetail, 'ttftMs' | 'decodingMs'> {
+ const start = metrics?.stepStartTime
+ const first = metrics?.firstTokenTime
+ const completed = metrics?.completedTime
+ if (
+ metrics?.timingRecorded !== true
+ || typeof start !== 'number'
+ || typeof first !== 'number'
+ || typeof completed !== 'number'
+ || !Number.isFinite(start)
+ || !Number.isFinite(first)
+ || !Number.isFinite(completed)
+ || first < start
+ || completed < first
+ ) return {}
+ return { ttftMs: first - start, decodingMs: completed - first }
+}
+
+function timelineRecordDetail(
+ cell: TrajectoryCellProps,
+ nowMilliseconds: number,
+): TimelineRecordDetail {
+ const elapsed = liveElapsedSeconds(cell, nowMilliseconds)
+ const durationMs = elapsed === null || !Number.isFinite(elapsed)
+ ? undefined
+ : Math.max(0, elapsed * 1_000)
+ const startedAt = cell.startedAt === null || !Number.isFinite(cell.startedAt)
+ ? undefined
+ : cell.startedAt
+ return {
+ ...(durationMs === undefined ? {} : { durationMs }),
+ ...(startedAt === undefined ? {} : { startedAt }),
+ ...assistantTimingDetail(cell.assistantMetrics),
+ }
+}
+
+function timelineKindLabel(kind: TrajectoryCellKind): string {
+ switch (kind) {
+ case 'system': return 'SYSTEM'
+ case 'user': return 'USER'
+ case 'context': return 'CONTEXT'
+ case 'compacted': return 'COMPACTED'
+ case 'message': return 'ASSISTANT'
+ case 'tool': return 'TOOL'
+ case 'subtool': return 'SUBTOOL'
+ }
+}
+
+function formatRecordedTime(timestamp: number): string {
+ return new Date(timestamp).toLocaleTimeString(undefined, {
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ fractionalSecondDigits: 3,
+ })
+}
+
+function timelineTooltipLabel(
+ kind: TrajectoryCellKind,
+ detail: TimelineRecordDetail | undefined,
+): string {
+ const heading = timelineKindLabel(kind)
+ if (detail === undefined) return heading
+ const duration = detail.durationMs === undefined
+ ? null
+ : `Total ${formatTimelineOffset(detail.durationMs)}`
+ const range = detail.startedAt === undefined
+ ? null
+ : detail.durationMs === undefined
+ ? `Started ${formatRecordedTime(detail.startedAt)}`
+ : `${formatRecordedTime(detail.startedAt)} → ${formatRecordedTime(
+ detail.startedAt + detail.durationMs,
+ )}`
+ const segments = detail.ttftMs === undefined || detail.decodingMs === undefined
+ ? null
+ : `TTFT ${formatTimelineOffset(detail.ttftMs)} · Decoding ${formatTimelineOffset(
+ detail.decodingMs,
+ )}`
+ const timing = [duration, segments].filter(value => value !== null).join(' · ')
+ return [heading, range, timing].filter(value => value !== null && value !== '').join('\n')
+}
+
+/** Props for the fixed full-domain overview above the trajectory ledger. */
+export interface TrajectoryTimelineProps {
+ turns: readonly TrajectoryTurnModel[]
+ mode: TrajectoryTimelineMode
+ range: TrajectoryTimeRange | null
+ /** Whether one earlier history page request is pending anywhere. */
+ olderHistoryLoading?: boolean
+ /** Whether the loaded timeline omits an earlier history prefix. */
+ hasEarlierRecords?: boolean
+ /** Load one earlier history page from the truncation control. */
+ onLoadEarlier?: () => Promise<boolean>
+ selectedIndex?: number | null
+ /** Record indexes matching the active ledger search, or null without a query. */
+ searchMatchIndexes?: ReadonlySet<number> | null
+ onRangeChange: (range: TrajectoryTimeRange | null) => void
+ /** Select a directly clicked timeline block. */
+ onRecordSelect?: (index: number) => void
+ /** Bring the nearest record into view after clicking timeline whitespace. */
+ onRecordFocus?: (index: number) => void
+ /** Shared presentation clock used only for open running intervals. */
+ nowMilliseconds?: number
+}
+
+function orderedRange(left: number, right: number): FractionRange {
+ return left <= right ? { start: left, end: right } : { start: right, end: left }
+}
+
+function clampFraction(value: number): number {
+ return Math.min(1, Math.max(0, value))
+}
+
+function centeredRange(
+ center: number,
+ width: number,
+ minimum: number,
+ maximum: number,
+): FractionRange {
+ const clampedWidth = Math.min(maximum - minimum, Math.max(0, width))
+ const start = Math.min(
+ Math.max(center - clampedWidth / 2, minimum),
+ maximum - clampedWidth,
+ )
+ return { start, end: start + clampedWidth }
+}
+
+function rangeFraction(
+ range: TrajectoryTimeRange,
+ start: number,
+ duration: number,
+ minimum: number,
+ maximum: number,
+): FractionRange {
+ const bounded = orderedRange(
+ Math.min(maximum, Math.max(minimum, range.start)),
+ Math.min(maximum, Math.max(minimum, range.end)),
+ )
+ return {
+ start: (bounded.start - start) / duration,
+ end: (bounded.end - start) / duration,
+ }
+}
+
+function LaneLabels() {
+ return (
+ <div className={css.labels} aria-hidden="true">
+ <span>Input</span>
+ <span>Model</span>
+ <span>Tools</span>
+ </div>
+ )
+}
+
+function EarlierHistoryBoundary({
+ loading,
+ onHover,
+ onLoad,
+}: {
+ loading: boolean
+ onHover: () => void
+ onLoad: (() => void) | undefined
+}) {
+ return (
+ <Tooltip
+ label={loading ? 'Loading earlier history…' : 'Click to load earlier history'}
+ side="right"
+ delayMs={TIMELINE_TOOLTIP_DELAY_MS}
+ >
+ <button
+ type="button"
+ className={css.earlierHistory}
+ data-earlier-history
+ data-loading={loading || undefined}
+ aria-label={loading ? 'Loading earlier history' : 'Load earlier history'}
+ aria-disabled={loading || onLoad === undefined}
+ disabled={loading || onLoad === undefined}
+ onClick={onLoad}
+ onPointerEnter={(event) => {
+ event.stopPropagation()
+ onHover()
+ }}
+ onPointerMove={(event) => { event.stopPropagation() }}
+ onPointerDown={(event) => { event.stopPropagation() }}
+ >
+ …
+ </button>
+ </Tooltip>
+ )
+}
+
+/** Overview renderer with drag ranges, click-sized focus, and Escape reset. */
+export const TrajectoryTimeline = memo(function TrajectoryTimeline({
+ turns,
+ mode,
+ range,
+ olderHistoryLoading = false,
+ hasEarlierRecords = false,
+ onLoadEarlier,
+ selectedIndex = null,
+ searchMatchIndexes = null,
+ onRangeChange,
+ onRecordSelect,
+ onRecordFocus,
+ nowMilliseconds = Date.now(),
+}: TrajectoryTimelineProps) {
+ const model = useMemo(
+ () => deriveTrajectoryTimeline(turns, mode, nowMilliseconds),
+ [mode, nowMilliseconds, turns],
+ )
+ const detailByIndex = useMemo(
+ () => new Map(turns.flatMap(turn =>
+ turn.groups.flatMap(group =>
+ group.cells.map(cell => [cell.index, timelineRecordDetail(cell, nowMilliseconds)] as const),
+ ),
+ )),
+ [nowMilliseconds, turns],
+ )
+ const dragRef = useRef<{
+ pointerId: number
+ anchorTime: number
+ anchorClientX: number
+ recordIndex: number | null
+ } | null>(null)
+ const panRef = useRef<PanGesture | null>(null)
+ const rootRef = useRef<HTMLElement | null>(null)
+ const trackRef = useRef<HTMLDivElement | null>(null)
+ const [draft, setDraft] = useState<TrajectoryTimeRange | null>(null)
+ const [hover, setHover] = useState<HoverPoint | null>(null)
+ const loadingEarlierRef = useRef<Promise<boolean> | null>(null)
+ const [localOlderHistoryLoading, setLocalOlderHistoryLoading] = useState(false)
+ useEffect(() => {
+ loadingEarlierRef.current = null
+ setLocalOlderHistoryLoading(false)
+ }, [onLoadEarlier])
+ const [panning, setPanning] = useState(false)
+ const [viewport, setViewport] = useState<TrajectoryTimeRange | null>(null)
+ const [animateViewport, setAnimateViewport] = useState(false)
+ useEffect(() => {
+ if (
+ model !== null
+ && range !== null
+ && (range.end < model.start || range.start > model.end)
+ ) {
+ onRangeChange(null)
+ }
+ }, [model, onRangeChange, range])
+ useEffect(() => {
+ if (model === null) return
+ setAnimateViewport(false)
+ setViewport(current =>
+ current !== null && (current.end < model.start || current.start > model.end)
+ ? null
+ : current)
+ }, [model])
+ useEffect(() => {
+ if (model === null || selectedIndex === null) return
+ const selectedSpan = model.spans.find(span => span.index === selectedIndex)
+ if (selectedSpan === undefined) return
+ setAnimateViewport(true)
+ setViewport((current) => {
+ if (current === null) return current
+ if (
+ selectedSpan.end > current.start
+ && selectedSpan.start < current.end
+ ) return current
+ const duration = Math.max(1, current.end - current.start)
+ const desiredStart = selectedSpan.end <= current.start
+ ? selectedSpan.start
+ : selectedSpan.end - duration
+ const nextStart = Math.min(
+ Math.max(desiredStart, model.start),
+ Math.max(model.start, model.end - duration),
+ )
+ if (nextStart === current.start) return current
+ return { start: nextStart, end: nextStart + duration }
+ })
+ }, [model, selectedIndex])
+ const fullDuration = Math.max(1, (model?.end ?? 0) - (model?.start ?? 0))
+ const viewportDuration = Math.min(
+ fullDuration,
+ Math.max(1, (viewport?.end ?? 0) - (viewport?.start ?? 0)),
+ )
+ const viewportStart = model === null || viewport === null
+ ? model?.start ?? 0
+ : Math.min(
+ Math.max(viewport.start, model.start),
+ model.end - viewportDuration,
+ )
+ const domainDuration = viewport === null ? fullDuration : viewportDuration
+ const domainStart = viewport === null ? model?.start ?? 0 : viewportStart
+ const showsEarlierBoundary = hasEarlierRecords
+ && model !== null
+ && domainStart === model.start
+ const olderBusy = olderHistoryLoading || localOlderHistoryLoading
+ const loadEarlier = onLoadEarlier === undefined || olderBusy
+ ? undefined
+ : () => {
+ if (loadingEarlierRef.current !== null || olderHistoryLoading) return
+ const operation = onLoadEarlier()
+ loadingEarlierRef.current = operation
+ setLocalOlderHistoryLoading(true)
+ void operation.finally(() => {
+ if (loadingEarlierRef.current !== operation) return
+ loadingEarlierRef.current = null
+ setLocalOlderHistoryLoading(false)
+ })
+ }
+ const projectedDomainStyle = model === null
+ ? undefined
+ : {
+ '--trajectory-domain-left':
+ `${-(domainStart - model.start) / domainDuration * 100}%`,
+ '--trajectory-domain-width': `${fullDuration / domainDuration * 100}%`,
+ } as CSSProperties
+ const committed = model === null || range === null
+ ? null
+ : rangeFraction(range, domainStart, domainDuration, model.start, model.end)
+ const draftFraction = model === null || draft === null
+ ? null
+ : rangeFraction(draft, domainStart, domainDuration, model.start, model.end)
+ const visibleRange = draftFraction ?? committed
+ const activeRange = draft ?? range
+ useEffect(() => {
+ const root = rootRef.current
+ if (root === null) return
+ const onWheel = (event: globalThis.WheelEvent): void => {
+ event.preventDefault()
+ const track = trackRef.current
+ if (track === null || model === null) return
+ setAnimateViewport(false)
+ const rect = track.getBoundingClientRect()
+ const anchorFraction =
+ clampFraction((event.clientX - rect.left) / Math.max(1, rect.width))
+ const nextDuration = Math.min(
+ fullDuration,
+ Math.max(
+ Math.min(mode === 'sequence' ? MINIMUM_ZOOM_OPERATIONS : 20, fullDuration),
+ domainDuration * Math.exp(event.deltaY * 0.0015),
+ ),
+ )
+ if (nextDuration >= fullDuration * 0.999) {
+ setViewport(null)
+ return
+ }
+ const anchorTime = domainStart + anchorFraction * domainDuration
+ const nextStart = Math.min(
+ Math.max(anchorTime - anchorFraction * nextDuration, model.start),
+ model.end - nextDuration,
+ )
+ setViewport({ start: nextStart, end: nextStart + nextDuration })
+ }
+ root.addEventListener('wheel', onWheel, { passive: false })
+ return () => { root.removeEventListener('wheel', onWheel) }
+ }, [domainDuration, domainStart, fullDuration, mode, model])
+
+ if (model === null) {
+ return (
+ <section ref={rootRef} className={css.root} aria-label="Trajectory timeline">
+ <div className={css.plot}>
+ <LaneLabels />
+ <div className={css.track}>
+ <span className={css.empty}>No timing data</span>
+ {hasEarlierRecords && (
+ <EarlierHistoryBoundary
+ loading={olderBusy}
+ onHover={() => { setHover(null) }}
+ onLoad={loadEarlier}
+ />
+ )}
+ </div>
+ </div>
+ </section>
+ )
+ }
+
+ const minimumSelectionDuration = Math.min(
+ domainDuration,
+ fullDuration / model.spans.length,
+ )
+
+ const fractionAt = (event: PointerEvent<HTMLDivElement>): number => {
+ const rect = event.currentTarget.getBoundingClientRect()
+ return clampFraction((event.clientX - rect.left) / Math.max(1, rect.width))
+ }
+
+ const recordIndexAt = (event: PointerEvent<HTMLDivElement>): number | null => {
+ const target = event.target instanceof HTMLElement ? event.target : null
+ const value = target?.closest<HTMLElement>('[data-timeline-record-index]')
+ ?.dataset.timelineRecordIndex
+ if (value === undefined) return null
+ const index = Number(value)
+ return Number.isFinite(index) ? index : null
+ }
+
+ const commit = (nextRange: TrajectoryTimeRange) => {
+ onRangeChange(nextRange)
+ }
+
+ const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
+ if (event.button === 2) {
+ panRef.current = {
+ anchorClientX: event.clientX,
+ anchorStart: domainStart,
+ moved: false,
+ pannable: viewport !== null,
+ pointerId: event.pointerId,
+ }
+ if (viewport !== null) setAnimateViewport(false)
+ setPanning(true)
+ if (typeof event.currentTarget.setPointerCapture === 'function') {
+ event.currentTarget.setPointerCapture(event.pointerId)
+ }
+ return
+ }
+ if (event.button !== 0) return
+ const anchor = fractionAt(event)
+ const anchorTime = domainStart + anchor * domainDuration
+ const recordIndex = recordIndexAt(event)
+ setHover({ fraction: anchor, recordIndex })
+ dragRef.current = {
+ pointerId: event.pointerId,
+ anchorTime,
+ anchorClientX: event.clientX,
+ recordIndex,
+ }
+ if (typeof event.currentTarget.setPointerCapture === 'function') {
+ event.currentTarget.setPointerCapture(event.pointerId)
+ }
+ setDraft({ start: anchorTime, end: anchorTime })
+ }
+
+ const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
+ const rect = event.currentTarget.getBoundingClientRect()
+ const fraction = fractionAt(event)
+ setHover({ fraction, recordIndex: recordIndexAt(event) })
+ const pan = panRef.current
+ if (pan !== null && pan.pointerId === event.pointerId) {
+ if (Math.abs(event.clientX - pan.anchorClientX) >= MINIMUM_DRAG_PX) {
+ pan.moved = true
+ }
+ if (!pan.pannable) return
+ const delta = (event.clientX - pan.anchorClientX) / Math.max(1, rect.width)
+ const nextStart = Math.min(
+ Math.max(pan.anchorStart - delta * domainDuration, model.start),
+ model.end - domainDuration,
+ )
+ setViewport({ start: nextStart, end: nextStart + domainDuration })
+ return
+ }
+ const drag = dragRef.current
+ if (drag === null || drag.pointerId !== event.pointerId) return
+ let nextDomainStart = domainStart
+ if (viewport !== null) {
+ const localX = event.clientX - rect.left
+ const edgeWidth = Math.min(
+ MAXIMUM_EDGE_PAN_PX,
+ Math.max(1, rect.width * EDGE_PAN_ZONE_FRACTION),
+ )
+ const direction = localX < edgeWidth
+ ? -1
+ : localX > rect.width - edgeWidth ? 1 : 0
+ if (direction !== 0) {
+ const edgeDistance = direction < 0
+ ? edgeWidth - localX
+ : localX - (rect.width - edgeWidth)
+ const strength = clampFraction(edgeDistance / edgeWidth)
+ const desiredStart = domainStart
+ + direction * domainDuration * EDGE_PAN_STEP_FRACTION
+ * Math.max(0.2, strength)
+ nextDomainStart = Math.min(
+ Math.max(desiredStart, model.start),
+ model.end - domainDuration,
+ )
+ if (nextDomainStart !== domainStart) {
+ setAnimateViewport(false)
+ setViewport({
+ start: nextDomainStart,
+ end: nextDomainStart + domainDuration,
+ })
+ }
+ }
+ }
+ const pointTime = nextDomainStart + fraction * domainDuration
+ setDraft(orderedRange(drag.anchorTime, pointTime))
+ }
+
+ const onPointerEnd = (event: PointerEvent<HTMLDivElement>) => {
+ const pan = panRef.current
+ if (pan !== null && pan.pointerId === event.pointerId) {
+ const moved = pan.moved
+ || Math.abs(event.clientX - pan.anchorClientX) >= MINIMUM_DRAG_PX
+ panRef.current = null
+ setPanning(false)
+ if (!moved) onRangeChange(null)
+ return
+ }
+ const drag = dragRef.current
+ if (drag === null || drag.pointerId !== event.pointerId) return
+ const pointFraction = fractionAt(event)
+ const pointTime = domainStart + pointFraction * domainDuration
+ const selected = orderedRange(drag.anchorTime, pointTime)
+ setHover({ fraction: pointFraction, recordIndex: recordIndexAt(event) })
+ dragRef.current = null
+ setDraft(null)
+ const click = Math.abs(event.clientX - drag.anchorClientX) < MINIMUM_DRAG_PX
+ const clickedSpan = click && drag.recordIndex !== null
+ ? model.spans.find(span => span.index === drag.recordIndex)
+ : undefined
+ if (clickedSpan !== undefined) {
+ onRangeChange(null)
+ onRecordSelect?.(clickedSpan.index)
+ return
+ }
+ const committedRange = selected.end - selected.start < minimumSelectionDuration
+ ? centeredRange(
+ click ? selected.start : (selected.start + selected.end) / 2,
+ minimumSelectionDuration,
+ model.start,
+ model.end,
+ )
+ : selected
+ commit(committedRange)
+ if (click) {
+ const timelinePoint = selected.start
+ const nearest = model.spans.reduce((candidate, span) => {
+ const candidateDistance = timelinePoint < candidate.start
+ ? candidate.start - timelinePoint
+ : timelinePoint > candidate.end ? timelinePoint - candidate.end : 0
+ const spanDistance = timelinePoint < span.start
+ ? span.start - timelinePoint
+ : timelinePoint > span.end ? timelinePoint - span.end : 0
+ return spanDistance < candidateDistance ? span : candidate
+ })
+ onRecordFocus?.(nearest.index)
+ }
+ }
+
+ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (event.key !== 'Escape' || range === null) return
+ event.preventDefault()
+ onRangeChange(null)
+ }
+
+ const onPointerCancel = () => {
+ dragRef.current = null
+ panRef.current = null
+ setDraft(null)
+ setHover(null)
+ setPanning(false)
+ }
+
+ return (
+ <section ref={rootRef} className={css.root} aria-label="Trajectory timeline">
+ <div className={css.plot}>
+ <LaneLabels />
+ <div
+ ref={trackRef}
+ className={css.track}
+ data-panning={panning || undefined}
+ aria-label="Timeline overview; drag horizontally to focus events"
+ tabIndex={0}
+ onKeyDown={onKeyDown}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerEnd}
+ onPointerCancel={onPointerCancel}
+ onPointerLeave={() => {
+ if (dragRef.current === null && panRef.current === null) setHover(null)
+ }}
+ onDoubleClick={(event) => {
+ event.preventDefault()
+ onRangeChange(null)
+ }}
+ onContextMenu={(event) => {
+ event.preventDefault()
+ }}
+ >
+ {showsEarlierBoundary && (
+ <EarlierHistoryBoundary
+ loading={olderBusy}
+ onHover={() => { setHover(null) }}
+ onLoad={loadEarlier}
+ />
+ )}
+ {hover !== null && hover.recordIndex === null && draft === null && (
+ <div
+ className={css.hoverLine}
+ data-timeline-hover-line
+ aria-hidden="true"
+ style={{
+ '--trajectory-hover-left': `${hover.fraction * 100}%`,
+ } as CSSProperties}
+ />
+ )}
+ {visibleRange !== null && (
+ <>
+ <div
+ className={css.selection}
+ data-dragging={draft === null ? undefined : 'true'}
+ aria-hidden="true"
+ style={{
+ '--trajectory-selection-left': `${visibleRange.start * 100}%`,
+ '--trajectory-selection-width': `${(visibleRange.end - visibleRange.start) * 100}%`,
+ } as CSSProperties}
+ />
+ <div
+ className={css.selectionEdges}
+ data-dragging={draft === null ? undefined : 'true'}
+ aria-hidden="true"
+ style={{
+ '--trajectory-selection-left': `${visibleRange.start * 100}%`,
+ '--trajectory-selection-width': `${(visibleRange.end - visibleRange.start) * 100}%`,
+ } as CSSProperties}
+ />
+ </>
+ )}
+ <div
+ className={css.turnBoundaries}
+ data-animate-viewport={animateViewport || undefined}
+ aria-hidden="true"
+ style={projectedDomainStyle}
+ >
+ {model.turnBoundaries
+ .filter(boundary =>
+ boundary.time > model.start
+ && boundary.time >= domainStart
+ && boundary.time <= domainStart + domainDuration)
+ .map(boundary => (
+ <span
+ className={css.turnBoundary}
+ data-turn={boundary.turn}
+ key={boundary.turn}
+ style={{
+ '--trajectory-turn-left':
+ `${(boundary.time - model.start) / fullDuration * 100}%`,
+ } as CSSProperties}
+ />
+ ))}
+ </div>
+ <div
+ className={css.lanes}
+ data-animate-viewport={animateViewport || undefined}
+ data-timeline-domain
+ style={projectedDomainStyle}
+ >
+ {model.spans
+ .filter(span =>
+ span.index === selectedIndex
+ || (span.end >= domainStart && span.start <= domainStart + domainDuration))
+ .map((span) => {
+ const left = (span.start - model.start) / fullDuration
+ const width = (span.end - span.start) / fullDuration
+ const widthPercent = width * 100
+ const detail = detailByIndex.get(span.index)
+ const ttftMs = detail?.ttftMs
+ const decodingMs = detail?.decodingMs
+ const ttftFraction = ttftMs === undefined
+ || decodingMs === undefined
+ || ttftMs + decodingMs <= 0
+ ? null
+ : ttftMs / (ttftMs + decodingMs)
+ return (
+ <Tooltip
+ key={span.index}
+ label={() => timelineTooltipLabel(span.kind, detail)}
+ side="bottom"
+ delayMs={TIMELINE_TOOLTIP_DELAY_MS}
+ >
+ <span
+ aria-hidden="true"
+ className={css.span}
+ data-timeline-span={span.kind}
+ data-timeline-record-index={span.index}
+ data-assistant-timing={ttftFraction === null ? undefined : 'true'}
+ data-error={span.isError || undefined}
+ data-equal-duration={mode === 'time' || undefined}
+ data-current={span.index === selectedIndex || undefined}
+ data-hovered={hover?.recordIndex === span.index || undefined}
+ data-search-match={searchMatchIndexes === null
+ ? undefined
+ : searchMatchIndexes.has(span.index) ? 'true' : 'false'}
+ data-selected={activeRange === null
+ ? undefined
+ : span.start <= activeRange.end && span.end >= activeRange.start
+ ? 'true'
+ : 'false'}
+ style={{
+ '--trajectory-span-left': `${left * 100}%`,
+ '--trajectory-span-width': `${widthPercent}%`,
+ '--trajectory-span-gap': `min(${widthPercent * 0.08}%, 1px)`,
+ '--trajectory-span-lane': span.lane,
+ ...(ttftFraction === null
+ ? {}
+ : { '--trajectory-assistant-ttft': `${ttftFraction * 100}%` }),
+ } as CSSProperties}
+ />
+ </Tooltip>
+ )
+ })}
+ </div>
+ </div>
+ </div>
+ </section>
+ )
+})
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryToolbar.module.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryToolbar.module.css
new file mode 100644
index 0000000000..13bf5d2af8
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryToolbar.module.css
@@ -0,0 +1,217 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+/* Adapted from packages/client/ui-trajectory/src/client/TrajectoryToolbar.module.css under MIT. */
+.root {
+ position: sticky;
+ top: 0;
+ z-index: 4;
+ box-sizing: border-box;
+ width: 100%;
+ height: var(--dsh-trajectory-toolbar-height);
+ border-bottom: 1px solid var(--dsw-alias-border-l2);
+ background: var(--dsw-alias-bg-layer-1);
+}
+
+.inner {
+ display: flex;
+ align-items: center;
+ box-sizing: border-box;
+ width: 100%;
+ height: 100%;
+ padding: 0 6px;
+ gap: 8px;
+}
+
+.actions {
+ display: flex;
+ flex: none;
+ align-items: center;
+ gap: 2px;
+}
+
+.toggle {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ height: 20px;
+ padding: 0 7px;
+ gap: 4px;
+ border: 0;
+ border-radius: 3px;
+ color: var(--dsw-alias-label-tertiary);
+ background: transparent;
+ cursor: pointer;
+ font: var(--dsw-font-xxs-12);
+}
+
+.toggle:hover {
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.toggle[aria-pressed='true'] {
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.toggle:focus-visible {
+ outline: 1px solid var(--dsw-alias-state-business-primary);
+ outline-offset: 1px;
+}
+
+.toggleIcon {
+ flex: none;
+ width: 12px;
+ height: 12px;
+ stroke: currentColor;
+ stroke-width: 1.25;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+.control {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ justify-content: center;
+ box-sizing: border-box;
+ width: 88px;
+ height: 20px;
+ padding: 0 5px;
+ gap: 4px;
+ border: 0;
+ border-radius: 0;
+ color: var(--dsw-alias-label-tertiary);
+ background: transparent;
+ cursor: pointer;
+ font: var(--dsw-font-xxs-12);
+}
+
+.control[hidden] {
+ display: none;
+}
+
+.control:hover:not(:disabled),
+.control[aria-checked='true'],
+.control[aria-pressed='true'] {
+ color: var(--dsw-alias-label-primary);
+}
+
+.control:focus-visible {
+ outline: 1px solid var(--dsw-alias-state-business-primary);
+ outline-offset: 1px;
+}
+
+.control:disabled {
+ color: var(--dsw-alias-label-dimmed);
+ cursor: not-allowed;
+}
+
+.controlTrack {
+ position: relative;
+ display: inline-block;
+ flex: none;
+ width: 20px;
+ height: 10px;
+ border-radius: 5px;
+ background: var(--dsw-alias-border-l2);
+ transition: background-color 120ms var(--ds-ease-in-out);
+}
+
+.controlThumb {
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--dsw-alias-bg-layer-1);
+ transition: transform 120ms var(--ds-ease-in-out);
+}
+
+.controlTrack[data-on='true'] {
+ background: var(--dsw-alias-state-business-primary);
+}
+
+.controlTrack[data-on='true'] .controlThumb {
+ transform: translateX(10px);
+}
+
+.action {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ height: 20px;
+ padding: 0 5px;
+ gap: 4px;
+ border: 0;
+ border-radius: 3px;
+ color: var(--dsw-alias-label-tertiary);
+ background: transparent;
+ cursor: pointer;
+ font: var(--dsw-font-xxs-12);
+}
+
+.action:hover {
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.action:focus-visible {
+ outline: 1px solid var(--dsw-alias-state-business-primary);
+ outline-offset: 1px;
+}
+
+.actionIcon {
+ color: var(--dsw-alias-label-tertiary);
+ font: 14px/14px var(--ds-font-family-code);
+}
+
+.search {
+ display: flex;
+ flex: 0 1 164px;
+ align-items: center;
+ min-width: 84px;
+ height: 22px;
+ margin-left: auto;
+ padding: 0 6px;
+ gap: 4px;
+ border: 1px solid var(--dsw-alias-border-l2);
+ border-radius: 4px;
+ color: var(--dsw-alias-label-caption);
+ background: var(--dsw-alias-bg-layer-2);
+}
+
+.search:hover {
+ border-color: var(--dsw-alias-label-caption);
+}
+
+.search:focus-within {
+ border-color: var(--dsw-alias-state-business-primary);
+ background: var(--dsw-alias-bg-layer-1);
+}
+
+.searchIcon {
+ flex: none;
+}
+
+.searchInput {
+ min-width: 0;
+ width: 100%;
+ padding: 0;
+ border: 0;
+ outline: 0;
+ color: var(--dsw-alias-label-primary);
+ background: transparent;
+ font: var(--dsw-font-xxs-12);
+}
+
+.searchInput::placeholder {
+ color: var(--dsw-alias-label-caption);
+}
+
+.searchInput::-webkit-search-cancel-button {
+ width: 12px;
+ height: 12px;
+ cursor: pointer;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryToolbar.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryToolbar.tsx
new file mode 100644
index 0000000000..a3d68167a6
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryToolbar.tsx
@@ -0,0 +1,133 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Trajectory toolbar: timeline and ledger fold controls.
+ * Adapted mechanically from `packages/client/ui-trajectory/src/client/TrajectoryToolbar.tsx`
+ * under the repository MIT license.
+ */
+
+import { IconSearchOutline16 } from '../primitives/index.ts'
+import type { TrajectoryTranslate } from './i18n.ts'
+import css from './TrajectoryToolbar.module.css'
+
+export interface TrajectoryToolbarProps {
+ /** Whether timeline blocks use recorded durations instead of equal widths. */
+ actualDuration: boolean
+ /** Select recorded-duration or equal-width blocks. */
+ onActualDurationChange: (actualDuration: boolean) => void
+ /** Whether recorded timing retains idle gaps between operations. */
+ actualTime: boolean
+ /** Select complete wall-clock timing or idle-compressed timing. */
+ onActualTimeChange: (actualTime: boolean) => void
+ /** Whether every collapsible turn is currently folded. */
+ allTurnsCollapsed: boolean
+ /** Fold or expand every collapsible turn. */
+ onToggleAllTurns: () => void
+ /** Whether every collapsible assistant's tool calls are currently folded. */
+ allAssistantsCollapsed: boolean
+ /** Fold or expand tool calls under every collapsible assistant. */
+ onToggleAllAssistants: () => void
+ /** Current live ledger search query. */
+ searchQuery: string
+ /** Update the live ledger search query. */
+ onSearchQueryChange: (query: string) => void
+ /** Translate a toolbar dictionary key. */
+ t: TrajectoryTranslate
+}
+
+/**
+ * Render the sticky trajectory toolbar.
+ * @param props - rendered counts and whole-list fold state.
+ * @returns the toolbar element.
+ */
+export function TrajectoryToolbar({
+ actualDuration,
+ onActualDurationChange,
+ actualTime,
+ onActualTimeChange,
+ allTurnsCollapsed,
+ onToggleAllTurns,
+ allAssistantsCollapsed,
+ onToggleAllAssistants,
+ searchQuery,
+ onSearchQueryChange,
+ t,
+}: TrajectoryToolbarProps) {
+ return (
+ <div className={css.root} role="toolbar" aria-label={t('toolbar.aria')}>
+ <div className={css.inner}>
+ <div className={css.actions}>
+ <button
+ type="button"
+ className={css.toggle}
+ aria-label={t('toolbar.useActualDuration')}
+ aria-pressed={actualDuration}
+ title={actualDuration ? t('toolbar.useEqualWidth') : t('toolbar.useActualDuration')}
+ onClick={() => { onActualDurationChange(!actualDuration) }}
+ >
+ <svg
+ className={css.toggleIcon}
+ viewBox="0 0 16 16"
+ fill="none"
+ aria-hidden="true"
+ >
+ <circle cx="8" cy="8" r="5.25" />
+ <path d="M8 4.75V8l2.25 1.5" />
+ </svg>
+ {t('toolbar.duration')}
+ </button>
+ <button
+ type="button"
+ className={css.control}
+ role="switch"
+ aria-checked={actualTime}
+ hidden
+ onClick={() => { onActualTimeChange(!actualTime) }}
+ >
+ <span>{t('toolbar.actualTime')}</span>
+ <span className={css.controlTrack} data-on={actualTime || undefined} aria-hidden="true">
+ <span className={css.controlThumb} />
+ </span>
+ </button>
+ <button
+ type="button"
+ className={css.action}
+ aria-label={allTurnsCollapsed ? t('toolbar.expandTurns') : t('toolbar.collapseTurns')}
+ aria-pressed={allTurnsCollapsed}
+ title={allTurnsCollapsed ? t('toolbar.expandTurns') : t('toolbar.collapseTurns')}
+ onClick={onToggleAllTurns}
+ >
+ <span className={css.actionIcon} aria-hidden="true">
+ {allTurnsCollapsed ? '⊞' : '⊟'}
+ </span>
+ {t('toolbar.turns')}
+ </button>
+ <button
+ type="button"
+ className={css.action}
+ aria-label={allAssistantsCollapsed ? t('toolbar.expandCalls') : t('toolbar.collapseCalls')}
+ aria-pressed={allAssistantsCollapsed}
+ title={allAssistantsCollapsed ? t('toolbar.expandCalls') : t('toolbar.collapseCalls')}
+ onClick={onToggleAllAssistants}
+ >
+ <span className={css.actionIcon} aria-hidden="true">
+ {allAssistantsCollapsed ? '⊞' : '⊟'}
+ </span>
+ {t('toolbar.calls')}
+ </button>
+ </div>
+ <div className={css.search}>
+ <IconSearchOutline16 size={11} className={css.searchIcon} />
+ <input
+ type="search"
+ className={css.searchInput}
+ aria-label={t('toolbar.search')}
+ placeholder={t('toolbar.searchPlaceholder')}
+ value={searchQuery}
+ onChange={(event) => { onSearchQueryChange(event.currentTarget.value) }}
+ />
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/i18n.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/i18n.ts
new file mode 100644
index 0000000000..5c72ab76b1
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/i18n.ts
@@ -0,0 +1,51 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Standalone trajectory toolbar dictionary. */
+
+export type TrajectoryKey =
+ | 'toolbar.aria'
+ | 'toolbar.duration'
+ | 'toolbar.useActualDuration'
+ | 'toolbar.useEqualWidth'
+ | 'toolbar.actualTime'
+ | 'toolbar.turns'
+ | 'toolbar.expandTurns'
+ | 'toolbar.collapseTurns'
+ | 'toolbar.calls'
+ | 'toolbar.expandCalls'
+ | 'toolbar.collapseCalls'
+ | 'toolbar.search'
+ | 'toolbar.searchPlaceholder'
+
+export type TrajectoryTranslate = (key: TrajectoryKey) => string
+
+export const en: Readonly<Record<TrajectoryKey, string>> = {
+ 'toolbar.aria': 'Trajectory toolbar',
+ 'toolbar.duration': 'Duration',
+ 'toolbar.useActualDuration': 'Use actual duration',
+ 'toolbar.useEqualWidth': 'Use equal-width operations',
+ 'toolbar.actualTime': 'Actual time',
+ 'toolbar.turns': 'Turns',
+ 'toolbar.expandTurns': 'Expand turns',
+ 'toolbar.collapseTurns': 'Collapse turns',
+ 'toolbar.calls': 'Calls',
+ 'toolbar.expandCalls': 'Expand calls',
+ 'toolbar.collapseCalls': 'Collapse calls',
+ 'toolbar.search': 'Search trajectory',
+ 'toolbar.searchPlaceholder': 'Search',
+}
+
+export const zh: Readonly<Record<TrajectoryKey, string>> = {
+ ...en,
+ 'toolbar.aria': '轨迹工具栏',
+ 'toolbar.actualTime': '实际时间',
+ 'toolbar.search': '搜索轨迹',
+ 'toolbar.searchPlaceholder': '搜索',
+}
+
+/** Create a translator from a complete or partial dictionary. */
+export function trajectoryTranslator(
+ dictionary: Partial<Record<TrajectoryKey, string>> = en,
+): TrajectoryTranslate {
+ return key => dictionary[key] ?? en[key]
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/theme.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/theme.css
new file mode 100644
index 0000000000..125eb3a5d0
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/theme.css
@@ -0,0 +1,28 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+/*
+ * DSH theme provenance: exact copied source sheets are recorded in
+ * ../theme/PROVENANCE.md and used under the repository MIT license.
+ */
+@import '../theme/base.css';
+@import '../theme/design-platform.css';
+@import '../theme/scrollbar.css';
+@import '../theme/gradient-shadow-text.css';
+@import '../theme/shiki.css';
+
+.jiuwenTrajectoryTheme {
+ height: 100%;
+ min-height: 0;
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-bg-layer-1);
+ font-family: var(--dsw-font-family);
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+
+.jiuwenTrajectoryTheme button,
+.jiuwenTrajectoryTheme input,
+.jiuwenTrajectoryTheme select,
+.jiuwenTrajectoryTheme textarea {
+ font-family: inherit;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/agent-loop-records.json b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/agent-loop-records.json
new file mode 100644
index 0000000000..225ed5f0e9
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/agent-loop-records.json
@@ -0,0 +1,111 @@
+[
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "dddddddddddddddddddddddddddddddd",
+ "spanId": "1000000000000001",
+ "name": "llm.call",
+ "startTimeUnixNano": "1000000000",
+ "endTimeUnixNano": "2000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "behavior-session" } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "[{\"type\":\"text\",\"content\":\"Session system v1\"}]" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeat question\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"<system-reminder><prompt-attachment type=\\\"context\\\">Dynamic context</prompt-attachment></system-reminder>\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Historical output\"}]}]" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.step.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } },
+ { "key": "dsh.session.source_sequence", "value": { "intValue": "1" } }
+ ],
+ "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
+ "spanId": "2000000000000002",
+ "name": "llm.call",
+ "startTimeUnixNano": "3000000000",
+ "endTimeUnixNano": "4000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "behavior-session" } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "[{\"type\":\"text\",\"content\":\"Session system v1\"}]" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeat question\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Historical output\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeat question\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"<system-reminder><prompt-attachment type=\\\"context\\\">Dynamic context</prompt-attachment></system-reminder>\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"I will search\"},{\"type\":\"tool_call\",\"id\":\"call-loop-1\",\"name\":\"search\",\"arguments\":{\"q\":\"fact\"}}]}]" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "2" } },
+ { "key": "openjiuwen.step.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } },
+ { "key": "dsh.session.source_sequence", "value": { "intValue": "2" } }
+ ],
+ "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
+ "spanId": "3000000000000003",
+ "name": "tool.search",
+ "startTimeUnixNano": "4100000000",
+ "endTimeUnixNano": "4300000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "execute_tool" } },
+ { "key": "gen_ai.tool.name", "value": { "stringValue": "search" } },
+ { "key": "gen_ai.tool.call.id", "value": { "stringValue": "call-loop-1" } },
+ { "key": "gen_ai.tool.call.arguments", "value": { "stringValue": "{\"q\":\"fact\"}" } },
+ { "key": "openjiuwen.tool.authoritative", "value": { "boolValue": true } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "2" } },
+ { "key": "openjiuwen.step.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "tool" } },
+ { "key": "dsh.session.source_sequence", "value": { "intValue": "3" } }
+ ],
+ "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
+ "spanId": "4000000000000004",
+ "name": "llm.call",
+ "startTimeUnixNano": "4400000000",
+ "endTimeUnixNano": "5000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "behavior-session" } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "[{\"type\":\"text\",\"content\":\"Session system v2\"}]" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeat question\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeat question\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"I will search\"},{\"type\":\"tool_call\",\"id\":\"call-loop-1\",\"name\":\"search\",\"arguments\":{\"q\":\"fact\"}}]},{\"role\":\"tool\",\"parts\":[{\"type\":\"tool_call_response\",\"id\":\"call-loop-1\",\"name\":\"search\",\"response\":{\"answer\":42}}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"New context fact\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"<system-reminder><prompt-attachment type=\\\"context\\\">Dynamic context</prompt-attachment></system-reminder>\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"The answer is 42\"}]}]" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "2" } },
+ { "key": "openjiuwen.step.number", "value": { "intValue": "2" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "2" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } },
+ { "key": "dsh.session.source_sequence", "value": { "intValue": "4" } }
+ ],
+ "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
+ "spanId": "5000000000000005",
+ "name": "llm.call",
+ "startTimeUnixNano": "5500000000",
+ "endTimeUnixNano": "6200000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "behavior-session" } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "[{\"type\":\"text\",\"content\":\"Session system v2\"}]" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeat question\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Repeat question\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"I will search\"},{\"type\":\"tool_call\",\"id\":\"call-loop-1\",\"name\":\"search\",\"arguments\":{\"q\":\"fact\"}}]},{\"role\":\"tool\",\"parts\":[{\"type\":\"tool_call_response\",\"id\":\"call-loop-1\",\"name\":\"search\",\"response\":{\"answer\":42}}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"<system-reminder><prompt-attachment type=\\\"context\\\">Dynamic context</prompt-attachment></system-reminder>\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Done\"}]}]" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "2" } },
+ { "key": "openjiuwen.step.number", "value": { "intValue": "3" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "3" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } },
+ { "key": "dsh.session.source_sequence", "value": { "intValue": "5" } }
+ ],
+ "status": { "code": 1 }
+ }] }] }]
+ }
+]
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/behavior-edge-records.json b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/behavior-edge-records.json
new file mode 100644
index 0000000000..fad5efc95b
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/behavior-edge-records.json
@@ -0,0 +1,106 @@
+[
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "ffffffffffffffffffffffffffffffff", "spanId": "1000000000000011", "name": "llm.call",
+ "startTimeUnixNano": "10000000000", "endTimeUnixNano": "11000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "edge-session" } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "[{\"type\":\"text\",\"content\":\"Stable system\"}]" } },
+ { "key": "gen_ai.tool.definitions", "value": { "stringValue": "[{\"type\":\"function\",\"function\":{\"name\":\"stable_tool\",\"parameters\":{}}}]" } },
+ { "key": "gen_ai.request.model", "value": { "stringValue": "model-a" } },
+ { "key": "gen_ai.request.temperature", "value": { "doubleValue": 0 } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"A\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"B\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"C\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Same output\"}]}]" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } }, { "key": "openjiuwen.step.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "1" } }, { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }
+ ], "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "ffffffffffffffffffffffffffffffff", "spanId": "2000000000000022", "name": "llm.call",
+ "startTimeUnixNano": "12000000000", "endTimeUnixNano": "13000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "edge-session" } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "[{\"type\":\"text\",\"content\":\"Stable system\"}]" } },
+ { "key": "gen_ai.tool.definitions", "value": { "stringValue": "[{\"type\":\"function\",\"function\":{\"name\":\"stable_tool\",\"parameters\":{}}}]" } },
+ { "key": "gen_ai.request.model", "value": { "stringValue": "model-b" } },
+ { "key": "gen_ai.request.temperature", "value": { "doubleValue": 0.7 } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"A\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"C\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Same output\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Same output\"}]}]" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } }, { "key": "openjiuwen.step.number", "value": { "intValue": "2" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "2" } }, { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }
+ ], "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "ffffffffffffffffffffffffffffffff", "spanId": "3000000000000033", "name": "llm.call",
+ "startTimeUnixNano": "14000000000", "endTimeUnixNano": "15000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "edge-session" } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "[{\"type\":\"text\",\"content\":\"Stable system\"}]" } },
+ { "key": "gen_ai.tool.definitions", "value": { "stringValue": "[{\"type\":\"function\",\"function\":{\"name\":\"stable_tool\",\"parameters\":{}}}]" } },
+ { "key": "gen_ai.request.model", "value": { "stringValue": "model-c" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"A\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"B\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"C\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Same output\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Same output\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Same output\"}]}]" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } }, { "key": "openjiuwen.step.number", "value": { "intValue": "3" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "3" } }, { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }
+ ], "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "ffffffffffffffffffffffffffffffff", "spanId": "4000000000000044", "name": "llm.call",
+ "startTimeUnixNano": "16000000000", "endTimeUnixNano": "17000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "edge-session" } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "[{\"type\":\"text\",\"content\":\"Stable system\"}]" } },
+ { "key": "gen_ai.tool.definitions", "value": { "stringValue": "[{\"type\":\"function\",\"function\":{\"name\":\"stable_tool\",\"parameters\":{}}}]" } },
+ { "key": "gen_ai.request.model", "value": { "stringValue": "model-d" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"A\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"C\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"B\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Same output\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Same output\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Same output\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Final output\"}]}]" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } }, { "key": "openjiuwen.step.number", "value": { "intValue": "4" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "4" } }, { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }
+ ], "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "ffffffffffffffffffffffffffffffff", "spanId": "5000000000000055", "name": "llm.call",
+ "startTimeUnixNano": "18000000000", "endTimeUnixNano": "19000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "edge-session" } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "[{\"type\":\"text\",\"content\":\"Stable system\"}]" } },
+ { "key": "gen_ai.tool.definitions", "value": { "stringValue": "[{\"type\":\"function\",\"function\":{\"name\":\"stable_tool\",\"parameters\":{}}}]" } },
+ { "key": "gen_ai.request.model", "value": { "stringValue": "model-e" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"A\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"C\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"B\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Unique output\"}]}]" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } }, { "key": "openjiuwen.step.number", "value": { "intValue": "5" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "5" } }, { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }
+ ], "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "ffffffffffffffffffffffffffffffff", "spanId": "6000000000000066", "name": "llm.call",
+ "startTimeUnixNano": "20000000000", "endTimeUnixNano": "21000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "edge-session" } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "[{\"type\":\"text\",\"content\":\"Stable system\"}]" } },
+ { "key": "gen_ai.tool.definitions", "value": { "stringValue": "[{\"type\":\"function\",\"function\":{\"name\":\"stable_tool\",\"parameters\":{}}}]" } },
+ { "key": "gen_ai.request.model", "value": { "stringValue": "model-f" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"A\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"C\"}]},{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"B\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Same output\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"End output\"}]}]" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } }, { "key": "openjiuwen.step.number", "value": { "intValue": "6" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "6" } }, { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }
+ ], "status": { "code": 1 }
+ }] }] }]
+ }
+]
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/core-contract-records.json b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/core-contract-records.json
new file mode 100644
index 0000000000..3801ff0ae9
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/core-contract-records.json
@@ -0,0 +1,185 @@
+[
+ {
+ "resourceSpans": [{
+ "scopeSpans": [{
+ "spans": [{
+ "traceId": "cccccccccccccccccccccccccccccccc",
+ "spanId": "1000000000000000",
+ "name": "agent.agent.plan.core-session",
+ "startTimeUnixNano": "1000000000",
+ "endTimeUnixNano": "5000000000",
+ "attributes": [
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "core-session" } },
+ { "key": "openjiuwen.session.id", "value": { "stringValue": "openjiuwen-conflict" } },
+ { "key": "session.id", "value": { "stringValue": "legacy-conflict" } },
+ { "key": "openjiuwen.session_id", "value": { "stringValue": "old-openjiuwen-conflict" } },
+ { "key": "agentteam.session.id", "value": { "stringValue": "team-conflict" } },
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "invoke_agent" } },
+ { "key": "openjiuwen.trace.root", "value": { "boolValue": true } },
+ { "key": "openjiuwen.trace.schema_version", "value": { "stringValue": "1" } },
+ { "key": "openjiuwen.trace.complete", "value": { "boolValue": true } },
+ { "key": "openjiuwen.trace.forced_close", "value": { "boolValue": true } },
+ { "key": "openjiuwen.request.id", "value": { "stringValue": "web-request-1" } },
+ { "key": "openjiuwen.run.id", "value": { "stringValue": "run-1" } },
+ { "key": "openjiuwen.turn.id", "value": { "stringValue": "turn-1" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.agent.mode", "value": { "stringValue": "agent.plan" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "turn" } }
+ ],
+ "status": { "code": 1 }
+ }]
+ }]
+ }]
+ },
+ {
+ "resourceSpans": [{
+ "scopeSpans": [{
+ "spans": [{
+ "traceId": "cccccccccccccccccccccccccccccccc",
+ "spanId": "2000000000000000",
+ "parentSpanId": "1000000000000000",
+ "name": "llm.call",
+ "startTimeUnixNano": "2000000000",
+ "endTimeUnixNano": "4000000000",
+ "attributes": [
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "core-session" } },
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.provider.name", "value": { "stringValue": "openai" } },
+ { "key": "gen_ai.system", "value": { "stringValue": "legacy-provider-conflict" } },
+ { "key": "gen_ai.request.model", "value": { "stringValue": "request-model" } },
+ { "key": "gen_ai.request.temperature", "value": { "doubleValue": 0 } },
+ { "key": "gen_ai.request.top_p", "value": { "doubleValue": 0.8 } },
+ { "key": "gen_ai.request.max_tokens", "value": { "intValue": "0" } },
+ { "key": "gen_ai.request.stream", "value": { "boolValue": true } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "[{\"type\":\"text\",\"content\":\"Core system\"}]" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Core question\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"reasoning\",\"content\":\"Core reasoning\"},{\"type\":\"text\",\"content\":\"Core answer\"},{\"type\":\"tool_call\",\"id\":\"call-1\",\"name\":\"search\",\"arguments\":{\"q\":\"next\"}}]}]" } },
+ { "key": "gen_ai.tool.definitions", "value": { "stringValue": "[{\"type\":\"function\",\"function\":{\"name\":\"search\",\"description\":\"Search docs\",\"parameters\":{\"type\":\"object\",\"properties\":{\"q\":{\"type\":\"string\"}}}}}]" } },
+ { "key": "gen_ai.response.id", "value": { "stringValue": "resp-1" } },
+ { "key": "gen_ai.response.model", "value": { "stringValue": "response-model" } },
+ { "key": "gen_ai.response.finish_reasons", "value": { "arrayValue": { "values": [{ "stringValue": "tool_calls" }] } } },
+ { "key": "gen_ai.response.finish_reason", "value": { "stringValue": "legacy-conflict" } },
+ { "key": "gen_ai.response.time_to_first_chunk", "value": { "doubleValue": 0 } },
+ { "key": "gen_ai.usage.input_tokens", "value": { "intValue": "0" } },
+ { "key": "gen_ai.usage.prompt_tokens", "value": { "intValue": "99" } },
+ { "key": "gen_ai.usage.output_tokens", "value": { "intValue": "7" } },
+ { "key": "gen_ai.usage.completion_tokens", "value": { "intValue": "88" } },
+ { "key": "gen_ai.usage.cache_read.input_tokens", "value": { "intValue": "3" } },
+ { "key": "gen_ai.usage.cache_creation.input_tokens", "value": { "intValue": "2" } },
+ { "key": "gen_ai.usage.reasoning.output_tokens", "value": { "intValue": "2" } },
+ { "key": "gen_ai.usage.total_tokens", "value": { "intValue": "7" } },
+ { "key": "gen_ai.agent.id", "value": { "stringValue": "agent-1" } },
+ { "key": "gen_ai.agent.name", "value": { "stringValue": "Core Agent" } },
+ { "key": "gen_ai.agent.version", "value": { "stringValue": "1.0" } },
+ { "key": "gen_ai.agent.description", "value": { "stringValue": "Contract fixture" } },
+ { "key": "openjiuwen.request.id", "value": { "stringValue": "web-request-1" } },
+ { "key": "openjiuwen.run.id", "value": { "stringValue": "run-1" } },
+ { "key": "openjiuwen.turn.id", "value": { "stringValue": "turn-1" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.step.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.request.purpose", "value": { "stringValue": "assistant" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } },
+ { "key": "openjiuwen.trace.schema_version", "value": { "stringValue": "1" } },
+ { "key": "openjiuwen.gen_ai.usage.input_cost", "value": { "doubleValue": 0 } },
+ { "key": "openjiuwen.gen_ai.usage.output_cost", "value": { "doubleValue": 0.02 } },
+ { "key": "openjiuwen.gen_ai.usage.total_cost", "value": { "doubleValue": 0.02 } },
+ { "key": "openjiuwen.gen_ai.response.total_latency_ms", "value": { "doubleValue": 2000 } },
+ { "key": "openjiuwen.gen_ai.response.tpot_ms", "value": { "doubleValue": 250 } },
+ { "key": "openjiuwen.gen_ai.response.prompt_token_ids", "value": { "stringValue": "[1,2]" } },
+ { "key": "openjiuwen.gen_ai.response.completion_token_ids", "value": { "stringValue": "[3,4]" } },
+ { "key": "openjiuwen.gen_ai.response.logprobs", "value": { "stringValue": "[{\"token\":\"Core\",\"logprob\":-0.1}]" } },
+ { "key": "openjiuwen.gen_ai.response.parser_result", "value": { "stringValue": "{\"ok\":true}" } },
+ { "key": "openjiuwen.gen_ai.response.provider_metadata", "value": { "stringValue": "{\"system_fingerprint\":\"fp\"}" } },
+ { "key": "langfuse.observation.output", "value": { "stringValue": "{\"choices\":[{\"message\":{\"role\":\"assistant\",\"content\":\"Langfuse conflict\"},\"finish_reason\":\"langfuse-conflict\"}],\"usage\":{\"input_tokens\":77,\"output_tokens\":66,\"total_tokens\":143}}" } }
+ ],
+ "events": [
+ {
+ "timeUnixNano": "2500000000",
+ "name": "dsh.stream.chunk",
+ "attributes": [
+ { "key": "dsh.event.sequence", "value": { "intValue": "0" } },
+ { "key": "dsh.stream.kind", "value": { "stringValue": "text-delta" } },
+ { "key": "dsh.stream.text", "value": { "stringValue": "DSH conflict" } }
+ ]
+ },
+ {
+ "timeUnixNano": "2500000001",
+ "name": "openjiuwen.stream.chunk",
+ "attributes": [
+ { "key": "openjiuwen.event.sequence", "value": { "intValue": "0" } },
+ { "key": "openjiuwen.stream.kind", "value": { "stringValue": "text-delta" } },
+ { "key": "openjiuwen.stream.text", "value": { "stringValue": "OpenJiuwen wins" } }
+ ]
+ },
+ {
+ "timeUnixNano": "2500000002",
+ "name": "llm.chunk",
+ "attributes": [
+ { "key": "text", "value": { "stringValue": "must not project" } }
+ ]
+ }
+ ],
+ "status": { "code": 1 }
+ }]
+ }]
+ }]
+ },
+ {
+ "resourceSpans": [{
+ "scopeSpans": [{
+ "spans": [{
+ "traceId": "cccccccccccccccccccccccccccccccc",
+ "spanId": "3000000000000000",
+ "parentSpanId": "1000000000000000",
+ "name": "tool.search",
+ "startTimeUnixNano": "4100000000",
+ "endTimeUnixNano": "4500000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "execute_tool" } },
+ { "key": "gen_ai.tool.name", "value": { "stringValue": "search" } },
+ { "key": "gen_ai.tool.call.id", "value": { "stringValue": "call-1" } },
+ { "key": "gen_ai.tool.call.arguments", "value": { "stringValue": "{\"q\":\"next\"}" } },
+ { "key": "gen_ai.tool.call.result", "value": { "stringValue": "null" } },
+ { "key": "gen_ai.tool.type", "value": { "stringValue": "function" } },
+ { "key": "gen_ai.tool.description", "value": { "stringValue": "Search docs" } },
+ { "key": "openjiuwen.tool.resource_id", "value": { "stringValue": "resource-search" } },
+ { "key": "openjiuwen.tool.type", "value": { "stringValue": "function" } },
+ { "key": "openjiuwen.tool.authoritative", "value": { "boolValue": true } },
+ { "key": "openjiuwen.span.forced_close", "value": { "boolValue": true } },
+ { "key": "openjiuwen.span.forced_close.reason", "value": { "stringValue": "trace_safety_flush" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.step.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "tool" } }
+ ],
+ "status": { "code": 1 }
+ }]
+ }]
+ }]
+ },
+ {
+ "resourceSpans": [{
+ "scopeSpans": [{
+ "spans": [{
+ "traceId": "cccccccccccccccccccccccccccccccc",
+ "spanId": "4000000000000000",
+ "parentSpanId": "1000000000000000",
+ "name": "tool.search.callback",
+ "startTimeUnixNano": "4100000001",
+ "endTimeUnixNano": "4500000001",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "execute_tool" } },
+ { "key": "gen_ai.tool.name", "value": { "stringValue": "search" } },
+ { "key": "gen_ai.tool.call.id", "value": { "stringValue": "call-1" } },
+ { "key": "gen_ai.tool.call.arguments", "value": { "stringValue": "{\"q\":\"shadow\"}" } },
+ { "key": "gen_ai.tool.call.result", "value": { "stringValue": "{\"shadow\":true}" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.step.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "tool" } }
+ ],
+ "status": { "code": 1 }
+ }]
+ }]
+ }]
+ }
+]
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/legacy-langfuse-records.json b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/legacy-langfuse-records.json
new file mode 100644
index 0000000000..d63444f23d
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/legacy-langfuse-records.json
@@ -0,0 +1,120 @@
+[
+ {
+ "resourceSpans": [
+ {
+ "scopeSpans": [
+ {
+ "spans": [
+ {
+ "traceId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "spanId": "aaaaaaaaaaaaaaaa",
+ "name": "chat",
+ "startTimeUnixNano": "1000000000",
+ "endTimeUnixNano": "2000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "invalid structured system" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "invalid structured input" } },
+ { "key": "gen_ai.prompt.0.role", "value": { "stringValue": "system" } },
+ { "key": "gen_ai.prompt.0.content", "value": { "stringValue": "legacy system" } },
+ { "key": "gen_ai.prompt.1.role", "value": { "stringValue": "user" } },
+ { "key": "gen_ai.prompt.1.content", "value": { "stringValue": "legacy user" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "invalid structured output" } },
+ { "key": "langfuse.observation.output", "value": { "stringValue": "{\"choices\":[{\"message\":{\"role\":\"assistant\",\"content\":\"langfuse answer\",\"tool_calls\":[{\"id\":\"call-legacy\",\"type\":\"function\",\"function\":{\"name\":\"lookup\",\"arguments\":\"{\\\"query\\\":\\\"legacy\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":3}}" } },
+ { "key": "gen_ai.usage.prompt_tokens", "value": { "intValue": "7" } },
+ { "key": "gen_ai.usage.completion_tokens", "value": { "intValue": "3" } },
+ { "key": "gen_ai.usage.cache_tokens", "value": { "intValue": "2" } },
+ { "key": "gen_ai.usage.reasoning_tokens", "value": { "intValue": "0" } },
+ { "key": "gen_ai.response.time_to_first_token_ms", "value": { "doubleValue": 250 } }
+ ],
+ "status": { "code": 1 }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "resourceSpans": [
+ {
+ "scopeSpans": [
+ {
+ "spans": [
+ {
+ "traceId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "spanId": "bbbbbbbbbbbbbbbb",
+ "name": "chat",
+ "startTimeUnixNano": "3000000000",
+ "endTimeUnixNano": "4000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.prompt", "value": { "stringValue": "scalar user" } },
+ { "key": "gen_ai.completion", "value": { "stringValue": "scalar answer" } }
+ ],
+ "status": { "code": 1 }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "resourceSpans": [
+ {
+ "scopeSpans": [
+ {
+ "spans": [
+ {
+ "traceId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "spanId": "cccccccccccccccc",
+ "parentSpanId": "bbbbbbbbbbbbbbbb",
+ "name": "tool.lookup",
+ "startTimeUnixNano": "4100000000",
+ "endTimeUnixNano": "4200000000",
+ "attributes": [
+ { "key": "langfuse.observation.type", "value": { "stringValue": "tool" } },
+ { "key": "gen_ai.tool.name", "value": { "stringValue": "lookup" } },
+ { "key": "gen_ai.tool.id", "value": { "stringValue": "call-legacy" } },
+ { "key": "gen_ai.tool.input", "value": { "stringValue": "{\"query\":\"legacy\"}" } },
+ { "key": "gen_ai.tool.output", "value": { "stringValue": "{\"result\":\"legacy-result\"}" } }
+ ],
+ "status": { "code": 1 }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "resourceSpans": [
+ {
+ "scopeSpans": [
+ {
+ "spans": [
+ {
+ "traceId": "dddddddddddddddddddddddddddddddd",
+ "spanId": "dddddddddddddddd",
+ "name": "provider.request",
+ "startTimeUnixNano": "5000000000",
+ "endTimeUnixNano": "6000000000",
+ "attributes": [
+ { "key": "openjiuwen.session_id", "value": { "stringValue": "old-openjiuwen-session" } },
+ { "key": "langfuse.observation.type", "value": { "stringValue": "generation" } },
+ { "key": "langfuse.observation.input", "value": { "stringValue": "[{\"role\":\"user\",\"content\":\"embedded usage question\"}]" } },
+ { "key": "langfuse.observation.output", "value": { "stringValue": "{\"choices\":[{\"message\":{\"role\":\"assistant\",\"content\":\"embedded usage answer\"},\"finish_reason\":\"stop\"}],\"usage\":{\"input_tokens\":0,\"output_tokens\":4,\"total_tokens\":4,\"cache_tokens\":0,\"cache_creation_input_tokens\":0,\"reasoning_tokens\":0}}" } },
+ { "key": "dsh.turn.number", "value": { "intValue": "2" } },
+ { "key": "dsh.step.number", "value": { "intValue": "1" } },
+ { "key": "dsh.request.number", "value": { "intValue": "1" } }
+ ],
+ "status": { "code": 1 }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/output-replay-shape-records.json b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/output-replay-shape-records.json
new file mode 100644
index 0000000000..0ae4d9a4ff
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/output-replay-shape-records.json
@@ -0,0 +1,73 @@
+[
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "spanId": "1000000000000001", "name": "llm.call",
+ "startTimeUnixNano": "10000000000", "endTimeUnixNano": "11000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "shape-session" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Question\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"reasoning\",\"content\":\"Private reasoning\"},{\"type\":\"text\",\"content\":\"Reasoned answer\"},{\"type\":\"tool_call\",\"id\":\"call-trimmed\",\"name\":\"lookup\",\"arguments\":{\"q\":\"one\"}}]}]" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }
+ ], "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "spanId": "2000000000000002", "name": "llm.call",
+ "startTimeUnixNano": "12000000000", "endTimeUnixNano": "13000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "shape-session" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Question\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Reasoned answer\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"reasoning\",\"content\":\"Tool reasoning\"},{\"type\":\"text\",\"content\":\"Tool answer\"},{\"type\":\"tool_call\",\"id\":\"call-shape\",\"name\":\"lookup\",\"arguments\":\"{\\\"limit\\\":2,\\\"q\\\":\\\"two\\\"}\"}]}]" } },
+ { "key": "gen_ai.tool_calls", "value": { "stringValue": "[{\"id\":\"call-shape\",\"name\":\"lookup\",\"arguments\":{\"q\":\"two\",\"limit\":2}}]" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "2" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }
+ ], "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "spanId": "3000000000000003", "name": "llm.call",
+ "startTimeUnixNano": "14000000000", "endTimeUnixNano": "15000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "shape-session" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Question\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Reasoned answer\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"reasoning\",\"content\":\"Tool reasoning\"},{\"type\":\"text\",\"content\":\"Tool answer\"},{\"type\":\"tool_call\",\"id\":\"call-shape\",\"arguments\":\"\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Gap output\"}]}]" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "3" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }
+ ], "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "spanId": "4000000000000004", "name": "llm.call",
+ "startTimeUnixNano": "16000000000", "endTimeUnixNano": "17000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "shape-session" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Question\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Reasoned answer\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"reasoning\",\"content\":\"Tool reasoning\"},{\"type\":\"text\",\"content\":\"Tool answer\"},{\"type\":\"tool_call\",\"id\":\"call-shape\",\"arguments\":\"\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Another output\"}]}]" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "4" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }
+ ], "status": { "code": 1 }
+ }] }] }]
+ },
+ {
+ "resourceSpans": [{ "scopeSpans": [{ "spans": [{
+ "traceId": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "spanId": "5000000000000005", "name": "llm.call",
+ "startTimeUnixNano": "18000000000", "endTimeUnixNano": "19000000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "shape-session" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"Question\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Reasoned answer\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"reasoning\",\"content\":\"Tool reasoning\"},{\"type\":\"text\",\"content\":\"Tool answer\"},{\"type\":\"tool_call\",\"id\":\"call-shape\",\"arguments\":\"\"}]},{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Reasoned answer\"}]}]" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"End output\"}]}]" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "5" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }
+ ], "status": { "code": 1 }
+ }] }] }]
+ }
+]
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/standard-records.json b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/standard-records.json
new file mode 100644
index 0000000000..0fd3bb34e3
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/fixtures/standard-records.json
@@ -0,0 +1,106 @@
+[
+ {
+ "resourceSpans": [
+ {
+ "resource": {
+ "attributes": [
+ { "key": "service.name", "value": { "stringValue": "jiuwenswarm" } }
+ ]
+ },
+ "scopeSpans": [
+ {
+ "scope": { "name": "openjiuwen.observability", "version": "1" },
+ "spans": [
+ {
+ "traceId": "11111111111111111111111111111111",
+ "spanId": "1111111111111111",
+ "name": "chat",
+ "kind": 3,
+ "startTimeUnixNano": "1000000000",
+ "endTimeUnixNano": "2000000000",
+ "attributes": [
+ { "key": "gen_ai.conversation.id", "value": { "stringValue": "session-standard" } },
+ { "key": "session.id", "value": { "stringValue": "session-legacy-conflict" } },
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "chat" } },
+ { "key": "gen_ai.provider.name", "value": { "stringValue": "fixture-provider" } },
+ { "key": "gen_ai.request.model", "value": { "stringValue": "fixture-model" } },
+ { "key": "gen_ai.system_instructions", "value": { "stringValue": "[{\"type\":\"text\",\"content\":\"standard system\"}]" } },
+ { "key": "gen_ai.input.messages", "value": { "stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"standard user\"}]}]" } },
+ { "key": "gen_ai.prompt.0.role", "value": { "stringValue": "user" } },
+ { "key": "gen_ai.prompt.0.content", "value": { "stringValue": "legacy input conflict" } },
+ { "key": "gen_ai.output.messages", "value": { "stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"reasoning\",\"content\":\"standard reasoning\"},{\"type\":\"text\",\"content\":\"standard answer\"},{\"type\":\"tool_call\",\"id\":\"call-standard\",\"name\":\"lookup\",\"arguments\":{\"query\":\"x\"}}]}]" } },
+ { "key": "gen_ai.completion.0.role", "value": { "stringValue": "assistant" } },
+ { "key": "gen_ai.completion.0.content", "value": { "stringValue": "legacy output conflict" } },
+ { "key": "gen_ai.response.finish_reasons", "value": { "arrayValue": { "values": [{ "stringValue": "stop" }] } } },
+ { "key": "gen_ai.response.time_to_first_chunk", "value": { "doubleValue": 0 } },
+ { "key": "gen_ai.response.time_to_first_token_ms", "value": { "doubleValue": 900 } },
+ { "key": "gen_ai.usage.input_tokens", "value": { "intValue": "0" } },
+ { "key": "gen_ai.usage.prompt_tokens", "value": { "intValue": "99" } },
+ { "key": "gen_ai.usage.output_tokens", "value": { "intValue": "5" } },
+ { "key": "gen_ai.usage.reasoning.output_tokens", "value": { "intValue": "2" } },
+ { "key": "gen_ai.usage.cache_read.input_tokens", "value": { "intValue": "0" } },
+ { "key": "dsh.session.source_sequence", "value": { "intValue": "0" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },
+ { "key": "dsh.turn.number", "value": { "intValue": "9" } },
+ { "key": "openjiuwen.step.number", "value": { "intValue": "1" } },
+ { "key": "dsh.step.number", "value": { "intValue": "9" } },
+ { "key": "openjiuwen.request.number", "value": { "intValue": "1" } },
+ { "key": "dsh.request.retry_count", "value": { "intValue": "0" } },
+ { "key": "dsh.request.max_retries", "value": { "intValue": "0" } },
+ { "key": "openjiuwen.request.purpose", "value": { "stringValue": "assistant" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "inference" } }
+ ],
+ "events": [
+ {
+ "timeUnixNano": "1500000000",
+ "name": "openjiuwen.stream.chunk",
+ "attributes": [
+ { "key": "openjiuwen.event.sequence", "value": { "intValue": "0" } },
+ { "key": "openjiuwen.stream.kind", "value": { "stringValue": "text-delta" } },
+ { "key": "openjiuwen.stream.text", "value": { "stringValue": "standard answer" } }
+ ]
+ }
+ ],
+ "status": { "code": 1 }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "resourceSpans": [
+ {
+ "scopeSpans": [
+ {
+ "spans": [
+ {
+ "traceId": "11111111111111111111111111111111",
+ "spanId": "2222222222222222",
+ "parentSpanId": "1111111111111111",
+ "name": "tool.lookup",
+ "startTimeUnixNano": "2100000000",
+ "endTimeUnixNano": "2300000000",
+ "attributes": [
+ { "key": "gen_ai.operation.name", "value": { "stringValue": "execute_tool" } },
+ { "key": "gen_ai.tool.name", "value": { "stringValue": "lookup" } },
+ { "key": "gen_ai.tool.call.id", "value": { "stringValue": "call-standard" } },
+ { "key": "gen_ai.tool.id", "value": { "stringValue": "call-legacy-conflict" } },
+ { "key": "gen_ai.tool.call.arguments", "value": { "stringValue": "{\"query\":\"x\"}" } },
+ { "key": "gen_ai.tool.input", "value": { "stringValue": "{\"query\":\"legacy-conflict\"}" } },
+ { "key": "gen_ai.tool.call.result", "value": { "stringValue": "{\"result\":\"y\"}" } },
+ { "key": "gen_ai.tool.output", "value": { "stringValue": "{\"result\":\"legacy-conflict\"}" } },
+ { "key": "openjiuwen.turn.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.step.number", "value": { "intValue": "1" } },
+ { "key": "openjiuwen.trajectory.record.kind", "value": { "stringValue": "tool" } }
+ ],
+ "status": { "code": 1 }
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+]
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/index.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/index.ts
new file mode 100644
index 0000000000..0347b32a37
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/index.ts
@@ -0,0 +1,60 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Reusable trajectory UI and OTLP projection surface. */
+
+import './client/theme.css'
+
+export { TrajectoryExplorer } from './client/TrajectoryExplorer.tsx'
+export type { TrajectoryExplorerProps } from './client/TrajectoryExplorer.tsx'
+export { TrajectoryTable } from './client/TrajectoryTable.tsx'
+export type { TrajectoryTableProps } from './client/TrajectoryTable.tsx'
+export { TrajectoryTimeline } from './client/TrajectoryTimeline.tsx'
+export type { TrajectoryTimelineProps } from './client/TrajectoryTimeline.tsx'
+export { TrajectoryToolbar } from './client/TrajectoryToolbar.tsx'
+export type { TrajectoryToolbarProps } from './client/TrajectoryToolbar.tsx'
+export {
+ OtelGenAiTrajectoryProjector,
+ projectOtelTrajectory,
+} from './projector/otel-trajectory-projector.ts'
+export type { TrajectoryProjector } from './projector/otel-trajectory-projector.ts'
+export {
+ normalizeTrajectoryAttributes,
+ normalizeTrajectoryStreamEvents,
+} from './projector/attribute-resolver.ts'
+export type {
+ NormalizedTrajectoryAttributes,
+ NormalizedTrajectoryStreamEvent,
+} from './projector/attribute-resolver.ts'
+export type {
+ OtlpAnyValue,
+ OtlpExportTraceServiceRequest,
+ OtlpInstrumentationScope,
+ OtlpKeyValue,
+ OtlpResource,
+ OtlpResourceSpans,
+ OtlpScopeSpans,
+ OtlpSpan,
+ OtlpSpanEvent,
+ OtlpSpanLink,
+ OtlpStatus,
+} from './shared/otlp.ts'
+export type {
+ TrajectoryGroupModel,
+ TrajectoryPromptSnapshot,
+ TrajectoryRecordedFacts,
+ TrajectoryRequest,
+ TrajectoryRequestConfig,
+ TrajectorySnapshot,
+ TrajectoryToolSchema,
+ TrajectoryTurnModel,
+ TrajectoryUsage,
+} from './trajectory/model.ts'
+export type {
+ AssistantMetricDetail,
+ TrajectoryCell,
+ TrajectoryCellKind,
+ TrajectorySourceBlock,
+} from './trajectory/record.ts'
+export type { TrajectoryColorMode } from './theme/context.tsx'
+export { TrajectoryPanel } from './TrajectoryPanel.tsx'
+export type { TrajectoryPanelProps } from './TrajectoryPanel.tsx'
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/JsonTree.module.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/JsonTree.module.css
new file mode 100644
index 0000000000..edf607b3cd
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/JsonTree.module.css
@@ -0,0 +1,206 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+.root {
+ min-width: 0;
+ overflow: auto;
+ position: relative;
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-bg-layer-1);
+ font: 12px/16px var(--ds-font-family-code);
+ overscroll-behavior-x: contain;
+ overscroll-behavior-y: auto;
+}
+
+.container {
+ box-sizing: border-box;
+ width: max-content;
+ min-width: 100%;
+ margin: 0;
+ padding: 6px 8px 8px;
+ white-space: pre;
+}
+
+.expandedTopLevel {
+ box-sizing: border-box;
+ width: max-content;
+ min-width: 100%;
+ padding: 6px 8px 8px 14px;
+}
+
+.expandedTopLevel:has(> .topLevelBracket[data-json-root-row]:hover),
+.expandedTopLevel:has(> .topLevelBracket[data-json-root-row][data-json-copy-active]) {
+ background: var(--json-tree-hover);
+}
+
+.expandedTopLevelContainer {
+ padding: 0;
+}
+
+.row.topLevelBracket {
+ margin-left: 0;
+ padding-left: 0;
+}
+
+.children {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.row {
+ position: relative;
+ box-sizing: border-box;
+ min-width: 100%;
+ min-height: 16px;
+ margin: 0;
+ padding: 0 0 0 10px;
+ list-style: none;
+}
+
+.row:not(.topLevelBracket):hover:not(:has(.row:hover))::after,
+.row:not(.topLevelBracket)[data-json-copy-active]::after,
+.row:has(> .expander:focus-visible)::after {
+ position: absolute;
+ z-index: 0;
+ top: 0;
+ right: 0;
+ left: 0;
+ height: 16px;
+ background: var(--json-tree-hover);
+ content: '';
+ pointer-events: none;
+}
+
+.row > span:not(.expander) {
+ position: relative;
+ z-index: 1;
+}
+
+.label {
+ margin-right: 3px;
+ color: var(--json-tree-property);
+ font-weight: 400;
+}
+
+.clickableLabel {
+ cursor: pointer;
+}
+
+.stringValue {
+ color: var(--json-tree-string);
+}
+
+.numberValue {
+ color: var(--json-tree-number);
+}
+
+.keywordValue {
+ color: var(--json-tree-keyword);
+}
+
+.otherValue {
+ color: var(--dsw-alias-label-secondary);
+}
+
+.punctuation {
+ color: var(--json-tree-punctuation);
+}
+
+.preview {
+ color: var(--json-tree-punctuation);
+}
+
+.previewProperty {
+ color: var(--json-tree-punctuation);
+}
+
+.previewEllipsis {
+ color: var(--dsw-alias-label-tertiary);
+}
+
+.copyAnchor {
+ position: fixed;
+ z-index: 3;
+ display: inline-flex;
+}
+
+.copyButton {
+ box-sizing: border-box;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 16px;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ border-radius: 3px;
+ color: var(--dsw-alias-label-secondary);
+ background: var(--dsw-alias-bg-layer-1);
+ box-shadow: -5px 0 5px var(--dsw-alias-bg-layer-1);
+ cursor: pointer;
+}
+
+.copyButton:hover {
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.copyButton:focus-visible {
+ outline: 1px solid var(--dsw-alias-state-business-primary);
+ outline-offset: -1px;
+}
+
+.copyButton[data-state='failed'] {
+ color: var(--dsw-alias-state-error-primary);
+}
+
+.expander {
+ position: absolute;
+ z-index: 2;
+ top: 0;
+ left: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: flex-start;
+ box-sizing: border-box;
+ width: 8px;
+ height: 16px;
+ margin: 0;
+ color: var(--json-tree-icon);
+ cursor: pointer;
+ user-select: none;
+}
+
+.expander::before {
+ width: 0;
+ height: 0;
+ border-top: 4px solid transparent;
+ border-bottom: 4px solid transparent;
+ border-left: 6px solid currentColor;
+ content: '';
+ transform: scale(0.75);
+ transform-origin: 33.333% center;
+}
+
+.collapseIcon::before {
+ transform: rotate(90deg) scale(0.75);
+}
+
+.expander:hover {
+ color: var(--dsw-alias-label-primary);
+}
+
+.expander:focus-visible {
+ outline: none;
+}
+
+.collapsedContent {
+ margin: 0 1px;
+ color: var(--json-tree-punctuation);
+ cursor: pointer;
+}
+
+.collapsedContent::after {
+ content: '…';
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/JsonTree.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/JsonTree.tsx
new file mode 100644
index 0000000000..9f34f5f991
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/JsonTree.tsx
@@ -0,0 +1,664 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+import clsx from 'clsx'
+import { useEffect, useId, useMemo, useRef, useState } from 'react'
+import type {
+ KeyboardEvent as ReactKeyboardEvent,
+ MouseEvent as ReactMouseEvent,
+ ReactNode,
+ UIEvent as ReactUIEvent,
+} from 'react'
+import { IconCheckOutline16, IconCopyOutline16 } from './icons/index.tsx'
+import { Menu } from './Menu.tsx'
+import type { MenuEntry } from './Menu.tsx'
+import css from './JsonTree.module.css'
+
+const OBJECT_PREVIEW_LIMIT = 4
+const ARRAY_PREVIEW_LIMIT = 5
+const PREVIEW_DEPTH_LIMIT = 2
+
+/**
+ * Display copy for the tree's copy affordance; the owner passes localized
+ * labels (this package is cordis-free, so copy arrives via props). Every
+ * field defaults to the current built-in value, so existing consumers render
+ * unchanged.
+ */
+export interface JsonTreeLabels {
+ /** Menu item: copy the raw primitive value. */
+ copyValue: string
+ /** Menu item: copy the value as compact JSON (primitive rows). */
+ copyJson: string
+ /** Menu item: copy the property path. */
+ copyPath: string
+ /** Menu item: copy the value as pretty-printed JSON. */
+ copyPrettyJson: string
+ /** Menu item: copy the value as compact JSON (object rows). */
+ copyCompactJson: string
+ /** Copy-button state label after a successful copy. */
+ copied: string
+ /** Copy-button state label after a failed copy. */
+ copyFailed: string
+ /** Expander aria label while expanded. */
+ collapseNode: string
+ /** Expander aria label while collapsed. */
+ expandNode: string
+ /** Copy-button tooltip, given the current action label. */
+ copyButtonTitle: (action: string) => string
+}
+
+const DEFAULT_LABELS: JsonTreeLabels = {
+ copyValue: 'Copy value',
+ copyJson: 'Copy JSON',
+ copyPath: 'Copy property path',
+ copyPrettyJson: 'Copy pretty JSON',
+ copyCompactJson: 'Copy compact JSON',
+ copied: 'Copied',
+ copyFailed: 'Copy failed',
+ collapseNode: 'Collapse JSON node',
+ expandNode: 'Expand JSON node',
+ copyButtonTitle: action => `${action}; right-click for copy options`,
+}
+
+function valueCopyMenuItems(labels: JsonTreeLabels): readonly MenuEntry[] {
+ return [
+ { id: 'value', label: labels.copyValue },
+ { id: 'json', label: labels.copyJson },
+ { id: 'path', label: labels.copyPath },
+ ]
+}
+
+function objectCopyMenuItems(labels: JsonTreeLabels): readonly MenuEntry[] {
+ return [
+ { id: 'prettyJson', label: labels.copyPrettyJson },
+ { id: 'json', label: labels.copyCompactJson },
+ { id: 'path', label: labels.copyPath },
+ ]
+}
+
+type JsonPath = readonly (number | string)[]
+
+interface RowTarget {
+ path: JsonPath
+ value: unknown
+}
+
+interface CopyTarget extends RowTarget {
+ left: number
+ side: 'bottom' | 'top'
+ top: number
+}
+
+function isExpandableValue(value: unknown): value is object | unknown[] {
+ return typeof value === 'object' && value !== null && !(value instanceof Date)
+}
+
+function entriesOf(value: object | unknown[]): readonly (readonly [string, unknown])[] {
+ if (Array.isArray(value)) {
+ return value.map((item, index) => [String(index), item] as const)
+ }
+ return Object.keys(value).map(key => [
+ key,
+ (value as Record<string, unknown>)[key],
+ ] as const)
+}
+
+function bracketOf(value: object | unknown[]): readonly [string, string] {
+ return Array.isArray(value) ? ['[', ']'] : ['{', '}']
+}
+
+function previewPrimitive(value: unknown): ReactNode {
+ if (value === null) return <span className={css.keywordValue}>null</span>
+ if (typeof value === 'string') {
+ return <span className={css.stringValue}>{JSON.stringify(value)}</span>
+ }
+ if (typeof value === 'number') {
+ return <span className={css.numberValue}>{String(value)}</span>
+ }
+ if (typeof value === 'boolean') {
+ return <span className={css.keywordValue}>{String(value)}</span>
+ }
+ if (typeof value === 'bigint') {
+ return <span className={css.otherValue}>{value.toString()}</span>
+ }
+ if (typeof value === 'undefined') {
+ return <span className={css.otherValue}>undefined</span>
+ }
+ if (typeof value === 'symbol') {
+ return <span className={css.otherValue}>{value.description ?? 'Symbol'}</span>
+ }
+ if (typeof value === 'function') {
+ return <span className={css.otherValue}>{value.name || 'Function'}</span>
+ }
+ return null
+}
+
+function previewValue(value: unknown, depth: number): ReactNode {
+ if (!isExpandableValue(value)) return previewPrimitive(value)
+
+ const array = Array.isArray(value)
+ const entries = entriesOf(value)
+ const limit = array ? ARRAY_PREVIEW_LIMIT : OBJECT_PREVIEW_LIMIT
+ const visible = entries.slice(0, limit)
+ const [open, close] = bracketOf(value)
+
+ return (
+ <>
+ <span className={css.punctuation}>{open}</span>
+ {depth >= PREVIEW_DEPTH_LIMIT
+ ? <span className={css.previewEllipsis}>…</span>
+ : visible.map(([key, item], index) => (
+ <span key={key}>
+ {index > 0 && <span className={css.punctuation}>, </span>}
+ {!array && (
+ <>
+ <span className={css.previewProperty}>{key}</span>
+ <span className={css.punctuation}>: </span>
+ </>
+ )}
+ {previewValue(item, depth + 1)}
+ </span>
+ ))}
+ {depth < PREVIEW_DEPTH_LIMIT && entries.length > limit && (
+ <span className={css.previewEllipsis}>, …</span>
+ )}
+ <span className={css.punctuation}>{close}</span>
+ </>
+ )
+}
+
+function primitiveValue(value: unknown): ReactNode {
+ if (value === null) return <span className={css.keywordValue}>null</span>
+ if (typeof value === 'string') {
+ return <span className={css.stringValue}>{JSON.stringify(value)}</span>
+ }
+ if (typeof value === 'boolean') {
+ return <span className={css.keywordValue}>{String(value)}</span>
+ }
+ if (typeof value === 'number') {
+ return <span className={css.numberValue}>{String(value)}</span>
+ }
+ if (typeof value === 'bigint') {
+ return <span className={css.numberValue}>{`${value.toString()}n`}</span>
+ }
+ if (value instanceof Date) {
+ return <span className={css.otherValue}>{value.toISOString()}</span>
+ }
+ if (typeof value === 'function') {
+ return <span className={css.otherValue}>function() {'{ }'}</span>
+ }
+ if (typeof value === 'undefined') {
+ return <span className={css.otherValue}>undefined</span>
+ }
+ return <span className={css.otherValue}>{(value as symbol).toString()}</span>
+}
+
+function fieldText(field: string): string {
+ return field === '' ? '""' : field
+}
+
+function pathId(path: JsonPath): string {
+ return path.map(part => (
+ typeof part === 'number' ? `n${String(part)}` : `s${String(part.length)}:${part}`
+ )).join('/')
+}
+
+function claimFocus(button: HTMLElement): void {
+ button.focus()
+}
+
+function moveFocus(button: HTMLElement, direction: -1 | 1): void {
+ const tree = button.closest<HTMLElement>('[role="tree"]')
+ /* v8 ignore next -- JsonTree attaches expander handlers only beneath its owning role=tree. */
+ if (tree === null) return
+ const expanders = Array.from(tree.querySelectorAll<HTMLElement>('[data-json-expander]'))
+ const current = expanders.indexOf(button)
+ /* v8 ignore next -- the current expander is a member of the queried non-empty set. */
+ if (current < 0 || expanders.length === 0) return
+ const next = (current + direction + expanders.length) % expanders.length
+ const nextExpander = expanders[next]
+ /* v8 ignore next -- modulo over the non-empty expander set always resolves a member. */
+ if (nextExpander !== undefined) claimFocus(nextExpander)
+}
+
+function NodeField({
+ field,
+ expandable,
+ onToggle,
+}: {
+ field: string | undefined
+ expandable: boolean
+ onToggle: () => void
+}) {
+ if (field === undefined) return null
+ return (
+ <span
+ className={clsx(css.label, expandable && css.clickableLabel)}
+ onClick={expandable ? onToggle : undefined}
+ >
+ {fieldText(field)}:
+ </span>
+ )
+}
+
+interface JsonTreeNodeProps {
+ field?: string
+ initialExpanded: boolean
+ labels: JsonTreeLabels
+ lastElement: boolean
+ onClaimTabStop: (id: string) => void
+ onRowHover: (row: HTMLElement, target: RowTarget) => void
+ path: JsonPath
+ tabStopId: string | null
+ value: unknown
+}
+
+function JsonTreeNode({
+ field,
+ initialExpanded,
+ labels,
+ lastElement,
+ onClaimTabStop,
+ onRowHover,
+ path,
+ tabStopId,
+ value,
+}: JsonTreeNodeProps) {
+ const contentsId = useId()
+ const expanderRef = useRef<HTMLSpanElement>(null)
+ const [expanded, setExpanded] = useState(initialExpanded)
+ const nodeId = pathId(path)
+ const container = isExpandableValue(value)
+ const entries = container ? entriesOf(value) : []
+ const expandable = entries.length > 0
+
+ const toggle = () => {
+ setExpanded(current => !current)
+ claimFocus(expanderRef.current as HTMLSpanElement)
+ }
+
+ const onExpanderKeyDown = (event: ReactKeyboardEvent<HTMLSpanElement>) => {
+ if (event.key === 'ArrowRight' || event.key === 'ArrowLeft') {
+ event.preventDefault()
+ setExpanded(event.key === 'ArrowRight')
+ return
+ }
+ if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
+ event.preventDefault()
+ moveFocus(event.currentTarget, event.key === 'ArrowUp' ? -1 : 1)
+ }
+ }
+
+ const row = (children: ReactNode, ariaExpanded?: boolean) => (
+ <div
+ className={css.row}
+ role="treeitem"
+ aria-expanded={ariaExpanded}
+ onMouseOver={(event) => {
+ event.stopPropagation()
+ onRowHover(event.currentTarget, { path, value })
+ }}
+ >
+ {children}
+ </div>
+ )
+
+ if (!container) {
+ return row((
+ <>
+ <NodeField field={field} expandable={false} onToggle={toggle} />
+ {primitiveValue(value)}
+ {!lastElement && <span className={css.punctuation}>,</span>}
+ </>
+ ))
+ }
+
+ const [open, close] = bracketOf(value)
+ if (!expandable) {
+ return row((
+ <>
+ <NodeField field={field} expandable={false} onToggle={toggle} />
+ <span className={css.punctuation}>{open}</span>
+ <span className={css.punctuation}>{close}</span>
+ {!lastElement && <span className={css.punctuation}>,</span>}
+ </>
+ ))
+ }
+
+ return row((
+ <>
+ <span
+ ref={expanderRef}
+ className={clsx(css.expander, expanded ? css.collapseIcon : css.expandIcon)}
+ data-json-expander
+ role="button"
+ aria-label={expanded ? labels.collapseNode : labels.expandNode}
+ aria-expanded={expanded}
+ aria-controls={expanded ? contentsId : undefined}
+ tabIndex={tabStopId === nodeId ? 0 : -1}
+ onFocus={() => { onClaimTabStop(nodeId) }}
+ onClick={toggle}
+ onKeyDown={onExpanderKeyDown}
+ />
+ <NodeField field={field} expandable onToggle={toggle} />
+ <span className={css.preview}>{previewValue(value, 0)}</span>
+ {!lastElement && <span className={css.punctuation}>,</span>}
+ {expanded && (
+ <ul id={contentsId} role="group" className={css.children}>
+ {entries.map(([key, item], index) => (
+ <JsonTreeNode
+ key={key}
+ field={key}
+ value={item}
+ path={[...path, Array.isArray(value) ? index : key]}
+ labels={labels}
+ lastElement={index === entries.length - 1}
+ initialExpanded={false}
+ tabStopId={tabStopId}
+ onClaimTabStop={onClaimTabStop}
+ onRowHover={onRowHover}
+ />
+ ))}
+ </ul>
+ )}
+ </>
+ ), expanded)
+}
+
+function formattedPath(path: JsonPath): string {
+ return path.reduce<string>((result, part) => {
+ if (typeof part === 'number') return `${result}[${String(part)}]`
+ return /^[A-Za-z_$][\w$]*$/.test(part)
+ ? `${result}.${part}`
+ : `${result}[${JSON.stringify(part)}]`
+ }, '$')
+}
+
+function copyText(target: CopyTarget, mode: 'json' | 'path' | 'prettyJson' | 'value'): string {
+ if (mode === 'path') return formattedPath(target.path)
+ if (mode === 'prettyJson') return JSON.stringify(target.value, null, 2)
+ if (mode === 'json') return JSON.stringify(target.value)
+ if (typeof target.value === 'string') return target.value
+ if (typeof target.value === 'undefined') return 'undefined'
+ if (typeof target.value === 'bigint') return target.value.toString()
+ if (typeof target.value === 'symbol') return target.value.description ?? 'Symbol'
+ if (typeof target.value === 'function') return target.value.name || 'Function'
+ return JSON.stringify(target.value)
+}
+
+/** Props for the read-only, token-themed JSON tree. */
+export interface JsonTreeProps {
+ /** Parsed JSON object or array. */
+ data: object | unknown[]
+ /** Accessible label for the tree. */
+ label?: string
+ /** Optional positioning class owned by the caller. */
+ className?: string | undefined
+ /** Whether JSON rows expose copy actions. */
+ copyable?: boolean
+ /** Whether the top-level object or array is always expanded. */
+ expandTopLevel?: boolean
+ /** Localized display copy; omitted fields keep the built-in defaults. */
+ labels?: Partial<JsonTreeLabels> | undefined
+}
+
+/**
+ * Render parsed JSON as a compact, keyboard-accessible inspector tree.
+ * @param props - Parsed data, accessible label, and display options.
+ * @returns A read-only JSON tree with an optionally fixed-open top level.
+ */
+export function JsonTree({
+ data,
+ label = 'JSON',
+ className,
+ copyable = true,
+ expandTopLevel = true,
+ labels,
+}: JsonTreeProps) {
+ const copyLabels = useMemo<JsonTreeLabels>(
+ () => (labels === undefined ? DEFAULT_LABELS : { ...DEFAULT_LABELS, ...labels }),
+ [labels],
+ )
+ const rootEntries = entriesOf(data)
+ const firstExpandableIndex = rootEntries.findIndex(([, value]) => (
+ isExpandableValue(value) && entriesOf(value).length > 0
+ ))
+ const firstExpandableEntry = rootEntries[firstExpandableIndex]
+ const initialTabStopId = expandTopLevel
+ ? firstExpandableEntry === undefined
+ ? null
+ : pathId([Array.isArray(data) ? firstExpandableIndex : firstExpandableEntry[0]])
+ : isExpandableValue(data) && rootEntries.length > 0 ? pathId([]) : null
+ const rootRef = useRef<HTMLDivElement>(null)
+ const activeRowRef = useRef<HTMLElement>()
+ const copyButtonRef = useRef<HTMLButtonElement>(null)
+ const copyMenuOpenRef = useRef(false)
+ const resetTimer = useRef<ReturnType<typeof setTimeout>>()
+ const [copyTarget, setCopyTarget] = useState<CopyTarget>()
+ const [copyState, setCopyState] = useState<'idle' | 'copied' | 'failed'>('idle')
+ const [copyMenuOpen, setCopyMenuOpen] = useState(false)
+ const [tabStopId, setTabStopId] = useState<string | null>(initialTabStopId)
+
+ const setActiveRow = (row: HTMLElement | undefined) => {
+ activeRowRef.current?.removeAttribute('data-json-copy-active')
+ activeRowRef.current = row
+ row?.setAttribute('data-json-copy-active', '')
+ }
+
+ const clearCopyTarget = () => {
+ setActiveRow(undefined)
+ setCopyTarget(undefined)
+ setCopyState('idle')
+ copyMenuOpenRef.current = false
+ setCopyMenuOpen(false)
+ }
+
+ const copyPosition = (row: HTMLElement): Pick<CopyTarget, 'left' | 'side' | 'top'> => {
+ const root = rootRef.current
+ /* v8 ignore next -- row events and viewport listeners run only after the root ref mounts. */
+ if (root === null) throw new Error('JsonTree root is not mounted')
+ const rootRect = root.getBoundingClientRect()
+ const rowRect = row.getBoundingClientRect()
+ return {
+ left: rootRect.left + root.clientWidth - 26,
+ side: rowRect.top - rootRect.top > root.clientHeight / 2 ? 'top' : 'bottom',
+ top: rowRect.top,
+ }
+ }
+
+ const positionCopyButton = (row: HTMLElement, target: RowTarget) => {
+ const position = copyPosition(row)
+ setCopyTarget({ ...target, ...position })
+ }
+
+ const repositionCopyButton = (row: HTMLElement) => {
+ const position = copyPosition(row)
+ setCopyTarget((current) => {
+ /* v8 ignore next -- an active row and its copy target are installed together. */
+ if (current === undefined) return current
+ return { ...current, ...position }
+ })
+ }
+
+ useEffect(() => () => {
+ if (resetTimer.current !== undefined) clearTimeout(resetTimer.current)
+ activeRowRef.current?.removeAttribute('data-json-copy-active')
+ }, [])
+
+ useEffect(() => {
+ activeRowRef.current?.removeAttribute('data-json-copy-active')
+ activeRowRef.current = undefined
+ copyMenuOpenRef.current = false
+ setCopyTarget(undefined)
+ setCopyState('idle')
+ setCopyMenuOpen(false)
+ setTabStopId(initialTabStopId)
+ }, [data, expandTopLevel, initialTabStopId])
+
+ useEffect(() => {
+ const reposition = () => {
+ const row = activeRowRef.current
+ if (row !== undefined) repositionCopyButton(row)
+ }
+ window.addEventListener('scroll', reposition, true)
+ window.addEventListener('resize', reposition)
+ return () => {
+ window.removeEventListener('scroll', reposition, true)
+ window.removeEventListener('resize', reposition)
+ }
+ }, [])
+
+ const handleRowHover = (row: HTMLElement, target: RowTarget) => {
+ if (!copyable || copyMenuOpenRef.current) return
+ if (activeRowRef.current === row) return
+ setActiveRow(row)
+ setCopyState('idle')
+ copyMenuOpenRef.current = false
+ setCopyMenuOpen(false)
+ positionCopyButton(row, target)
+ }
+
+ const handleRootMouseOver = (event: ReactMouseEvent<HTMLDivElement>) => {
+ if (!copyable || copyMenuOpenRef.current) return
+ /* v8 ignore next -- browser mouse events delivered through React target an Element. */
+ if (!(event.target instanceof Element)) return
+ if (event.target.closest('[data-json-copy-button]') === null) clearCopyTarget()
+ }
+
+ const handleScroll = (_event: ReactUIEvent<HTMLDivElement>) => {
+ const row = activeRowRef.current
+ if (row !== undefined) repositionCopyButton(row)
+ }
+
+ const copy = async (mode: 'json' | 'path' | 'prettyJson' | 'value') => {
+ /* v8 ignore next -- copy controls only render while their target exists. */
+ if (copyTarget === undefined) return
+ try {
+ await navigator.clipboard.writeText(copyText(copyTarget, mode))
+ setCopyState('copied')
+ } catch {
+ setCopyState('failed')
+ }
+ if (resetTimer.current !== undefined) clearTimeout(resetTimer.current)
+ resetTimer.current = setTimeout(() => { setCopyState('idle') }, 1_500)
+ }
+
+ const [rootOpen, rootClose] = bracketOf(data)
+ const copyTargetIsObject = typeof copyTarget?.value === 'object' && copyTarget.value !== null
+ const defaultCopyMode = copyTargetIsObject ? 'prettyJson' : 'value'
+ const copyTitle = copyState === 'copied'
+ ? copyLabels.copied
+ : copyState === 'failed'
+ ? copyLabels.copyFailed
+ : copyTargetIsObject ? copyLabels.copyPrettyJson : copyLabels.copyValue
+
+ return (
+ <div
+ ref={rootRef}
+ className={clsx(css.root, className)}
+ onMouseOver={handleRootMouseOver}
+ onMouseLeave={() => {
+ if (!copyMenuOpenRef.current) clearCopyTarget()
+ }}
+ onScroll={handleScroll}
+ >
+ {expandTopLevel
+ ? (
+ <div className={css.expandedTopLevel}>
+ <div
+ className={clsx(css.row, css.topLevelBracket)}
+ data-json-root-row
+ onMouseOver={(event) => {
+ event.stopPropagation()
+ handleRowHover(event.currentTarget, { path: [], value: data })
+ }}
+ >
+ <span className={css.punctuation}>{rootOpen}</span>
+ </div>
+ <div
+ aria-label={label}
+ className={clsx(css.container, css.expandedTopLevelContainer)}
+ role="tree"
+ >
+ {rootEntries.map(([key, value], index) => (
+ <JsonTreeNode
+ key={key}
+ field={key}
+ value={value}
+ path={[Array.isArray(data) ? index : key]}
+ labels={copyLabels}
+ lastElement={index === rootEntries.length - 1}
+ initialExpanded={false}
+ tabStopId={tabStopId}
+ onClaimTabStop={setTabStopId}
+ onRowHover={handleRowHover}
+ />
+ ))}
+ </div>
+ <div className={clsx(css.row, css.topLevelBracket)}>
+ <span className={css.punctuation}>{rootClose}</span>
+ </div>
+ </div>
+ )
+ : (
+ <div aria-label={label} className={css.container} role="tree">
+ <JsonTreeNode
+ value={data}
+ path={[]}
+ labels={copyLabels}
+ lastElement
+ initialExpanded
+ tabStopId={tabStopId}
+ onClaimTabStop={setTabStopId}
+ onRowHover={handleRowHover}
+ />
+ </div>
+ )}
+ {copyTarget !== undefined && (
+ <span
+ className={css.copyAnchor}
+ style={{ left: copyTarget.left, top: copyTarget.top }}
+ >
+ <Menu
+ open={copyMenuOpen}
+ compact
+ portal
+ align="end"
+ side={copyTarget.side}
+ anchor={(
+ <button
+ ref={copyButtonRef}
+ type="button"
+ className={css.copyButton}
+ data-json-copy-button
+ data-state={copyState}
+ aria-label={copyTitle}
+ title={copyLabels.copyButtonTitle(copyTitle)}
+ onClick={() => void copy(defaultCopyMode)}
+ onContextMenu={(event) => {
+ event.preventDefault()
+ event.stopPropagation()
+ copyMenuOpenRef.current = true
+ setCopyMenuOpen(true)
+ }}
+ >
+ {copyState === 'copied'
+ ? <IconCheckOutline16 size={12} />
+ : <IconCopyOutline16 size={12} />}
+ </button>
+ )}
+ items={copyTargetIsObject ? objectCopyMenuItems(copyLabels) : valueCopyMenuItems(copyLabels)}
+ onSelect={(id) => {
+ void copy(id as 'json' | 'path' | 'prettyJson' | 'value')
+ copyMenuOpenRef.current = false
+ setCopyMenuOpen(false)
+ }}
+ onClose={clearCopyTarget}
+ getAnchorRect={() => (
+ copyButtonRef.current as HTMLButtonElement
+ ).getBoundingClientRect()}
+ />
+ </span>
+ )}
+ </div>
+ )
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/Menu.module.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/Menu.module.css
new file mode 100644
index 0000000000..f135b31510
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/Menu.module.css
@@ -0,0 +1,244 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+.root {
+ position: relative;
+ display: inline-flex;
+}
+
+/* Dropdown card (figma MenuDropdown 122:9481 / 419:16920): menu surface,
+ * r12, inverted hairline border, shadow-lv3, 4px inset padding. */
+.list,
+.submenu {
+ /* min-widths below are the design's outer card widths — include the pad. */
+ box-sizing: border-box;
+ padding: 4px;
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ border: 1px solid var(--dsw-alias-border-inverted);
+ border-radius: 12px;
+ background: var(--dsw-specific-menu);
+ box-shadow: var(--dsw-shadow-lv3);
+ /* Elevated surface: the scrollbar thumb takes the l2 elevation tokens. The
+ declaration sits on the card rather than on `.scrollable .viewport`
+ because the elevation is a property of this surface, and the custom
+ properties inherit down to whichever descendant actually scrolls (see
+ ui-theme styles/scrollbar.css for the rebinding contract). */
+ --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2);
+ --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2);
+}
+
+/* Primary card is 218 wide in the design across both hosts. */
+.list {
+ position: absolute;
+ top: calc(100% + 4px);
+ left: 0;
+ z-index: 100;
+ min-width: 218px;
+ max-width: 360px;
+}
+
+/* Portal mode: fixed in the viewport, coordinates supplied inline from the
+ * anchor rect (side/align resolved in JS, the in-place offset rules above
+ * don't apply). Portaled lists must layer above modal overlays (z 1000) —
+ * an anchor inside a dialog still expects its menu on top. */
+.portal {
+ position: fixed;
+ top: auto;
+ left: auto;
+ z-index: 1100;
+}
+
+/* Open above the anchor (empty-state workspace chip: figma 122:9481). */
+.sideTop {
+ top: auto;
+ bottom: calc(100% + 4px);
+}
+
+.alignEnd {
+ left: auto;
+ right: 0;
+}
+
+/* Viewport fit: the card stops 12px short of the viewport's top/bottom edges
+ * (24 = 2 × the portal MARGIN in Menu.tsx) and taller content scrolls inside
+ * .viewport, so a pinned .footer stays visible. Menus with submenu rows skip
+ * this class — the overflow clip would crop the side card, so they rely on
+ * staying short. */
+.scrollable {
+ max-height: calc(100vh - 24px);
+}
+
+.viewport {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+
+.scrollable .viewport {
+ overflow-y: auto;
+}
+
+/* Pinned rows below the scroll region; l2 hairline (l1 is near-invisible on
+ * the menu surface) mirrors the .separator spacing. */
+.footer {
+ flex: none;
+ display: flex;
+ flex-direction: column;
+ margin-top: 4px;
+ padding-top: 4px;
+ border-top: 1px solid var(--dsw-alias-border-l2);
+}
+
+.itemWrap {
+ position: relative;
+}
+
+/* Menu cell (figma .Menu_cell): min-h 40, r10, pad 10/8, 14/22 primary,
+ * gap 8 between leading icon / label / trailing check. */
+.item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ min-height: 40px;
+ padding: 8px 10px;
+ border: none;
+ border-radius: 10px;
+ background: transparent;
+ cursor: pointer;
+ font-size: 14px;
+ line-height: 22px;
+ color: var(--dsw-alias-label-primary);
+ text-align: left;
+}
+
+.item:hover:not(:disabled) {
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+.denseList .item {
+ min-height: 34px;
+ padding-block: 5px;
+}
+
+.denseList .label {
+ padding-block: 4px;
+}
+
+.list.compactList,
+.submenu.compactList {
+ min-width: 164px;
+ padding: 2px;
+ border-radius: 7px;
+}
+
+.compactList .item {
+ min-height: 26px;
+ gap: 6px;
+ padding: 3px 7px;
+ border-radius: 5px;
+ font-size: 12px;
+ line-height: 18px;
+}
+
+.compactList .itemIcon {
+ width: 14px;
+ height: 14px;
+}
+
+.compactList .separator {
+ margin: 2px;
+}
+
+.compactList .label {
+ padding: 4px 7px;
+ font-size: 11px;
+ line-height: 16px;
+}
+
+.item:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+
+.itemIcon {
+ display: inline-flex;
+ flex: none;
+ width: 16px;
+ height: 16px;
+ align-items: center;
+ justify-content: center;
+ color: var(--dsw-alias-label-tertiary);
+}
+
+.itemLabel {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.check {
+ flex: none;
+ color: var(--dsw-alias-label-primary);
+}
+
+/* Selected cell keeps the plain fill (marker is the trailing check); the
+ * class remains as a hook for owner-side emphasis. */
+.selected {
+ background: transparent;
+}
+
+/* Destructive row: error text/icon, danger hover fill. */
+.danger {
+ color: var(--dsw-alias-state-error-primary);
+}
+
+.danger .itemIcon {
+ color: var(--dsw-alias-state-error-primary);
+}
+
+.danger:hover:not(:disabled) {
+ background: var(--dsw-alias-interactive-bg-hover-danger);
+}
+
+/* Heading row: non-interactive small grey text, padding aligned with items. */
+.label {
+ padding: 8px 10px;
+ font-size: 12px;
+ line-height: 16px;
+ color: var(--dsw-alias-label-tertiary);
+}
+
+/* Separator cell (figma 122:9481): py 4 / px 2 around the hairline. */
+.separator {
+ height: 1px;
+ margin: 4px 2px;
+ background: var(--dsw-alias-border-l1);
+}
+
+/* Nested card to the right of the parent row (figma 419:16920).
+ * Bottom-aligned with the parent menu card (grows upward): itemWrap sits in
+ * .list's 4px pad, so bottom: -4px matches the list's outer bottom edge.
+ * Horizontal: list pad (4px) + 6px card gap = 10px past itemWrap — plain
+ * `100% + 6px` collapses to ~2px between outer card edges.
+ * ::before bridges the full gap so the pointer can cross without mouseLeave. */
+.submenu {
+ position: absolute;
+ top: auto;
+ bottom: -4px;
+ left: calc(100% + 10px);
+ z-index: 101;
+ min-width: 163px;
+}
+
+.submenu::before {
+ content: '';
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: -10px;
+ width: 10px;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/Menu.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/Menu.tsx
new file mode 100644
index 0000000000..c4962b5754
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/Menu.tsx
@@ -0,0 +1,307 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+// Menu: minimal controlled dropdown (group-by pickers, project selectors).
+// Default: pure CSS positioning relative to the anchor wrapper — no popper.
+// Opt-in `portal` renders the list into document.body, fixed-positioned from
+// the anchor rect, for anchors inside overflow-clipping containers (sidebar).
+// The owner controls `open`; outside-click closing uses one document listener
+// active only while open. Submenus open on hover/focus inside the same root.
+// Entries also cover non-interactive `label` headings and `danger` rows.
+// Lists keep 12px clearance to the viewport's top/bottom edges and scroll
+// internally past that; submenu-bearing menus are exempt (see .scrollable).
+
+import { useEffect, useLayoutEffect, useRef, useState } from 'react'
+import type { CSSProperties, ReactNode } from 'react'
+import { createPortal } from 'react-dom'
+import clsx from 'clsx'
+import { IconCheckOutline16 } from './icons/index.tsx'
+import { usePointerGrace } from './pointer-grace.ts'
+import { useTrajectoryColorMode } from '../theme/context.tsx'
+import css from './Menu.module.css'
+
+/** Selectable row (optionally with a nested submenu). */
+export interface MenuItem {
+ id: string
+ label: ReactNode
+ disabled?: boolean
+ /** Leading icon (figma .Menu_cell gap 8). */
+ icon?: ReactNode
+ /** Destructive row: error-colored text/icon and danger hover fill. */
+ danger?: boolean
+ /** Nested card opened to the right on hover/focus. */
+ submenu?: readonly MenuItem[]
+}
+
+/** Hairline between item groups (not selectable). */
+export interface MenuSeparator {
+ type: 'separator'
+ id: string
+}
+
+/** Non-interactive heading row above a group of items. */
+export interface MenuLabel {
+ type: 'label'
+ id: string
+ text: string
+}
+
+/** One primary-menu entry: a row, a separator, or a heading label. */
+export type MenuEntry = MenuItem | MenuSeparator | MenuLabel
+
+function isSeparator(entry: MenuEntry): entry is MenuSeparator {
+ return 'type' in entry && entry.type === 'separator'
+}
+
+function isLabel(entry: MenuEntry): entry is MenuLabel {
+ return 'type' in entry && entry.type === 'label'
+}
+
+/** Unplaced portal list: hidden but laid out at a fixed origin so offsetWidth/offsetHeight are real. */
+const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 }
+
+/**
+ * Render an anchored dropdown menu.
+ * @param props.open - whether the list is showing (owner-controlled).
+ * @param props.anchor - the trigger element (rendered in place).
+ * @param props.items - selectable rows and optional separators.
+ * @param props.selectedId - row shown as selected.
+ * @param props.selectedIds - rows shown as selected when a menu contains independent option groups.
+ * @param props.onSelect - row click callback (not called for disabled rows or submenu parents that only open children).
+ * @param props.onClose - invoked on outside click or Escape.
+ * @param props.align - list alignment against the anchor (default 'start').
+ * @param props.side - open below (`bottom`, default) or above (`top`) the anchor.
+ * @param props.portal - render the list into document.body, fixed-positioned
+ * from the anchor rect (repositions on scroll/resize while open). Use when an
+ * ancestor's overflow clipping would crop the in-place list; default false
+ * keeps the pure-CSS in-place behavior.
+ * @param props.closeOnPointerLeave - close the list once the pointer has left
+ * both trigger and list for the pointer grace (default false keeps it open
+ * until outside click/Escape/selection). The grace makes the 4px trigger->list
+ * gap and a brief overshoot survivable; coming back cancels the close.
+ * @param props.dense - reduce vertical row spacing without changing the standard typography or card width.
+ * @param props.compact - use reduced menu typography and spacing.
+ * @param props.getAnchorRect - portal mode only: supply the anchor rect
+ * directly (e.g. from a host-owned trigger button) instead of measuring the
+ * Menu's own wrapper span. Required when the wrapper isn't itself laid out at
+ * the trigger (render-prop anchors, effect-positioned proxies — measuring the
+ * wrapper there races the host's layout effects). Called on open and on every
+ * scroll/resize; return null to skip placement for that frame.
+ * @param props.footer - rows pinned below the scrolling items area, separated
+ * by a hairline; they stay visible while the items above scroll.
+ * @returns anchor wrapper with the conditional list.
+ */
+export function Menu({ open, anchor, items, selectedId, selectedIds, onSelect, onClose, align = 'start', side = 'bottom', portal = false, closeOnPointerLeave = false, dense = false, compact = false, getAnchorRect, footer, className }: {
+ open: boolean
+ anchor: ReactNode
+ items: readonly MenuEntry[]
+ footer?: readonly MenuEntry[]
+ selectedId?: string | undefined
+ selectedIds?: readonly string[] | undefined
+ onSelect: (id: string) => void
+ onClose: () => void
+ align?: 'start' | 'end'
+ side?: 'bottom' | 'top' | 'right'
+ portal?: boolean
+ closeOnPointerLeave?: boolean
+ dense?: boolean
+ compact?: boolean
+ getAnchorRect?: () => DOMRect | null
+ className?: string
+}) {
+ const rootRef = useRef<HTMLSpanElement>(null)
+ const listRef = useRef<HTMLDivElement>(null)
+ const [openSubmenuId, setOpenSubmenuId] = useState<string | null>(null)
+ const [fixedPos, setFixedPos] = useState<CSSProperties | null>(null)
+ const colorMode = useTrajectoryColorMode()
+ const { arm: armClose, cancel: cancelClose } = usePointerGrace(onClose)
+
+ // Portal mode: fixed-position the list from the anchor rect before paint;
+ // track the anchor while open (capture-phase scroll catches nested panes).
+ // getAnchorRect trumps measuring the wrapper span: a child layout effect
+ // runs before the parent's, so a wrapper the host positions in its own
+ // effect measures stale here — the host callback owns the truth instead.
+ useLayoutEffect(() => {
+ if (!open || !portal) { setFixedPos(null); return }
+ const place = () => {
+ let r: DOMRect | null
+ if (getAnchorRect !== undefined) {
+ r = getAnchorRect()
+ } else {
+ /* v8 ignore next 2 -- the ref is attached before the layout effect runs and the listeners die with it. */
+ r = rootRef.current?.getBoundingClientRect() ?? null
+ }
+ if (r === null) return
+ const MARGIN = 12
+ const vw = window.innerWidth
+ const vh = window.innerHeight
+ const listEl = listRef.current
+ const lw = listEl?.offsetWidth ?? 0
+ const lh = listEl?.offsetHeight ?? 0
+
+ let x: number
+ let y: number
+ if (side === 'right') {
+ x = r.right + 4
+ y = r.top
+ } else if (align === 'start') {
+ x = r.left
+ y = side === 'bottom' ? r.bottom + 4 : r.top - lh - 4
+ } else {
+ x = r.right - lw
+ y = side === 'bottom' ? r.bottom + 4 : r.top - lh - 4
+ }
+
+ if (lw > 0) x = Math.min(Math.max(x, MARGIN), vw - lw - MARGIN)
+ if (lh > 0) y = Math.min(Math.max(y, MARGIN), vh - lh - MARGIN)
+
+ setFixedPos({ left: x, top: y })
+ }
+ // First run measures the hidden pre-render (same commit as `open`), so
+ // end/top alignment and clamping use real dimensions before anything
+ // paints — no visible jump from a zero-size first guess.
+ place()
+ window.addEventListener('scroll', place, true)
+ window.addEventListener('resize', place)
+ return () => {
+ window.removeEventListener('scroll', place, true)
+ window.removeEventListener('resize', place)
+ }
+ }, [open, portal, align, side, getAnchorRect])
+
+ useEffect(() => {
+ if (!open) {
+ setOpenSubmenuId(null)
+ return
+ }
+ const onPointerDown = (e: PointerEvent) => {
+ if (!(e.target instanceof Node)) return
+ // The portaled list is outside the anchor subtree; check both.
+ if (rootRef.current?.contains(e.target) === true) return
+ if (listRef.current?.contains(e.target) === true) return
+ onClose()
+ }
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') onClose()
+ }
+ document.addEventListener('pointerdown', onPointerDown)
+ document.addEventListener('keydown', onKeyDown)
+ return () => {
+ document.removeEventListener('pointerdown', onPointerDown)
+ document.removeEventListener('keydown', onKeyDown)
+ }
+ }, [open, onClose])
+
+ // A close from selection/Escape/outside click outruns a pending grace close;
+ // left armed it would shut a list reopened inside the grace window. Its own
+ // effect, not the listener effect above: that one re-runs on every `onClose`
+ // identity change and would cancel the grace mid-transit.
+ useEffect(() => {
+ if (!open) cancelClose()
+ }, [open, cancelClose])
+
+ // The submenu card is absolutely positioned outside the list box; the
+ // scroll clip would crop it, so only submenu-free menus get the height cap.
+ const scrollable = !items.some(entry => !isSeparator(entry) && !isLabel(entry) && entry.submenu !== undefined && entry.submenu.length > 0)
+
+ const renderEntry = (entry: MenuEntry) => {
+ if (isSeparator(entry)) {
+ return <div key={entry.id} className={css.separator} role="separator" />
+ }
+ if (isLabel(entry)) {
+ return <div key={entry.id} className={css.label} role="presentation">{entry.text}</div>
+ }
+ const hasSub = entry.submenu !== undefined && entry.submenu.length > 0
+ const subOpen = hasSub && openSubmenuId === entry.id
+ const selected = entry.id === selectedId || selectedIds?.includes(entry.id) === true
+ return (
+ <div
+ key={entry.id}
+ className={css.itemWrap}
+ onMouseEnter={() => { setOpenSubmenuId(hasSub ? entry.id : null) }}
+ onMouseLeave={() => { setOpenSubmenuId(null) }}
+ >
+ <button
+ type="button"
+ role="menuitem"
+ className={clsx(css.item, selected && css.selected, entry.danger === true && css.danger)}
+ disabled={entry.disabled}
+ aria-haspopup={hasSub ? 'menu' : undefined}
+ aria-expanded={hasSub ? subOpen : undefined}
+ onFocus={() => { setOpenSubmenuId(hasSub ? entry.id : null) }}
+ onClick={() => {
+ if (hasSub) {
+ setOpenSubmenuId(entry.id)
+ return
+ }
+ onSelect(entry.id)
+ }}
+ >
+ {entry.icon !== undefined && <span className={css.itemIcon}>{entry.icon}</span>}
+ <span className={css.itemLabel}>{entry.label}</span>
+ {/* Selection marker is a trailing check (figma .Menu_cell), not a fill. */}
+ {selected && <IconCheckOutline16 className={css.check} />}
+ </button>
+ {subOpen && entry.submenu !== undefined && (
+ <div className={clsx(css.submenu, compact && css.compactList)} role="menu">
+ {entry.submenu.map(sub => (
+ <button
+ key={sub.id}
+ type="button"
+ role="menuitem"
+ className={css.item}
+ disabled={sub.disabled}
+ onClick={() => { onSelect(sub.id) }}
+ >
+ {sub.icon !== undefined && <span className={css.itemIcon}>{sub.icon}</span>}
+ <span className={css.itemLabel}>{sub.label}</span>
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ )
+ }
+
+ // Portal lists render hidden until placed: the placement effect measures
+ // this pre-render in the same commit, so the first painted frame is
+ // already at the final position (with getAnchorRect returning null the
+ // list simply stays hidden).
+ const list = open && (
+ <div
+ ref={listRef}
+ className={clsx(css.list, dense && css.denseList, compact && css.compactList, scrollable && css.scrollable, portal && css.portal, portal && 'jiuwenTrajectoryPortal', side === 'top' && !portal && css.sideTop, align === 'end' && !portal && css.alignEnd)}
+ data-trajectory-theme={portal ? colorMode : undefined}
+ style={portal ? fixedPos ?? MEASURE_STYLE : undefined}
+ role="menu"
+ // React portals bubble synthetic events through the REACT tree: without
+ // this stop, an item click re-fires the anchor row's own onClick
+ // (open/toggle) after onSelect.
+ onClick={(e) => { e.stopPropagation() }}
+ >
+ <div className={css.viewport} role="presentation">
+ {items.map(renderEntry)}
+ </div>
+ {footer !== undefined && footer.length > 0 && (
+ <div className={css.footer} role="presentation">
+ {footer.map(renderEntry)}
+ </div>
+ )}
+ </div>
+ )
+
+ // Pointer-leave dismissal watches the WRAPPER, not the list: React's
+ // enter/leave traversal runs over the React tree, so trigger and portaled
+ // list are one region here. Aiming back at the trigger, or crossing the 4px
+ // gap between them, therefore never counts as leaving.
+ return (
+ <span
+ ref={rootRef}
+ className={clsx(css.root, className)}
+ onPointerEnter={closeOnPointerLeave ? cancelClose : undefined}
+ onPointerLeave={closeOnPointerLeave ? () => { if (open) armClose() } : undefined}
+ >
+ {anchor}
+ {portal ? (list !== false && createPortal(list, document.body)) : list}
+ </span>
+ )
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/PROVENANCE.md b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/PROVENANCE.md
new file mode 100644
index 0000000000..734497ec9a
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/PROVENANCE.md
@@ -0,0 +1,7 @@
+# UI primitive source provenance
+
+English | [中文](PROVENANCE.zh.md)
+
+The files in this directory are copies of the modules required by the trajectory viewer from `packages/client/ui-primitives/src` at DeepSeek Harness commit `99f6f02fecdb7dff40c3fbc9470f5907c29f74ca`. They are used under the MIT license and are maintained locally so this repository has no runtime, build, workspace, or source-path dependency on DeepSeek Harness.
+
+The copied set contains Tooltip, Menu, JSON tree, Markdown parsing and rendering, syntax highlighting, KaTeX rendering, icons, and their CSS. The JiuwenSwarm copy adds trajectory-local portal theme propagation and moves concrete presentation colors into scoped theme tokens. `index.ts` deliberately exports only the primitives consumed by this feature.
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/PROVENANCE.zh.md b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/PROVENANCE.zh.md
new file mode 100644
index 0000000000..5d70f51bc9
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/PROVENANCE.zh.md
@@ -0,0 +1,7 @@
+# UI 基础组件来源
+
+[English](PROVENANCE.md) | 中文
+
+本目录中的文件复制自 DeepSeek Harness commit `99f6f02fecdb7dff40c3fbc9470f5907c29f74ca` 的 `packages/client/ui-primitives/src`,包含轨迹查看器所需的模块。这些文件依据 MIT 许可证使用并在本仓库中维护,因此本仓库在运行时、构建、workspace 或源码路径上均不依赖 DeepSeek Harness。
+
+复制内容包括 Tooltip、Menu、JSON tree、Markdown 解析和渲染、语法高亮、KaTeX 渲染、图标及其 CSS。JiuwenSwarm 副本增加了轨迹局部的 portal 主题传递,并把具体展示颜色移入限定作用域的主题 token。`index.ts` 有意仅导出本 feature 使用的基础组件。
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/Tooltip.module.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/Tooltip.module.css
new file mode 100644
index 0000000000..df29365899
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/Tooltip.module.css
@@ -0,0 +1,51 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+/* Visual spec mirrors deepsuite @deepseek/ui Tooltip.css (size m, no arrow),
+ except padding tightened 6/12 -> 3/7, type 14/22 -> 13/20, radius
+ 10 -> 8, a tooltip-bg plate,
+ one text color across both themes (the plate stays dark in light and dark
+ mode). Behavior (fixed positioning off the anchor rect) is local — the
+ upstream Floating stack is intentionally not vendored. */
+
+.bubble {
+ position: fixed;
+ z-index: 100;
+ /* Fixed-position shrink-to-fit measures only the space from `left` to the
+ viewport edge, so anchors near the right edge would wrap early;
+ max-content sizes by the label alone, capped at half the viewport. */
+ width: max-content;
+ max-width: 50vw;
+ padding: 3px 7px;
+ border-radius: 8px;
+ background: var(--dsw-alias-tooltip-bg);
+ color: var(--dsw-static-neutral-bluish-00);
+ font-size: 13px;
+ line-height: 20px;
+ white-space: pre-line;
+ /* Unbreakable tokens (URLs, paths) must not push past max-width. */
+ overflow-wrap: break-word;
+ pointer-events: none;
+ animation: tooltip-in 150ms var(--ds-ease-in-out);
+}
+
+.bubble[data-side='right'] {
+ transform: translateY(-50%);
+}
+
+.bubble[data-side='bottom'] {
+ transform: translateX(-50%);
+}
+
+.bubble[data-side='top'] {
+ transform: translate(-50%, -100%);
+}
+
+@keyframes tooltip-in {
+ from { opacity: 0; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .bubble {
+ animation: none;
+ }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/Tooltip.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/Tooltip.tsx
new file mode 100644
index 0000000000..96624f1551
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/Tooltip.tsx
@@ -0,0 +1,170 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+// Hover/focus label bubble (figma tooltip pill: dark plate, white text).
+// TODO: interaction is a placeholder (horizontal overflow clamps and a
+// vertical collision flips the bubble to the other side, but there is no
+// arrow) — visuals and behavior get a proper pass later.
+// The anchor is the child element itself (cloneElement, no wrapper node), so
+// attaching a tooltip never changes the anchor's layout context. The bubble is
+// position:fixed and coordinates come from the anchor's rect at show time, so
+// it escapes ancestor overflow clipping (the sidebar rail clips its column)
+// without a portal.
+
+import { cloneElement, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
+import type { FocusEventHandler, MouseEventHandler, MutableRefObject, ReactElement, Ref } from 'react'
+import css from './Tooltip.module.css'
+
+/** Bubble placement relative to the anchor. */
+export type TooltipSide = 'right' | 'bottom' | 'top'
+
+/** Props Tooltip injects into its anchor child; the child's own handlers are chained ahead of the tooltip's. */
+interface AnchorProps {
+ ref?: Ref<HTMLElement> | undefined
+ onMouseEnter?: MouseEventHandler | undefined
+ onMouseLeave?: MouseEventHandler | undefined
+ onFocus?: FocusEventHandler | undefined
+ onBlur?: FocusEventHandler | undefined
+}
+
+type TooltipLabel = string | (() => string)
+
+/**
+ * Attach a hover/focus tooltip to an anchor element.
+ * @param props.label - bubble text, or a resolver evaluated only while the bubble is visible.
+ * @param props.side - placement relative to the anchor (default 'right').
+ * @param props.delayMs - hover delay in milliseconds; keyboard focus remains immediate.
+ * @param props.disabled - suppress the bubble while true; the anchor renders identically so
+ * toggling never remounts it (which would cut its CSS transitions).
+ * @param props.maxWidth - bubble width cap in pixels, for labels long enough that the default
+ * half-viewport cap would render a slab wider than the surface the anchor sits on.
+ * @param props.children - a single anchor element; its own ref (callback or object) is forwarded alongside the tooltip's.
+ * @returns the cloned anchor plus a fixed-position bubble while hovered/focused.
+ */
+export function Tooltip({ label, side = 'right', delayMs = 0, disabled = false, maxWidth, children }: { label: TooltipLabel; side?: TooltipSide; delayMs?: number; disabled?: boolean; maxWidth?: number; children: ReactElement<AnchorProps> }) {
+ const anchor = useRef<HTMLElement | null>(null)
+ // React 18 keeps the element's ref outside props; forward it so wrapping an
+ // anchor in Tooltip never silently severs the owner's ref.
+ const childRef = (children as ReactElement<AnchorProps> & { ref?: Ref<HTMLElement> }).ref
+ const mergedRef = useCallback((el: HTMLElement | null) => {
+ anchor.current = el
+ if (typeof childRef === 'function') childRef(el)
+ else if (childRef != null) (childRef as MutableRefObject<HTMLElement | null>).current = el
+ }, [childRef])
+ // The anchor's edges rather than final coordinates: a vertical flip has to
+ // re-derive the bubble's own top from the opposite edge.
+ const [pos, setPos] = useState<{ x: number; top: number; bottom: number } | null>(null)
+ // Where the bubble actually sits, which is the requested side until the
+ // viewport refuses it.
+ const [placement, setPlacement] = useState<TooltipSide>(side)
+ const bubble = useRef<HTMLSpanElement | null>(null)
+ const resolvedLabel = pos === null
+ ? null
+ : typeof label === 'function' ? label() : label
+ const y = pos === null
+ ? 0
+ : placement === 'right'
+ ? pos.top + (pos.bottom - pos.top) / 2
+ : placement === 'top' ? pos.top - 8 : pos.bottom + 8
+ const EDGE_MARGIN = 12
+ // Viewport fit: fixed positioning knows nothing about edges, so a centered
+ // bubble near the right edge would clip and a long label under an anchor low
+ // on the page would run off the bottom. Horizontally the bubble slides back
+ // inside; vertically it flips to the opposite side, which is the only move
+ // that does not cover the anchor being read. Each measurement resets the base
+ // position first, so a shorter label or a larger viewport releases a previous
+ // adjustment without another render.
+ useLayoutEffect(() => {
+ if (pos === null) return
+ const fit = () => {
+ const el = bubble.current
+ /* v8 ignore next -- pos is set only while the bubble is mounted. */
+ if (el === null) return
+ el.style.left = `${pos.x}px`
+ const r = el.getBoundingClientRect()
+ let dx = 0
+ if (r.right > window.innerWidth - EDGE_MARGIN) dx = window.innerWidth - EDGE_MARGIN - r.right
+ if (r.left + dx < EDGE_MARGIN) dx = EDGE_MARGIN - r.left
+ el.style.left = `${pos.x + dx}px`
+ if (side === 'right') return
+ // Flip only into a side that genuinely fits, so an anchor with room on
+ // neither side keeps the requested placement instead of oscillating.
+ const fitsBelow = pos.bottom + 8 + r.height <= window.innerHeight - EDGE_MARGIN
+ const fitsAbove = pos.top - 8 - r.height >= EDGE_MARGIN
+ if (placement === 'bottom' && !fitsBelow && fitsAbove) setPlacement('top')
+ if (placement === 'top' && !fitsAbove && fitsBelow) setPlacement('bottom')
+ }
+ fit()
+ window.addEventListener('resize', fit)
+ return () => { window.removeEventListener('resize', fit) }
+ }, [placement, pos, resolvedLabel, side])
+ const showTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
+ // Hover and focus are independent triggers: the bubble hides only after
+ // BOTH clear (hovering away from a focused anchor must not drop it).
+ const triggers = useRef({ hover: false, focus: false })
+
+ // Disabling mid-hover (e.g. clicking a rail control expands the sidebar)
+ // must drop an already-visible bubble: no mouseleave fires.
+ const cancelShow = useCallback(() => {
+ if (showTimer.current === null) return
+ clearTimeout(showTimer.current)
+ showTimer.current = null
+ }, [])
+ useEffect(() => {
+ if (disabled) {
+ cancelShow()
+ triggers.current = { hover: false, focus: false }
+ setPos(null)
+ }
+ return cancelShow
+ }, [cancelShow, disabled])
+
+ const show = () => {
+ if (disabled) return
+ const el = anchor.current
+ /* v8 ignore next -- the ref is attached by event time: events fire on the cloned anchor. */
+ if (el === null) return
+ const r = el.getBoundingClientRect()
+ // Every show starts from the requested side; the fit pass flips it only
+ // where this anchor's position demands it.
+ setPlacement(side)
+ setPos({ x: side === 'right' ? r.right + 10 : r.left + r.width / 2, top: r.top, bottom: r.bottom })
+ }
+ const showAfterHoverDelay = () => {
+ cancelShow()
+ if (delayMs <= 0) {
+ show()
+ return
+ }
+ showTimer.current = setTimeout(() => {
+ showTimer.current = null
+ show()
+ }, delayMs)
+ }
+ const hide = () => {
+ cancelShow()
+ if (!triggers.current.hover && !triggers.current.focus) setPos(null)
+ }
+
+ return (
+ <>
+ {cloneElement(children, {
+ ref: mergedRef,
+ onMouseEnter: (e) => { children.props.onMouseEnter?.(e); triggers.current.hover = true; showAfterHoverDelay() },
+ onMouseLeave: (e) => { children.props.onMouseLeave?.(e); triggers.current.hover = false; cancelShow(); setPos(null) },
+ onFocus: (e) => { children.props.onFocus?.(e); triggers.current.focus = true; cancelShow(); show() },
+ onBlur: (e) => { children.props.onBlur?.(e); triggers.current.focus = false; hide() },
+ })}
+ {pos !== null && (
+ <span
+ ref={bubble}
+ className={css.bubble}
+ data-side={placement}
+ style={{ left: pos.x, top: y, ...maxWidth === undefined ? {} : { maxWidth } }}
+ role="tooltip"
+ >
+ {resolvedLabel}
+ </span>
+ )}
+ </>
+ )
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/clipboard.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/clipboard.ts
new file mode 100644
index 0000000000..5b8230995f
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/clipboard.ts
@@ -0,0 +1,49 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+// Host clipboard write shared by Web UI copy controls. Success feedback stays
+// with each control; this helper only reports whether the host accepted a write.
+
+/**
+ * Write text to the host clipboard, preferring the async Clipboard API and
+ * falling back to `execCommand('copy')` on hosts (jsdom, insecure contexts)
+ * that omit it.
+ * @param text - the exact text to place on the clipboard.
+ * @returns true only when the host accepted the write.
+ */
+export async function writeClipboard(text: string): Promise<boolean> {
+ // lib.dom types clipboard non-optional, but insecure contexts omit it —
+ // that runtime gap is exactly what this guard detects.
+ /* oxlint-disable-next-line typescript/no-unnecessary-condition */
+ if (navigator.clipboard?.writeText) {
+ try {
+ await navigator.clipboard.writeText(text)
+ return true
+ } catch {
+ // Denied permissions / iframe policy — do not claim success.
+ return false
+ }
+ }
+ // jsdom and older hosts: best-effort execCommand path when present.
+ // execCommand('copy') is the only clipboard fallback where the async API
+ // is missing; deprecated but deliberately retained.
+ /* oxlint-disable typescript/no-deprecated */
+ const exec = typeof document.execCommand === 'function'
+ ? document.execCommand.bind(document)
+ : undefined
+ if (exec === undefined) return false
+ const el = document.createElement('textarea')
+ el.value = text
+ el.setAttribute('readonly', '')
+ el.style.position = 'fixed'
+ el.style.left = '-9999px'
+ document.body.appendChild(el)
+ el.select()
+ try {
+ return exec('copy')
+ } catch {
+ return false
+ } finally {
+ el.remove()
+ }
+ /* oxlint-enable typescript/no-deprecated */
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/icons/index.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/icons/index.tsx
new file mode 100644
index 0000000000..3af12e8017
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/icons/index.tsx
@@ -0,0 +1,874 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * ic_ds_* icon set for the dsh web UI. All glyphs render fill="currentColor"
+ * and take {size, className}. Batch A mirrors the deepsuite icon library
+ * (same figma source); batch B glyphs are harness-only figma extracts.
+ */
+import type { IconProps } from './props.ts'
+
+export type { IconProps } from './props.ts'
+
+/** ic_ds_new_chat_outline_16 */
+export const IconNewChatOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M8.00003 0.3237C3.76075 0.3237 0.32373 3.76072 0.32373 8C0.32373 9.17603 0.589121 10.2922 1.0632 11.2901L1.35291 11.8989L2.5705 11.3205L2.28079 10.7117C1.89079 9.89074 1.67301 8.97167 1.67301 8C1.67301 4.50546 4.50549 1.67298 8.00003 1.67298C11.4946 1.67298 14.3271 4.50546 14.3271 8C14.3271 11.4945 11.4946 14.327 8.00003 14.327C7.28473 14.327 6.76077 14.277 6.29621 14.1487C5.83857 14.0224 5.40441 13.8109 4.88514 13.4488C4.12569 12.919 3.03778 12.7316 2.141 13.2978L2.12682 13.307L2.11264 13.3171L1.34886 13.854L1.79659 15.188L2.86122 14.4384C3.19068 14.2305 3.68325 14.2542 4.11326 14.5539C4.72789 14.9826 5.30042 15.2724 5.93762 15.4484C6.56803 15.6224 7.22776 15.6763 8.00003 15.6763C12.2393 15.6763 15.6763 12.2393 15.6763 8C15.6763 3.76072 12.2393 0.3237 8.00003 0.3237ZM7.32033 4.82535V7.32536H4.82538V8.67464H7.32033V11.1747H8.6696V8.67464H11.1747V7.32536H8.6696V4.82535H7.32033Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_search_outline_16 */
+export const IconSearchOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M11.894845 6.647401C11.894845 3.725463 9.534486 1.356779 6.623219 1.35657C3.711786 1.35657 1.351635 3.725338 1.351635 6.647401C1.351843 9.569296 3.711911 11.938273 6.623219 11.938273C9.534361 11.938064 11.894637 9.569171 11.894845 6.647401ZM13.245462 6.647401C13.245254 10.317935 10.280401 13.293613 6.623219 13.293821C2.965871 13.293821 0.000204 10.31806 0 6.647401C0 2.976574 2.965746 0 6.623219 0C10.280526 0.000205 13.245462 2.9767 13.245462 6.647401Z"
+ fill="currentColor"
+ />
+ <path
+ d="M16.000417 15.041079L15.044449 16.000433L11.530434 12.473588L12.486298 11.514234L16.000417 15.041079Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_globe_outline_14 — meridian globe (harness-only figma extract). */
+export const IconGlobeOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M7.00018 0.353516C10.6708 0.353535 13.6468 3.32958 13.6469 7.00018C13.6468 10.6708 10.6708 13.6468 7.00018 13.6469C3.32957 13.6468 0.353535 10.6708 0.353516 7.00018C0.353535 3.32957 3.32957 0.353531 7.00018 0.353516ZM5.44643 7.59661C5.49463 8.97506 5.70762 10.191 6.02136 11.0793C6.20141 11.5891 6.40328 11.9585 6.59898 12.1889C6.79501 12.4196 6.93213 12.454 7.00018 12.454C7.06822 12.454 7.20533 12.4197 7.40138 12.1889C7.59708 11.9585 7.79895 11.589 7.979 11.0793C8.29274 10.191 8.50574 8.97506 8.55394 7.59661H5.44643ZM1.57861 7.59661C1.80785 9.70467 3.2386 11.4509 5.1715 12.1388C5.07135 11.9317 4.97972 11.7098 4.89746 11.477C4.53084 10.4391 4.30224 9.0828 4.25357 7.59661H1.57861ZM9.74679 7.59661C9.69813 9.0828 9.46952 10.4391 9.1029 11.477C9.0206 11.7099 8.92818 11.9316 8.82797 12.1388C10.7613 11.4511 12.1925 9.70496 12.4218 7.59661H9.74679ZM5.1706 1.8616C3.23814 2.54963 1.80876 4.29604 1.5795 6.40376H4.25357C4.30224 4.91756 4.53083 3.56129 4.89746 2.5234C4.97968 2.29066 5.07051 2.0686 5.1706 1.8616ZM7.00018 1.54637C6.93213 1.54638 6.79503 1.5807 6.59898 1.81145C6.40332 2.04177 6.20139 2.41058 6.02136 2.92012C5.70754 3.80851 5.49461 5.02499 5.44643 6.40376H8.55394C8.50575 5.025 8.29282 3.80851 7.979 2.92012C7.79898 2.41059 7.59705 2.04177 7.40138 1.81145C7.20531 1.58067 7.06823 1.54637 7.00018 1.54637ZM8.82887 1.8616C8.92902 2.0687 9.02064 2.29053 9.1029 2.5234C9.46953 3.56129 9.69812 4.91756 9.74679 6.40376H12.4209C12.1916 4.29575 10.7618 2.54943 8.82887 1.8616Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_settings_outline_14 */
+export const IconSettingsOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <g clipPath="url(#clip0_2580_121189)">
+ <path
+ d="M12.1192 4.91016C11.9392 4.52714 11.7007 4.1292 11.4483 3.78809C11.385 3.70258 11.3517 3.68409 11.2462 3.67383C10.7419 3.6248 10.2318 3.69454 9.72662 3.64551C9.29108 3.60318 8.93739 3.40341 8.67682 3.05176C8.38762 2.66127 8.19217 2.20926 7.90338 1.81934C7.83985 1.73359 7.80848 1.71542 7.70221 1.70508C7.24758 1.6609 6.7511 1.66104 6.29791 1.70508C6.19164 1.71542 6.16027 1.73359 6.09674 1.81934C5.80775 2.20954 5.61248 2.66131 5.3233 3.05176C5.06273 3.40341 4.70904 3.60318 4.2735 3.64551C3.76831 3.69454 3.25825 3.6248 2.75397 3.67383C2.6484 3.68409 2.61509 3.70258 2.55182 3.78809C2.30019 4.12814 2.06125 4.52646 1.88092 4.91016C1.83256 5.01309 1.83242 5.04912 1.88092 5.15235C2.07954 5.57482 2.37449 5.94529 2.5733 6.36817C2.76971 6.78606 2.76964 7.21293 2.5733 7.63086C2.37462 8.05374 2.07947 8.42453 1.88092 8.84668C1.83235 8.95004 1.83257 8.98695 1.88092 9.08985C2.06098 9.47285 2.2994 9.87079 2.55182 10.2119C2.61509 10.2974 2.6484 10.3159 2.75397 10.3262C3.25879 10.3753 3.76834 10.3055 4.2735 10.3545C4.70904 10.3968 5.06273 10.5966 5.3233 10.9482C5.6125 11.3387 5.80795 11.7907 6.09674 12.1807C6.16027 12.2664 6.19164 12.2846 6.29791 12.2949C6.7511 12.339 7.24758 12.3391 7.70221 12.2949C7.80848 12.2846 7.83985 12.2664 7.90338 12.1807C8.19237 11.7905 8.38764 11.3387 8.67682 10.9482C8.93739 10.5966 9.29108 10.3968 9.72662 10.3545C10.2318 10.3055 10.7419 10.3752 11.2462 10.3262C11.3517 10.3159 11.385 10.2974 11.4483 10.2119C11.7007 9.87079 11.9391 9.47285 12.1192 9.08985C12.1675 8.98695 12.1678 8.95004 12.1192 8.84668C11.9205 8.42428 11.6255 8.05377 11.4268 7.63086C11.2305 7.21293 11.2304 6.78606 11.4268 6.36817C11.6256 5.94531 11.9207 5.5746 12.1192 5.15235C12.1677 5.04912 12.1676 5.01309 12.1192 4.91016ZM13.2051 5.66309C13.0064 6.08573 12.7114 6.45579 12.5128 6.87793C12.4642 6.98123 12.4645 7.01829 12.5128 7.1211C12.7112 7.54328 13.0064 7.91405 13.2051 8.33692C13.4015 8.75487 13.4015 9.18169 13.2051 9.59961C12.9911 10.0551 12.7109 10.5221 12.4122 10.9258C12.1522 11.277 11.7974 11.4782 11.3624 11.5205C10.8573 11.5696 10.3477 11.4999 9.84283 11.5488C9.73621 11.5592 9.70429 11.5772 9.64069 11.6631C9.35229 12.0526 9.15705 12.5044 8.86823 12.8945C8.60854 13.2452 8.25275 13.447 7.81842 13.4893C7.28749 13.5409 6.71096 13.5407 6.1817 13.4893C5.74737 13.447 5.39158 13.2452 5.1319 12.8945C4.84312 12.5045 4.64808 12.0529 4.35944 11.6631C4.29583 11.5772 4.26392 11.5592 4.15729 11.5488C3.65283 11.5 3.14295 11.5696 2.63776 11.5205C2.20274 11.4782 1.84796 11.277 1.58795 10.9258C1.28834 10.5209 1.00864 10.0543 0.794982 9.59961C0.598644 9.18169 0.598598 8.75487 0.794982 8.33692C0.993688 7.91405 1.28889 7.54328 1.48737 7.1211C1.53567 7.01829 1.53593 6.98123 1.48737 6.87793C1.28887 6.45603 0.993667 6.08569 0.794982 5.66309C0.598535 5.24516 0.59869 4.81829 0.794982 4.40039C1.00898 3.94492 1.28922 3.47791 1.58795 3.07422C1.84796 2.723 2.20274 2.5218 2.63776 2.47949C3.14295 2.43038 3.65283 2.50003 4.15729 2.45117C4.26391 2.44081 4.29583 2.4228 4.35944 2.33692C4.64783 1.94742 4.84308 1.49557 5.1319 1.10547C5.39158 0.754835 5.74737 0.553005 6.1817 0.510744C6.71263 0.459147 7.28917 0.459309 7.81842 0.510744C8.25275 0.553005 8.60854 0.754835 8.86823 1.10547C9.157 1.49551 9.35204 1.94708 9.64069 2.33692C9.70429 2.4228 9.73621 2.44081 9.84283 2.45117C10.3477 2.50007 10.8573 2.43039 11.3624 2.47949C11.7974 2.5218 12.1522 2.723 12.4122 3.07422C12.7118 3.47909 12.9915 3.94567 13.2051 4.40039C13.4014 4.81829 13.4016 5.24516 13.2051 5.66309Z"
+ fill="currentColor"
+ />
+ <path
+ d="M7.9317 7C7.9317 6.48569 7.51438 6.06836 7.00006 6.06836C6.48575 6.06836 6.06842 6.48569 6.06842 7C6.06842 7.51432 6.48575 7.93164 7.00006 7.93164C7.51438 7.93164 7.9317 7.51432 7.9317 7ZM9.13092 7C9.13092 8.17706 8.17712 9.13086 7.00006 9.13086C5.823 9.13086 4.8692 8.17706 4.8692 7C4.8692 5.82294 5.823 4.86914 7.00006 4.86914C8.17712 4.86914 9.13092 5.82294 9.13092 7Z"
+ fill="currentColor"
+ />
+ </g>
+ <defs>
+ <clipPath id="clip0_2580_121189">
+ <rect width={14} height={14} fill="currentColor" />
+ </clipPath>
+ </defs>
+ </svg>
+)
+
+/** ic_ds_settings_outline_16 */
+export const IconSettingsOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <g clipPath="url(#clip0_1450_63327)">
+ <path
+ d="M14.0861 5.51366C13.8717 5.0575 13.588 4.58542 13.2889 4.18108C13.208 4.07172 13.1596 4.04373 13.0243 4.03054C12.4277 3.97255 11.8245 4.05527 11.2269 3.9972C10.7224 3.94816 10.3133 3.71661 10.0115 3.30919C9.66986 2.84777 9.43973 2.31343 9.09824 1.85234C9.01771 1.74365 8.96805 1.71589 8.83354 1.70282C8.29432 1.65044 7.70402 1.65061 7.16656 1.70282C7.03205 1.71589 6.98239 1.74365 6.90186 1.85234C6.56067 2.31303 6.33025 2.84774 5.98855 3.30919C5.68681 3.71661 5.27774 3.94816 4.77317 3.9972C4.17564 4.05527 3.57239 3.97255 2.97585 4.03054C2.84046 4.04373 2.79208 4.07172 2.71115 4.18108C2.41212 4.58542 2.12835 5.0575 1.91403 5.51366C1.85299 5.64359 1.85286 5.7018 1.91403 5.8319C2.14865 6.33077 2.49748 6.76892 2.73237 7.26854C2.9594 7.7515 2.96041 8.24717 2.73338 8.73044C2.49837 9.23061 2.14891 9.66837 1.91403 10.1681C1.85291 10.2982 1.85299 10.3564 1.91403 10.4863C2.12856 10.9429 2.41185 11.4142 2.71115 11.8189C2.79208 11.9283 2.84046 11.9563 2.97585 11.9694C3.57239 12.0274 4.17564 11.9447 4.77317 12.0028C5.27774 12.0518 5.68681 12.2834 5.98855 12.6908C6.33024 13.1522 6.56037 13.6866 6.90186 14.1476C6.98239 14.2563 7.03205 14.2841 7.16656 14.2972C7.70402 14.3494 8.29432 14.3495 8.83354 14.2972C8.96805 14.2841 9.01771 14.2563 9.09824 14.1476C9.43944 13.687 9.66985 13.1522 10.0115 12.6908C10.3133 12.2834 10.7224 12.0518 11.2269 12.0028C11.8244 11.9447 12.4271 12.0275 13.0243 11.9694C13.1596 11.9563 13.208 11.9283 13.2889 11.8189C13.5891 11.4131 13.872 10.942 14.0861 10.4863C14.1471 10.3564 14.1472 10.2982 14.0861 10.1681C13.8513 9.66861 13.5017 9.23061 13.2667 8.73044C13.0397 8.24717 13.0407 7.7515 13.2677 7.26854C13.5026 6.7689 13.8513 6.33106 14.0861 5.8319C14.1472 5.7018 14.1471 5.64359 14.0861 5.51366ZM15.3035 6.40373C15.0685 6.90359 14.7188 7.34119 14.4841 7.84037C14.4231 7.97025 14.423 8.02855 14.4841 8.15861C14.7189 8.65833 15.0685 9.09611 15.3035 9.59626C15.5308 10.0801 15.5308 10.5744 15.3035 11.0582C15.052 11.5933 14.7225 12.1426 14.37 12.6191C14.0685 13.0265 13.6581 13.259 13.1536 13.3081C12.5566 13.366 11.9541 13.2835 11.3573 13.3414C11.2228 13.3545 11.1731 13.3823 11.0926 13.491C10.7511 13.9521 10.521 14.4864 10.1793 14.9478C9.87828 15.3542 9.46719 15.5869 8.96387 15.6358C8.34008 15.6964 7.66194 15.6966 7.03623 15.6358C6.53291 15.5869 6.12182 15.3542 5.82084 14.9478C5.47911 14.4863 5.24878 13.9517 4.90753 13.491C4.82701 13.3823 4.77734 13.3545 4.64284 13.3414C4.04647 13.2835 3.44373 13.366 2.84653 13.3081C2.34201 13.259 1.93164 13.0265 1.63013 12.6191C1.27867 12.144 0.948453 11.5941 0.696621 11.0582C0.469315 10.5744 0.469279 10.0801 0.696621 9.59626C0.931628 9.09613 1.2813 8.65807 1.51597 8.15861C1.57708 8.02855 1.57702 7.97025 1.51597 7.84037C1.28117 7.34095 0.931635 6.9036 0.696621 6.40373C0.469213 5.91992 0.469367 5.42562 0.696621 4.94183C0.948441 4.40587 1.27868 3.85598 1.63013 3.38092C1.93164 2.97349 2.34201 2.74095 2.84653 2.6919C3.44353 2.63397 4.04599 2.71649 4.64284 2.65856C4.77734 2.64549 4.82701 2.61774 4.90753 2.50904C5.24905 2.04792 5.47913 1.51362 5.82084 1.05219C6.12182 0.645806 6.53291 0.413119 7.03623 0.364178C7.66002 0.303556 8.33816 0.303369 8.96387 0.364178C9.46719 0.413119 9.87828 0.645806 10.1793 1.05219C10.521 1.51365 10.7513 2.04828 11.0926 2.50904C11.1731 2.61774 11.2228 2.64549 11.3573 2.65856C11.9541 2.71649 12.5566 2.63397 13.1536 2.6919C13.6581 2.74095 14.0685 2.97349 14.37 3.38092C14.7214 3.85598 15.0517 4.40587 15.3035 4.94183C15.5307 5.42562 15.5309 5.91992 15.3035 6.40373Z"
+ fill="currentColor"
+ />
+ <path
+ d="M9.13764 7.99999C9.13764 7.3715 8.62855 6.8624 8.00005 6.8624C7.37155 6.8624 6.86246 7.3715 6.86246 7.99999C6.86246 8.62849 7.37155 9.13759 8.00005 9.13759C8.62855 9.13759 9.13764 8.62849 9.13764 7.99999ZM10.4834 7.99999C10.4834 9.37126 9.37132 10.4833 8.00005 10.4833C6.62878 10.4833 5.51674 9.37126 5.51674 7.99999C5.51674 6.62873 6.62878 5.51669 8.00005 5.51669C9.37132 5.51669 10.4834 6.62873 10.4834 7.99999Z"
+ fill="currentColor"
+ />
+ </g>
+ <defs>
+ <clipPath id="clip0_1450_63327">
+ <rect width={16} height={16} fill="currentColor" />
+ </clipPath>
+ </defs>
+ </svg>
+)
+
+/** ic_ds_panel_left_outline_16 */
+export const IconPanelLeftOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M9.67272 0.522841C10.8339 0.522841 11.76 0.522714 12.4963 0.602493C13.2453 0.683657 13.8789 0.854248 14.4264 1.25197C14.7504 1.48739 15.0355 1.77247 15.2709 2.0965C15.6686 2.64394 15.8392 3.27758 15.9204 4.02655C16.0002 4.7629 16 5.68895 16 6.85014V9.14986C16 10.3111 16.0002 11.2371 15.9204 11.9735C15.8392 12.7224 15.6686 13.3561 15.2709 13.9035C15.0355 14.2275 14.7504 14.5126 14.4264 14.748C13.8789 15.1458 13.2453 15.3163 12.4963 15.3975C11.76 15.4773 10.8339 15.4772 9.67272 15.4772H6.3273C5.16611 15.4772 4.24006 15.4773 3.50371 15.3975C2.75474 15.3163 2.1211 15.1458 1.57366 14.748C1.24963 14.5126 0.964549 14.2275 0.729131 13.9035C0.331407 13.3561 0.160817 12.7224 0.0796529 11.9735C-0.000126137 11.2371 1.25338e-09 10.3111 1.25338e-09 9.14986V6.85014C1.25329e-09 5.68895 -0.000126137 4.7629 0.0796529 4.02655C0.160817 3.27758 0.331407 2.64394 0.729131 2.0965C0.964549 1.77247 1.24963 1.48739 1.57366 1.25197C2.1211 0.854248 2.75474 0.683657 3.50371 0.602493C4.24006 0.522714 5.16611 0.522841 6.3273 0.522841H9.67272ZM5.54303 1.88715V14.1118C5.78636 14.1128 6.04709 14.1169 6.3273 14.1169H9.67272C10.8639 14.1169 11.7032 14.1164 12.3493 14.0465C12.9824 13.9779 13.3497 13.8494 13.6268 13.6482C13.8354 13.4966 14.0195 13.3125 14.1711 13.1039C14.3723 12.8268 14.5007 12.4595 14.5693 11.8264C14.6393 11.1803 14.6398 10.341 14.6398 9.14986V6.85014C14.6398 5.65896 14.6393 4.81967 14.5693 4.1736C14.5007 3.54048 14.3723 3.17318 14.1711 2.89609C14.0195 2.68747 13.8354 2.50337 13.6268 2.35179C13.3497 2.1506 12.9824 2.02212 12.3493 1.95353C11.7032 1.88358 10.8639 1.88307 9.67272 1.88307H6.3273C6.04709 1.88307 5.78636 1.8862 5.54303 1.88715ZM4.1828 1.91166C3.99125 1.9216 3.8148 1.93577 3.65076 1.95353C3.01764 2.02212 2.65034 2.1506 2.37325 2.35179C2.16463 2.50337 1.98052 2.68747 1.82895 2.89609C1.62776 3.17318 1.49928 3.54048 1.43069 4.1736C1.36074 4.81967 1.36023 5.65896 1.36023 6.85014V9.14986C1.36023 10.341 1.36074 11.1803 1.43069 11.8264C1.49928 12.4595 1.62776 12.8268 1.82895 13.1039C1.98052 13.3125 2.16463 13.4966 2.37325 13.6482C2.65034 13.8494 3.01764 13.9779 3.65076 14.0465C3.81478 14.0642 3.99127 14.0774 4.1828 14.0873V1.91166Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_ellipsis_outline_16 */
+export const IconEllipsisOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M4.55146 8.00001C4.55146 8.63513 4.03659 9.15001 3.40146 9.15001C2.76634 9.15001 2.25146 8.63513 2.25146 8.00001C2.25146 7.36488 2.76634 6.85001 3.40146 6.85001C4.03659 6.85001 4.55146 7.36488 4.55146 8.00001Z"
+ fill="currentColor"
+ />
+ <path
+ d="M9.1476 8.00001C9.1476 8.63513 8.63273 9.15001 7.9976 9.15001C7.36248 9.15001 6.8476 8.63513 6.8476 8.00001C6.8476 7.36488 7.36248 6.85001 7.9976 6.85001C8.63273 6.85001 9.1476 7.36488 9.1476 8.00001Z"
+ fill="currentColor"
+ />
+ <path
+ d="M13.7486 8.00001C13.7486 8.63513 13.2338 9.15001 12.5986 9.15001C11.9635 9.15001 11.4486 8.63513 11.4486 8.00001C11.4486 7.36488 11.9635 6.85001 12.5986 6.85001C13.2338 6.85001 13.7486 7.36488 13.7486 8.00001Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_plus_outline_16 */
+export const IconPlusOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M8.64453 1.5V7.34961H14.5V8.65039H8.64453V14.5H7.34473V8.65039H1.5V7.34961H7.34473V1.5H8.64453Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_check_outline_16 */
+export const IconCheckOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M15.0498 3.92579L8.49512 12.3818C8.25774 12.6881 8.04517 12.9645 7.84668 13.1689C7.63957 13.3823 7.38732 13.5841 7.04492 13.6719C6.86373 13.7183 6.6757 13.7346 6.48926 13.7197C6.13666 13.6915 5.8528 13.5355 5.6123 13.3604C5.38201 13.1926 5.12573 12.9567 4.83984 12.6953L1.03125 9.21289L1.96875 8.1875L5.77734 11.6699C6.08684 11.9529 6.27773 12.1249 6.43066 12.2363C6.50183 12.2882 6.54699 12.3135 6.57324 12.3252C6.58525 12.3305 6.59269 12.3322 6.5957 12.333C6.59802 12.3336 6.59961 12.334 6.59961 12.334C6.63317 12.3367 6.66758 12.3335 6.7002 12.3252C6.7002 12.3252 6.70211 12.3251 6.7041 12.3242C6.70698 12.3229 6.71348 12.319 6.72461 12.3115C6.74849 12.2956 6.78843 12.2642 6.84961 12.2012C6.98138 12.0654 7.13957 11.8628 7.39648 11.5313L13.9502 3.07422L15.0498 3.92579Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_check_outline_14 */
+export const IconCheckOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M11.5635 4.58984L7.61426 9.07715C7.35154 9.37561 7.11346 9.64812 6.89453 9.84668C6.66593 10.054 6.38519 10.2506 6.01465 10.3164C5.82079 10.3508 5.62207 10.3529 5.42773 10.3213C5.0561 10.2609 4.77266 10.0674 4.54102 9.86328C4.31926 9.66791 4.07752 9.39911 3.81055 9.10449L2.44531 7.59863L3.55664 6.59082L4.92188 8.09766C5.21256 8.41844 5.38878 8.61191 5.53223 8.73828C5.61022 8.80699 5.65253 8.83192 5.66895 8.83984C5.69648 8.84429 5.72449 8.84467 5.75195 8.83984C5.72657 8.84451 5.75564 8.85422 5.88672 8.73535C6.02833 8.60692 6.20225 8.41088 6.48828 8.08594L10.4385 3.59961L11.5635 4.58984Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_branch_outline_16 */
+export const IconBranchOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M13.0762 1.37207C14.0846 1.37228 14.9021 2.19077 14.9023 3.19922C14.9022 4.20772 14.0847 5.02518 13.0762 5.02539C12.2967 5.02539 11.6325 4.53691 11.3701 3.84961H4.35547C4.79397 4.26458 5.15861 4.7644 5.41699 5.33496L7.10645 9.06738C7.88526 10.7875 9.55104 11.9228 11.4189 12.0371C11.7085 11.4109 12.3411 10.9756 13.0762 10.9756C14.0843 10.9759 14.9023 11.7936 14.9023 12.8018C14.9023 13.81 14.0843 14.6277 13.0762 14.6279C12.2534 14.6279 11.5574 14.0832 11.3291 13.335C8.9868 13.1879 6.89981 11.7612 5.92285 9.60352L4.23242 5.87109C3.67503 4.64033 2.44878 3.84961 1.09766 3.84961V2.54883C1.10665 2.54883 1.11601 2.54975 1.125 2.5498L11.3701 2.54883C11.6326 1.86151 12.2969 1.37207 13.0762 1.37207ZM13.0762 12.2764C12.7858 12.2764 12.5508 12.5114 12.5508 12.8018C12.5508 13.0921 12.7858 13.3281 13.0762 13.3281C13.3664 13.3279 13.6025 13.092 13.6025 12.8018C13.6025 12.5115 13.3664 12.2766 13.0762 12.2764ZM13.0762 2.67285C12.7855 2.67285 12.55 2.90861 12.5498 3.19922C12.5499 3.48987 12.7855 3.72559 13.0762 3.72559C13.3667 3.72538 13.6024 3.48975 13.6025 3.19922C13.6023 2.90874 13.3666 2.67306 13.0762 2.67285Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_chevron_down_outline_14 */
+export const IconChevronDownOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M11.8486 5.5L11.4238 5.92383L8.69727 8.65137C8.44157 8.90706 8.21562 9.13382 8.01172 9.29785C7.79912 9.46883 7.55595 9.61756 7.25 9.66602C7.08435 9.69222 6.91565 9.69222 6.75 9.66602C6.44405 9.61756 6.20088 9.46883 5.98828 9.29785C5.78438 9.13382 5.55843 8.90706 5.30273 8.65137L2.57617 5.92383L2.15137 5.5L3 4.65137L3.42383 5.07617L6.15137 7.80273C6.42595 8.07732 6.59876 8.24849 6.74023 8.3623C6.87291 8.46904 6.92272 8.47813 6.9375 8.48047C6.97895 8.48703 7.02105 8.48703 7.0625 8.48047C7.07728 8.47813 7.12709 8.46904 7.25977 8.3623C7.40124 8.24849 7.57405 8.07732 7.84863 7.80273L10.5762 5.07617L11 4.65137L11.8486 5.5Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_chevron_left_outline_14 */
+export const IconChevronLeftOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M8.5 2.15137L8.07617 2.57617L5.34863 5.30273C5.09294 5.55843 4.86618 5.78438 4.70215 5.98828C4.53117 6.20088 4.38244 6.44405 4.33398 6.75C4.30778 6.91565 4.30778 7.08435 4.33398 7.25C4.38244 7.55595 4.53117 7.79912 4.70215 8.01172C4.86618 8.21561 5.09294 8.44157 5.34863 8.69727L8.07617 11.4238L8.5 11.8486L9.34863 11L8.92383 10.5762L6.19727 7.84863C5.92268 7.57405 5.75151 7.40124 5.6377 7.25977C5.53096 7.12709 5.52187 7.07728 5.51953 7.0625C5.51297 7.02105 5.51297 6.97895 5.51953 6.9375C5.52187 6.92272 5.53096 6.87291 5.6377 6.74023C5.75152 6.59876 5.92268 6.42595 6.19727 6.15137L8.92383 3.42383L9.34863 3L8.5 2.15137Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_chevron_right_outline_14 */
+export const IconChevronRightOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M5.5 2.15137L5.92383 2.57617L8.65137 5.30273C8.90706 5.55843 9.13382 5.78438 9.29785 5.98828C9.46883 6.20088 9.61756 6.44405 9.66602 6.75C9.69222 6.91565 9.69222 7.08435 9.66602 7.25C9.61756 7.55595 9.46883 7.79912 9.29785 8.01172C9.13382 8.21561 8.90706 8.44157 8.65137 8.69727L5.92383 11.4238L5.5 11.8486L4.65137 11L5.07617 10.5762L7.80273 7.84863C8.07732 7.57405 8.24849 7.40124 8.3623 7.25977C8.46904 7.12709 8.47813 7.07728 8.48047 7.0625C8.48703 7.02105 8.48703 6.97895 8.48047 6.9375C8.47813 6.92272 8.46904 6.87291 8.3623 6.74023C8.24848 6.59876 8.07732 6.42595 7.80273 6.15137L5.07617 3.42383L4.65137 3L5.5 2.15137Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_triangle_right_fill_14 — tree expand arrow; points right, consumers rotate it 90° for the open state. */
+export const IconTriangleRightFill14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M4.25 2.82782L4.25 11.1722C4.25 11.6622 4.84243 11.9076 5.18891 11.5611L9.36109 7.38891C9.57588 7.17412 9.57588 6.82588 9.36109 6.61109L5.18891 2.43891C4.84243 2.09243 4.25 2.33782 4.25 2.82782Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_chevron_up_outline_14 */
+export const IconChevronUpOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M2.15137 8.5L2.57617 8.07617L5.30273 5.34863C5.55843 5.09294 5.78438 4.86618 5.98828 4.70215C6.20088 4.53117 6.44405 4.38244 6.75 4.33398C6.91565 4.30778 7.08435 4.30778 7.25 4.33398C7.55595 4.38244 7.79912 4.53117 8.01172 4.70215C8.21561 4.86618 8.44157 5.09294 8.69727 5.34863L11.4238 8.07617L11.8486 8.5L11 9.34863L10.5762 8.92383L7.84863 6.19727C7.57405 5.92269 7.40124 5.75152 7.25977 5.6377C7.12709 5.53096 7.07728 5.52187 7.0625 5.51953C7.02105 5.51297 6.97895 5.51297 6.9375 5.51953C6.92272 5.52187 6.87291 5.53096 6.74023 5.6377C6.59876 5.75152 6.42595 5.92268 6.15137 6.19727L3.42383 8.92383L3 9.34863L2.15137 8.5Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_close_outline_16 */
+export const IconCloseOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M14.1168 13.197L13.197 14.1167L1.8833 2.80303L2.80309 1.88324L14.1168 13.197Z"
+ fill="currentColor"
+ />
+ <path
+ d="M13.197 1.88326L14.1168 2.80305L2.80309 14.1168L1.8833 13.197L13.197 1.88326Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_close_fill_14 */
+export const IconCloseFill14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M10.6074 4.40278L8.00975 6.99973L10.6074 9.59739L9.59736 10.6074L6.9997 8.00978L4.40274 10.6074L3.3927 9.59739L5.98966 6.99973L3.3927 4.40278L4.40274 3.39273L6.9997 5.98969L9.59736 3.39273L10.6074 4.40278Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_copy_outline_16 */
+export const IconCopyOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M6.14929 4.02032C7.11197 4.02032 7.87983 4.02016 8.49597 4.07598C9.12128 4.13269 9.65792 4.25188 10.1415 4.53106C10.7202 4.8653 11.2008 5.3459 11.535 5.92462C11.8142 6.40818 11.9334 6.94481 11.9901 7.57012C12.0459 8.18625 12.0458 8.95419 12.0458 9.9168C12.0458 10.8795 12.0459 11.6473 11.9901 12.2635C11.9334 12.8888 11.8142 13.4254 11.535 13.909C11.2008 14.4877 10.7202 14.9683 10.1415 15.3025C9.65792 15.5817 9.12128 15.7009 8.49597 15.7576C7.87984 15.8134 7.11196 15.8133 6.14929 15.8133C5.18667 15.8133 4.41874 15.8134 3.80261 15.7576C3.1773 15.7009 2.64067 15.5817 2.1571 15.3025C1.5784 14.9683 1.09778 14.4877 0.76355 13.909C0.484366 13.4254 0.365184 12.8888 0.308472 12.2635C0.252649 11.6473 0.252808 10.8795 0.252808 9.9168C0.252808 8.95418 0.252664 8.18625 0.308472 7.57012C0.365184 6.94481 0.484366 6.40818 0.76355 5.92462C1.09777 5.34589 1.57839 4.86529 2.1571 4.53106C2.64067 4.25188 3.1773 4.13269 3.80261 4.07598C4.41874 4.02017 5.18666 4.02032 6.14929 4.02032ZM6.14929 5.37774C5.16181 5.37774 4.46634 5.37761 3.92566 5.42657C3.39434 5.47472 3.07859 5.56574 2.83582 5.70587C2.4632 5.92106 2.15354 6.2307 1.93835 6.60333C1.79823 6.8461 1.70721 7.16185 1.65906 7.69317C1.6101 8.23385 1.61023 8.92933 1.61023 9.9168C1.61023 10.9043 1.61009 11.5998 1.65906 12.1404C1.70721 12.6717 1.79823 12.9875 1.93835 13.2303C2.15356 13.6029 2.46321 13.9126 2.83582 14.1277C3.07859 14.2679 3.39434 14.3589 3.92566 14.407C4.46634 14.456 5.16182 14.4559 6.14929 14.4559C7.13682 14.4559 7.83224 14.456 8.37292 14.407C8.90425 14.3589 9.21999 14.2679 9.46277 14.1277C9.83535 13.9126 10.145 13.6029 10.3602 13.2303C10.5004 12.9875 10.5914 12.6717 10.6395 12.1404C10.6885 11.5998 10.6884 10.9043 10.6884 9.9168C10.6884 8.92934 10.6885 8.23384 10.6395 7.69317C10.5914 7.16185 10.5004 6.8461 10.3602 6.60333C10.1451 6.23071 9.83536 5.92107 9.46277 5.70587C9.21999 5.56574 8.90424 5.47472 8.37292 5.42657C7.83224 5.3776 7.13682 5.37774 6.14929 5.37774ZM9.80164 0.367975C10.7638 0.367975 11.5314 0.36788 12.1473 0.423639C12.7726 0.480307 13.3093 0.598759 13.7928 0.877741C14.3717 1.21192 14.8521 1.69355 15.1864 2.27227C15.4655 2.75574 15.5857 3.29164 15.6425 3.9168C15.6983 4.53301 15.6971 5.3016 15.6971 6.26446V7.82989C15.6971 8.29264 15.6989 8.58993 15.6649 8.84844C15.4668 10.3525 14.401 11.5738 12.9833 11.9988V10.5467C13.6973 10.1903 14.2105 9.49662 14.3192 8.67169C14.3387 8.52347 14.3407 8.3358 14.3407 7.82989V6.26446C14.3407 5.27706 14.3398 4.58149 14.2909 4.04083C14.2428 3.50968 14.1526 3.19372 14.0126 2.95098C13.7974 2.57849 13.4876 2.26869 13.1151 2.05352C12.8724 1.91347 12.5564 1.82237 12.0253 1.77423C11.4847 1.72528 10.7888 1.7254 9.80164 1.7254H7.71472C6.7562 1.72558 5.92665 2.27697 5.52332 3.07891H4.07019C4.54221 1.51132 5.9932 0.368186 7.71472 0.367975H9.80164Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_refresh_outline_16 */
+export const IconRefreshOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M7.92136 0.349152C10.3744 0.349234 12.5564 1.5052 13.9557 3.29894L15.1281 2.12759C15.3303 1.92546 15.6767 2.06943 15.6767 2.35538V5.53923C15.6766 5.71626 15.5329 5.85976 15.3559 5.86002H12.171C11.8854 5.8597 11.7426 5.51465 11.9443 5.31249L12.9641 4.29056C11.8237 2.74305 9.98908 1.74106 7.92136 1.74097C4.46436 1.74097 1.66233 4.543 1.66233 8C1.66233 11.457 4.46436 14.259 7.92136 14.259C11.3782 14.2589 14.1804 11.4569 14.1804 8H15.5722C15.5722 12.2251 12.1465 15.6507 7.92136 15.6508C3.69614 15.6508 0.270508 12.2252 0.270508 8C0.270508 3.77478 3.69614 0.349152 7.92136 0.349152Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_refresh_outline_14 */
+export const IconRefreshOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M1.272 6.21348C1.70645 3.08888 4.59169 0.908064 7.71634 1.34239C8.95495 1.51469 10.0438 2.07331 10.8814 2.87755L11.9458 1.81407C12.1347 1.6255 12.4572 1.75911 12.4575 2.02598V5.08751C12.4574 5.25303 12.3233 5.38731 12.1577 5.38731H9.0972C8.82993 5.38731 8.69629 5.06361 8.88528 4.87462L10.0327 3.72618C9.3732 3.09994 8.52006 2.66569 7.5513 2.53087C5.08313 2.18779 2.80376 3.91044 2.46048 6.37852C2.11747 8.84665 3.84009 11.1261 6.30814 11.4693C8.77612 11.8121 11.0557 10.0896 11.399 7.62169L11.9937 7.70372L12.5874 7.78673C12.153 10.9112 9.26756 13.0919 6.1431 12.6578C3.01854 12.2234 0.837738 9.33809 1.272 6.21348Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_like_outline_16 */
+export const IconLikeOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M8.27868 0.811572C8.81991 0.142194 9.79022 0.0421835 10.4538 0.557601L10.5823 0.669306L10.6066 0.693544L10.6097 0.695652L10.6392 0.725159C11.355 1.44679 11.6337 2.49468 11.3716 3.47669L11.3706 3.48091L11.3611 3.51674L11.3601 3.51885L10.889 5.22604C10.8796 5.25997 10.8707 5.29157 10.8627 5.32088C10.8934 5.32095 10.927 5.32194 10.9628 5.32194H11.9007C12.4264 5.32194 12.7831 5.319 13.0651 5.36725C14.8182 5.66719 15.9851 7.34568 15.6565 9.09357C15.6036 9.37487 15.477 9.7092 15.294 10.2022L14.3371 12.7798C14.1402 13.3104 13.9774 13.7518 13.8102 14.1024C13.6376 14.4645 13.4386 14.7793 13.1442 15.0424C12.9712 15.197 12.7802 15.3303 12.5751 15.4386C12.226 15.6231 11.8608 15.7 11.4612 15.7358C11.0743 15.7705 10.6035 15.7695 10.0375 15.7695H4.87377C4.08053 15.7695 3.42928 15.7702 2.90734 15.7137C2.37212 15.6557 1.88991 15.5311 1.46676 15.2237C1.22415 15.0474 1.01078 14.8339 0.834466 14.5914C0.527021 14.1682 0.401373 13.686 0.343384 13.1508C0.286822 12.6287 0.287531 11.9769 0.287531 11.1833V9.51405C0.287531 8.84778 0.281347 8.36714 0.399237 7.9565C0.671152 7.00935 1.41115 6.26832 2.35829 5.99638C2.76894 5.87849 3.24958 5.88573 3.91585 5.88573C4.11983 5.88573 4.14548 5.88319 4.16244 5.88046C4.23532 5.86863 4.30409 5.83663 4.35845 5.78667C4.3711 5.77504 4.38761 5.75604 4.51442 5.59488L8.25655 0.838972L8.2576 0.837918L8.27868 0.811572ZM1.69122 11.1833C1.69122 12.0082 1.69217 12.5711 1.73865 13.0001C1.78371 13.4157 1.86473 13.6221 1.96943 13.7662C2.0592 13.8898 2.16733 13.9989 2.29085 14.0887C2.43501 14.1934 2.64216 14.2744 3.05803 14.3195C3.45897 14.3629 3.97637 14.3656 4.7157 14.3659C4.30801 13.8053 4.06453 13.1171 4.06444 12.371V8.59406H5.46813V12.371C5.46838 13.4733 6.36166 14.3669 7.46407 14.3669H10.0375C10.6286 14.3669 11.0269 14.3663 11.3369 14.3385C11.6339 14.3118 11.7956 14.2638 11.9196 14.1983C12.0241 14.1431 12.1213 14.0747 12.2094 13.996C12.314 13.9025 12.4151 13.7678 12.5435 13.4986C12.6774 13.2176 12.8162 12.845 13.0219 12.2909L13.9788 9.71322C14.1848 9.15816 14.2531 8.96731 14.2781 8.83433C14.4618 7.85692 13.8093 6.91895 12.8291 6.75092C12.6957 6.7281 12.4928 6.72458 11.9007 6.72458H10.9628C10.7737 6.72458 10.5693 6.72657 10.4 6.70666C10.2211 6.68562 9.96702 6.63024 9.74771 6.43161C9.64454 6.33811 9.55957 6.2261 9.4969 6.10177C9.3639 5.83784 9.37799 5.57899 9.40521 5.40097C9.431 5.23261 9.48672 5.03616 9.53694 4.85404L10.008 3.14579L10.0175 3.11102C10.1488 2.61338 10.0078 2.08338 9.64654 1.71681L9.6086 1.67887L9.55064 1.64304C9.48795 1.62043 9.41425 1.63814 9.36938 1.69362L9.35779 1.70627L9.35884 1.70732L5.61672 6.46217C5.51822 6.58735 5.42237 6.7133 5.30689 6.81942C5.05075 7.05471 4.73126 7.20939 4.38796 7.26519C4.23315 7.29032 4.07513 7.28837 3.91585 7.28837C3.15356 7.28837 2.91916 7.2957 2.7461 7.34528C2.26364 7.48379 1.88564 7.86081 1.74708 8.34325C1.69738 8.51636 1.69122 8.7511 1.69122 9.51405V11.1833Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_like_fill_16 */
+export const IconLikeFill16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M14.0593 12.922L15.0976 10.1247C15.3087 9.5559 15.4143 9.27138 15.4566 9.04658C15.7349 7.56751 14.7472 6.14737 13.2637 5.89357C13.0382 5.85499 12.7348 5.85499 12.1281 5.85499H11.1099C10.6615 5.85499 10.4372 5.85499 10.3034 5.73376C10.2607 5.69508 10.2255 5.64885 10.1995 5.5974C10.1182 5.43613 10.1778 5.21997 10.297 4.78765L10.8081 2.93419L10.819 2.89456C11.0336 2.09024 10.8051 1.23244 10.2189 0.64139L10.1898 0.612405L10.1692 0.592068C9.77357 0.210076 9.13559 0.249344 8.78983 0.676966L8.77186 0.699678L4.71076 5.86083C4.52965 6.09101 4.38573 6.35138 4.38573 6.64427V12.7431C4.38573 14.3601 5.69654 15.6709 7.31351 15.6709L10.1068 15.6709C11.3628 15.6709 11.9908 15.6709 12.5043 15.3995C12.6723 15.3107 12.8289 15.2018 12.9706 15.0752C13.4037 14.6882 13.6222 14.0995 14.0593 12.922Z"
+ fill="currentColor"
+ />
+ <path
+ d="M2.91388 13.2113C2.91388 14.6907 4.08499 15.5536 4.08499 15.5536H2.65606C1.46328 15.5536 0.496338 14.5866 0.496338 13.3938V8.34439C0.496338 7.15161 1.46328 6.18467 2.65606 6.18467H2.91388V13.2113Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_dislike_outline_16 */
+export const IconDislikeOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M7.72451 15.1086C7.18929 15.7705 6.22975 15.8694 5.57357 15.3597L5.44643 15.2492L5.42247 15.2253L5.41934 15.2232L5.39016 15.194C4.68239 14.4804 4.40679 13.4441 4.66589 12.473L4.66693 12.4689L4.67631 12.4334L4.67735 12.4314L5.14318 10.7431C5.15243 10.7096 5.1613 10.6783 5.16923 10.6493C5.13878 10.6493 5.10558 10.6483 5.07023 10.6483H4.14274C3.62288 10.6483 3.27015 10.6512 2.9912 10.6035C1.25757 10.3069 0.103662 8.64702 0.42863 6.91854C0.480965 6.64037 0.606164 6.30975 0.787119 5.82223L1.73336 3.27321C1.92812 2.74852 2.08912 2.31209 2.25442 1.96535C2.42515 1.60724 2.62191 1.29594 2.91304 1.03578C3.08408 0.882951 3.273 0.751121 3.47579 0.643944C3.82102 0.461504 4.18214 0.38551 4.57731 0.350066C4.95993 0.315784 5.42553 0.316718 5.98521 0.316718H11.0916C11.876 0.316718 12.52 0.31607 13.0362 0.37195C13.5655 0.429293 14.0423 0.552534 14.4608 0.856536C14.7007 1.03085 14.9117 1.24193 15.086 1.48181C15.3901 1.90027 15.5143 2.37709 15.5717 2.90638C15.6276 3.42269 15.6269 4.06721 15.6269 4.85202V6.50274C15.6269 7.1616 15.633 7.6369 15.5164 8.04299C15.2475 8.97962 14.5158 9.71242 13.5791 9.98133C13.173 10.0979 12.6977 10.0908 12.0389 10.0908C11.8372 10.0908 11.8118 10.0933 11.795 10.096C11.723 10.1077 11.6549 10.1393 11.6012 10.1887C11.5887 10.2002 11.5724 10.219 11.447 10.3784L7.74639 15.0815L7.74535 15.0825L7.72451 15.1086ZM14.2388 4.85202C14.2388 4.03628 14.2379 3.47965 14.1919 3.05541C14.1473 2.64443 14.0672 2.4403 13.9637 2.29779C13.8749 2.17562 13.768 2.06769 13.6458 1.9789C13.5033 1.87532 13.2984 1.79523 12.8872 1.75067C12.4907 1.70773 11.979 1.70511 11.2479 1.70482C11.6511 2.25917 11.8918 2.93968 11.8919 3.67755V7.41251H10.5038V3.67755C10.5036 2.58745 9.62023 1.70378 8.53007 1.70378H5.98521C5.40065 1.70378 5.00679 1.70442 4.70028 1.73192C4.40651 1.7583 4.24662 1.80571 4.12399 1.87052C4.02069 1.92511 3.92452 1.99276 3.8374 2.07061C3.73401 2.16306 3.634 2.2962 3.50705 2.56249C3.37462 2.84027 3.23734 3.20873 3.03393 3.75675L2.08768 6.30578C1.88395 6.85467 1.81646 7.0434 1.79172 7.1749C1.61005 8.14146 2.25533 9.06902 3.22464 9.23517C3.35654 9.25774 3.55717 9.26123 4.14274 9.26123H5.07023C5.25717 9.26123 5.4593 9.25926 5.62672 9.27894C5.80364 9.29975 6.05492 9.35452 6.27179 9.55094C6.37381 9.6434 6.45784 9.75417 6.51982 9.87712C6.65133 10.1381 6.6374 10.3941 6.61048 10.5701C6.58498 10.7366 6.52988 10.9309 6.48022 11.111L6.01439 12.8003L6.00501 12.8347C5.87513 13.3268 6.01464 13.8509 6.37184 14.2134L6.40935 14.2509L6.46667 14.2863C6.52866 14.3087 6.60155 14.2912 6.64591 14.2363L6.65738 14.2238L6.65633 14.2228L10.3569 9.52072C10.4543 9.39693 10.5491 9.27238 10.6633 9.16744C10.9166 8.93476 11.2325 8.7818 11.572 8.72662C11.7251 8.70177 11.8814 8.70369 12.0389 8.70369C12.7927 8.70369 13.0245 8.69645 13.1956 8.64742C13.6727 8.51045 14.0465 8.13761 14.1836 7.66053C14.2327 7.48935 14.2388 7.25721 14.2388 6.50274V4.85202Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_dislike_fill_16 */
+export const IconDislikeFill16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M1.92838 3.06811L0.88799 5.87104C0.676449 6.44097 0.570628 6.72606 0.52825 6.95131C0.249414 8.43336 1.2391 9.85637 2.72555 10.1107C2.95149 10.1493 3.25549 10.1493 3.86348 10.1493H4.88371C5.33306 10.1493 5.55774 10.1493 5.69187 10.2708C5.73467 10.3096 5.76994 10.3559 5.79593 10.4074C5.87738 10.569 5.81766 10.7856 5.69821 11.2188L5.18609 13.076L5.17522 13.1157C4.9602 13.9217 5.1891 14.7812 5.7765 15.3735L5.80568 15.4025L5.82635 15.4229C6.22273 15.8056 6.862 15.7663 7.20846 15.3378L7.22647 15.315L11.2958 10.1435C11.4772 9.91284 11.6214 9.65195 11.6214 9.35847V3.24734C11.6214 1.62711 10.308 0.313655 8.68776 0.313655L5.88886 0.313654C4.63032 0.313654 4.00105 0.313654 3.48649 0.585577C3.31815 0.674536 3.16127 0.783647 3.01929 0.910507C2.58531 1.29828 2.36633 1.88824 1.92838 3.06811Z"
+ fill="currentColor"
+ />
+ <path
+ d="M13.0963 2.77815C13.0963 1.29585 11.9228 0.431205 11.9228 0.431205H13.3546C14.5498 0.431205 15.5187 1.4001 15.5187 2.59529V7.65491C15.5187 8.8501 14.5498 9.81899 13.3546 9.81899H13.0963V2.77815Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_share_outline_16 */
+export const IconShareOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M7.95889 1.52285C7.95888 0.826234 8.76055 0.467983 9.27669 0.875208L9.37524 0.967191L15.1317 7.18358C15.5582 7.64419 15.5582 8.35614 15.1317 8.81676L9.37524 15.0331C8.87034 15.578 7.95888 15.2205 7.95889 14.4775V10.8207C7.10614 10.8432 6.31361 10.9316 5.45468 11.2515C4.39484 11.6463 3.18248 12.413 1.64676 13.9425C1.4533 14.135 1.18329 14.1696 0.969086 14.0908C0.74748 14.0091 0.547307 13.7879 0.54859 13.4844L0.55516 13.1315C0.618924 11.3494 1.11153 9.29838 2.27656 7.63787C3.45289 5.96147 5.29554 4.71635 7.95889 4.54797V1.52285ZM9.20911 5.13366C9.20899 5.50567 8.9031 5.77687 8.56523 5.77755C5.99383 5.78282 4.33736 6.8762 3.29964 8.35496C2.54519 9.43014 2.10739 10.7283 1.9152 11.9939C3.04749 11.0323 4.0569 10.4385 5.01917 10.0801C6.29638 9.60449 7.4406 9.56343 8.56429 9.56295C8.9178 9.5628 9.20894 9.84909 9.20911 10.2068L9.20817 13.3737L14.1837 8.00017L9.20817 2.62571L9.20911 5.13366Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_edit_outline_16 */
+export const IconEditOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M9.94076 1.34942C10.7047 0.90231 11.6503 0.902415 12.4143 1.34942C12.7061 1.52015 12.9688 1.79118 13.3104 2.13284C13.6521 2.47448 13.9231 2.73721 14.0939 3.02894C14.5408 3.79294 14.5409 4.73856 14.0939 5.50251C13.9231 5.79415 13.652 6.05704 13.3104 6.39861L6.65932 13.0497C6.28068 13.4284 6.00695 13.7108 5.66543 13.9097C5.32391 14.1085 4.94315 14.2074 4.42705 14.3498L3.24394 14.6761C2.77527 14.8054 2.34538 14.9262 2.00131 14.9684C1.65196 15.0112 1.17964 15.0013 0.810764 14.6325C0.441921 14.2637 0.432107 13.7913 0.47486 13.442C0.517035 13.0979 0.6379 12.668 0.767181 12.1993L1.09352 11.0162C1.23588 10.5001 1.33481 10.1193 1.5336 9.77784C1.7325 9.43632 2.0149 9.1626 2.39355 8.78395L9.04466 2.13284C9.38625 1.79126 9.64911 1.52016 9.94076 1.34942ZM15.5427 14.8398H7.55223L8.96707 13.425H15.5427V14.8398ZM3.39382 9.78422C2.965 10.213 2.84244 10.3436 2.75709 10.49C2.67183 10.6366 2.61862 10.8079 2.45733 11.3925L2.13099 12.5756C2.00183 13.0439 1.92194 13.3419 1.88863 13.5536C2.10041 13.5204 2.39872 13.4416 2.86764 13.3123L4.05075 12.9859C4.63544 12.8246 4.80669 12.7715 4.95323 12.6862C5.09968 12.6008 5.23022 12.4783 5.65905 12.0494L10.721 6.98644L8.45577 4.72121L3.39382 9.78422ZM11.7 2.57079C11.3774 2.38198 10.9777 2.38198 10.6551 2.57079C10.5602 2.62647 10.4487 2.72931 10.0449 3.13311L9.45604 3.72094L11.7213 5.98617L12.3102 5.39833C12.7139 4.99457 12.8168 4.88307 12.8725 4.78818C13.0613 4.46561 13.0612 4.06585 12.8725 3.74326C12.8169 3.64827 12.7146 3.53752 12.3102 3.13311C11.9057 2.72863 11.795 2.6264 11.7 2.57079Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_think_outline_14 */
+export const IconThinkOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M7.06431 5.93342C7.68763 5.93342 8.19307 6.43904 8.19322 7.06233C8.19322 7.68573 7.68772 8.19123 7.06431 8.19123C6.44099 8.19113 5.9354 7.68567 5.9354 7.06233C5.93555 6.43911 6.44108 5.93353 7.06431 5.93342Z"
+ fill="currentColor"
+ />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M8.6815 0.963693C10.1169 0.447019 11.6266 0.374829 12.5633 1.31135C13.5 2.24805 13.4277 3.75776 12.911 5.19319C12.7126 5.74431 12.4386 6.31796 12.0965 6.89729C12.4969 7.54638 12.8141 8.19018 13.036 8.80647C13.5527 10.2419 13.6251 11.7516 12.6883 12.6883C11.7516 13.625 10.242 13.5527 8.8065 13.036C8.19022 12.8141 7.54641 12.4969 6.89732 12.0965C6.31797 12.4386 5.74435 12.7125 5.19322 12.911C3.75777 13.4276 2.2481 13.5 1.31138 12.5633C0.374859 11.6266 0.447049 10.1168 0.963724 8.68147C1.17185 8.10338 1.46321 7.50063 1.82896 6.8924C1.52182 6.35711 1.27235 5.82825 1.08872 5.31819C0.572068 3.88278 0.499714 2.37306 1.43638 1.43635C2.37308 0.499655 3.8828 0.572044 5.31822 1.08869C5.82828 1.27232 6.35715 1.5218 6.89243 1.82893C7.50066 1.46318 8.10341 1.17181 8.6815 0.963693ZM11.3573 8.01154C10.9083 8.62253 10.3901 9.22873 9.80943 9.8094C9.22877 10.3901 8.62255 10.9083 8.01158 11.3572C8.4257 11.5841 8.8287 11.7688 9.21275 11.9071C10.5456 12.3868 11.4246 12.2547 11.8397 11.8397C12.2548 11.4246 12.3869 10.5456 11.9071 9.21272C11.7688 8.82866 11.5841 8.42568 11.3573 8.01154ZM2.56529 8.02912C2.37344 8.39322 2.21495 8.74796 2.09263 9.08772C1.61291 10.4204 1.74512 11.2995 2.16001 11.7147C2.57505 12.1297 3.45415 12.2618 4.78697 11.7821C5.11057 11.6656 5.44786 11.5164 5.7938 11.3367C5.249 10.9223 4.70922 10.4533 4.19029 9.9344C3.57578 9.31987 3.03169 8.67633 2.56529 8.02912ZM6.90708 3.2469C6.24065 3.70479 5.5646 4.26321 4.91392 4.91389C4.26325 5.56456 3.70482 6.24063 3.24693 6.90705C3.72674 7.63325 4.32777 8.37459 5.03892 9.08576C5.64943 9.69627 6.28183 10.2265 6.90806 10.6678C7.59368 10.2025 8.2908 9.63076 8.96079 8.96076C9.6308 8.29075 10.2025 7.59366 10.6678 6.90803C10.2265 6.2818 9.69631 5.6494 9.08579 5.03889C8.37462 4.32773 7.63328 3.72672 6.90708 3.2469ZM11.7147 2.15998C11.2996 1.74509 10.4204 1.61288 9.08775 2.0926C8.74835 2.21479 8.39382 2.37271 8.03013 2.56428C8.67728 3.03065 9.31995 3.5758 9.93443 4.19026C10.4534 4.7092 10.9223 5.24896 11.3368 5.79377C11.5164 5.44785 11.6656 5.11052 11.7821 4.78694C12.2618 3.45416 12.1297 2.57502 11.7147 2.15998ZM4.91197 2.2176C3.57922 1.73788 2.70004 1.86995 2.28501 2.28498C1.87001 2.70003 1.73791 3.5792 2.21763 4.91194C2.31709 5.18822 2.44112 5.47427 2.58677 5.7674C3.01931 5.1887 3.51474 4.6158 4.06529 4.06526C4.61584 3.5147 5.18872 3.01928 5.76743 2.58674C5.47431 2.4411 5.18824 2.31706 4.91197 2.2176Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_think_outline_16 */
+export const IconThinkOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M8.00192 6.64454C8.75026 6.64454 9.35732 7.25169 9.35739 8.00001C9.35739 8.74838 8.7503 9.35548 8.00192 9.35548C7.25367 9.35533 6.64743 8.74829 6.64743 8.00001C6.6475 7.25178 7.25371 6.64468 8.00192 6.64454Z"
+ fill="currentColor"
+ />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M9.97165 1.29981C11.5853 0.718916 13.271 0.642197 14.3144 1.68555C15.3577 2.72902 15.2811 4.41466 14.7002 6.02833C14.4707 6.66561 14.1504 7.32937 13.75 8.00001C14.1504 8.67062 14.4707 9.33444 14.7002 9.97169C15.2811 11.5854 15.3578 13.271 14.3144 14.3145C13.271 15.3579 11.5854 15.2811 9.97165 14.7002C9.3344 14.4708 8.67059 14.1505 7.99997 13.75C7.32933 14.1505 6.66558 14.4708 6.02829 14.7002C4.41461 15.2811 2.72899 15.3578 1.68552 14.3145C0.642155 13.271 0.71887 11.5854 1.29977 9.97169C1.52915 9.33454 1.84865 8.67049 2.24899 8.00001C1.84866 7.32953 1.52915 6.66544 1.29977 6.02833C0.718852 4.41459 0.64207 2.729 1.68552 1.68555C2.72897 0.642112 4.41456 0.718887 6.02829 1.29981C6.66541 1.52918 7.32949 1.8487 7.99997 2.24903C8.67045 1.84869 9.33451 1.52919 9.97165 1.29981ZM12.9404 9.2129C12.4391 9.893 11.8616 10.5681 11.2148 11.2149C10.568 11.8616 9.89296 12.4391 9.21286 12.9404C9.62532 13.1579 10.0271 13.338 10.4121 13.4766C11.9146 14.0174 12.9172 13.8738 13.3955 13.3955C13.8737 12.9173 14.0174 11.9146 13.4765 10.4121C13.3379 10.0271 13.1578 9.62535 12.9404 9.2129ZM3.05856 9.2129C2.84121 9.62523 2.66197 10.0272 2.52341 10.4121C1.98252 11.9146 2.12627 12.9172 2.60446 13.3955C3.08278 13.8737 4.08544 14.0174 5.58786 13.4766C5.97264 13.338 6.37389 13.1577 6.7861 12.9404C6.10624 12.4393 5.43168 11.8614 4.78513 11.2149C4.13823 10.5679 3.55992 9.89313 3.05856 9.2129ZM7.99899 3.792C7.23179 4.31419 6.45306 4.95512 5.70407 5.70411C4.95509 6.45309 4.31415 7.23184 3.79196 7.99903C4.3143 8.76666 4.95471 9.54653 5.70407 10.2959C6.45309 11.0449 7.23271 11.6848 7.99997 12.207C8.76725 11.6848 9.54683 11.0449 10.2959 10.2959C11.0449 9.54686 11.6848 8.76729 12.207 8.00001C11.6848 7.23275 11.0449 6.45312 10.2959 5.70411C9.5465 4.95475 8.76662 4.31434 7.99899 3.792ZM5.58786 2.52344C4.08533 1.98255 3.08272 2.12625 2.60446 2.6045C2.12621 3.08275 1.98252 4.08536 2.52341 5.5879C2.66189 5.97253 2.8414 6.37409 3.05856 6.78614C3.55983 6.10611 4.1384 5.43189 4.78513 4.78516C5.43186 4.13843 6.10606 3.55987 6.7861 3.0586C6.37405 2.84144 5.97249 2.66192 5.58786 2.52344ZM13.3955 2.6045C12.9172 2.12631 11.9146 1.98257 10.4121 2.52344C10.0272 2.66201 9.62519 2.84125 9.21286 3.0586C9.8931 3.55996 10.5679 4.13827 11.2148 4.78516C11.8614 5.43172 12.4392 6.10627 12.9404 6.78614C13.1577 6.37393 13.338 5.97267 13.4765 5.5879C14.0174 4.08549 13.8736 3.08281 13.3955 2.6045Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_agent_preset_outline_16 (figma extract): node interiors knock out to transparency via mask, so the glyph sits on any fill. */
+export const IconAgentPresetOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <mask id="mask0_agent_preset_16" maskUnits="userSpaceOnUse" x="0" y="0" width="16" height="16">
+ <rect width="16" height="16" fill="white" />
+ <circle cx="7.9995" cy="3.28319" r="1.712" fill="black" />
+ <circle cx="3.51122" cy="11.3855" r="1.712" fill="black" />
+ <circle cx="12.4878" cy="11.3855" r="1.712" fill="black" />
+ </mask>
+ <path
+ mask="url(#mask0_agent_preset_16)"
+ d="M12.2881 11.0425C12.6002 11.3723 13.0413 11.5786 13.5312 11.5786L13.5342 11.5776C13.1476 12.3233 12.6119 12.9785 11.9639 13.5005C10.9327 14.3309 9.6199 14.8286 8.19336 14.8286C7.29864 14.8285 6.45056 14.6313 5.6875 14.2808C6.08309 14.0281 6.36707 13.6189 6.45215 13.1392C6.99022 13.3561 7.57767 13.476 8.19336 13.4761C9.30019 13.4761 10.3157 13.0915 11.1152 12.4478C11.5935 12.0626 11.9924 11.5848 12.2881 11.0425ZM4.14746 4.36475C4.25569 4.83228 4.55488 5.2247 4.95898 5.4585C4.07956 6.30639 3.53144 7.49605 3.53125 8.81396C3.53125 9.69534 3.77613 10.5202 4.20117 11.2231C3.74959 11.3817 3.38395 11.7232 3.19531 12.1597C2.5541 11.2032 2.17969 10.052 2.17969 8.81396C2.17989 7.05087 2.93868 5.4646 4.14746 4.36475ZM8.19336 2.80029C8.85717 2.80029 9.49784 2.90834 10.0967 3.10791C12.3237 3.85044 13.9725 5.86061 14.1846 8.28369C13.9832 8.20048 13.7627 8.15382 13.5312 8.15381C13.2802 8.15381 13.042 8.20907 12.8271 8.30615C12.6281 6.47264 11.3666 4.95616 9.66895 4.39014C9.2063 4.236 8.70989 4.15186 8.19336 4.15186C7.96112 4.15189 7.7329 4.16981 7.50977 4.20264C7.51947 4.12886 7.52637 4.05348 7.52637 3.97705C7.52628 3.56604 7.3811 3.18914 7.13965 2.89404C7.48183 2.83352 7.83381 2.80033 8.19336 2.80029Z"
+ fill="currentColor"
+ />
+ <path
+ d="M9.1123 3.28271C9.11205 2.66858 8.61322 2.17041 7.99902 2.17041C7.38504 2.17067 6.88697 2.66874 6.88672 3.28271C6.88672 3.89691 7.38489 4.39574 7.99902 4.396C8.61338 4.396 9.1123 3.89707 9.1123 3.28271ZM10.3115 3.28271C10.3115 4.55981 9.27612 5.59521 7.99902 5.59521C6.72214 5.59496 5.6875 4.55965 5.6875 3.28271C5.68776 2.00599 6.7223 0.971447 7.99902 0.971191C9.27596 0.971191 10.3113 2.00584 10.3115 3.28271Z"
+ fill="currentColor"
+ />
+ <path
+ d="M4.62402 11.385C4.62377 10.7709 4.12494 10.2727 3.51074 10.2727C2.89676 10.273 2.39869 10.771 2.39844 11.385C2.39844 11.9992 2.89661 12.498 3.51074 12.4983C4.1251 12.4983 4.62402 11.9994 4.62402 11.385ZM5.82324 11.385C5.82324 12.6621 4.78784 13.6975 3.51074 13.6975C2.23386 13.6973 1.19922 12.6619 1.19922 11.385C1.19947 10.1083 2.23402 9.07374 3.51074 9.07349C4.78768 9.07349 5.82299 10.1081 5.82324 11.385Z"
+ fill="currentColor"
+ />
+ <path
+ d="M13.6006 11.385C13.6003 10.7709 13.1015 10.2727 12.4873 10.2727C11.8733 10.273 11.3753 10.771 11.375 11.385C11.375 11.9992 11.8732 12.498 12.4873 12.4983C13.1017 12.4983 13.6006 11.9994 13.6006 11.385ZM14.7998 11.385C14.7998 12.6621 13.7644 13.6975 12.4873 13.6975C11.2104 13.6973 10.1758 12.6619 10.1758 11.385C10.176 10.1083 11.2106 9.07374 12.4873 9.07349C13.7642 9.07349 14.7995 10.1081 14.7998 11.385Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_browse_outline_16 */
+export const IconBrowseOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M11.2426 4.80473V6.10551H4.75819V4.80473H11.2426Z" fill="currentColor" />
+ <path d="M9.40858 7.84478V9.14557H4.75819V7.84478H9.40858Z" fill="currentColor" />
+ <path
+ d="M9.23438 0.546389C10.1941 0.546389 10.9683 0.544914 11.5859 0.611819C12.2161 0.680096 12.7634 0.825745 13.2393 1.17139C13.5172 1.3733 13.7619 1.61812 13.9639 1.896C14.3096 2.37183 14.4551 2.91922 14.5234 3.54932C14.5903 4.16686 14.5889 4.94133 14.5889 5.90088V10.0981C14.5889 11.0576 14.5903 11.8321 14.5234 12.4497C14.4552 13.0798 14.3094 13.6272 13.9639 14.103C13.7619 14.381 13.5172 14.6257 13.2393 14.8276C12.7633 15.1734 12.2163 15.3189 11.5859 15.3872C10.9683 15.4541 10.1942 15.4536 9.23438 15.4536H6.76563C5.80591 15.4536 5.03168 15.4541 4.41407 15.3872C3.78385 15.3189 3.23665 15.1734 2.76074 14.8276C2.48291 14.6257 2.23802 14.3809 2.03614 14.103C1.69066 13.6272 1.54483 13.0798 1.47657 12.4497C1.40973 11.8321 1.41114 11.0576 1.41114 10.0981V5.90088C1.41113 4.94132 1.40966 4.16686 1.47657 3.54932C1.54488 2.91921 1.69042 2.37184 2.03614 1.896C2.2381 1.61807 2.4828 1.37333 2.76074 1.17139C3.23665 0.825682 3.78386 0.680109 4.41407 0.611819C5.03168 0.544905 5.80591 0.546389 6.76563 0.546389H9.23438ZM6.76563 1.896C5.77586 1.896 5.0876 1.89738 4.55957 1.95459C4.0443 2.01043 3.76214 2.11349 3.55469 2.26416C3.39135 2.38284 3.24761 2.52662 3.12891 2.68994C2.97821 2.89736 2.8752 3.17967 2.81934 3.69483C2.76214 4.22279 2.76075 4.91131 2.76074 5.90088V10.0981C2.76074 11.0876 2.76221 11.7762 2.81934 12.3042C2.87516 12.8194 2.97829 13.1026 3.12891 13.3101C3.24754 13.4733 3.39147 13.6172 3.55469 13.7358C3.76213 13.8865 4.04438 13.9896 4.55957 14.0454C5.0876 14.1026 5.77586 14.103 6.76563 14.103H9.23438C10.2242 14.103 10.9124 14.1026 11.4404 14.0454C11.9556 13.9896 12.2379 13.8865 12.4453 13.7358C12.6086 13.6172 12.7525 13.4733 12.8711 13.3101C13.0217 13.1026 13.1248 12.8195 13.1807 12.3042C13.2378 11.7762 13.2393 11.0876 13.2393 10.0981V5.90088C13.2393 4.91131 13.2379 4.22279 13.1807 3.69483C13.1248 3.17969 13.0218 2.89736 12.8711 2.68994C12.7524 2.52667 12.6086 2.38281 12.4453 2.26416C12.2379 2.11355 11.9556 2.01041 11.4404 1.95459C10.9124 1.8974 10.2241 1.896 9.23438 1.896H6.76563Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_link_outline_14 */
+export const IconLinkOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M8.19727 5.86969C9.2092 6.90067 9.20969 8.55271 8.19727 9.58338L6.88871 10.8919C5.85801 11.9039 4.20584 11.9037 3.17502 10.8919L3.10873 10.8243C2.09622 9.7934 2.09626 8.14148 3.10873 7.11058L4.36757 5.85174C4.28261 6.33758 4.30355 6.84354 4.44077 7.33362L3.89249 7.88053C3.30043 8.48348 3.30108 9.4507 3.89318 10.0536L3.94566 10.1061C4.54861 10.698 5.51521 10.6981 6.11808 10.1061L7.41283 8.81275C8.00484 8.21002 8.00504 7.24267 7.41352 6.63964L7.35966 6.58716C7.21975 6.44976 7.05995 6.34434 6.89009 6.27089L7.70009 5.4609C7.85176 5.55768 7.99607 5.67091 8.1296 5.80202L8.19727 5.86969Z"
+ fill="currentColor"
+ />
+ <path
+ d="M5.80913 8.12648C4.79584 7.09547 4.79591 5.44245 5.80913 4.41141C5.81733 4.40304 5.82707 4.39209 5.8409 4.37826L7.07833 3.14082C7.09224 3.12693 7.10311 3.11729 7.11148 3.10906C8.14253 2.09591 9.79557 2.09579 10.8266 3.10906L10.8908 3.17328C11.9041 4.20425 11.9039 5.85727 10.8908 6.88835L9.63193 8.14581C9.70566 7.66581 9.67564 7.16895 9.53456 6.68948L10.1063 6.11772C10.6989 5.51458 10.6992 4.54691 10.1063 3.94391L10.0552 3.8942C9.45215 3.30157 8.48446 3.30151 7.88142 3.8942L6.59358 5.18204C6.00081 5.78507 6.00092 6.75274 6.59358 7.35584L6.6433 7.40694C6.77998 7.54132 6.93555 7.64528 7.10112 7.71837L6.29251 8.52699C6.14446 8.43127 6.00395 8.31906 5.87335 8.1907L5.80913 8.12648Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_link_outline_16 */
+export const IconLinkOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M9.94133 6.50173C11.3218 7.99603 11.3218 10.3011 9.94128 11.7954C9.88691 11.8542 9.82125 11.9196 9.72099 12.0198L7.75707 13.9838C7.65709 14.0838 7.592 14.1491 7.53334 14.2034C6.03906 15.5843 3.7327 15.5854 2.23827 14.2048C2.17933 14.1503 2.11374 14.0844 2.01315 13.9838C1.91318 13.8839 1.84922 13.8188 1.79495 13.7601C0.413857 12.2657 0.413909 9.95948 1.795 8.46503C1.84923 8.4064 1.91335 8.34115 2.01321 8.24129L3.79275 6.46313C3.71814 7.08101 3.75236 7.71445 3.90115 8.33518L3.00344 9.23151C2.89398 9.34097 2.8535 9.38307 2.82251 9.41658C1.93771 10.3744 1.93704 11.8514 2.82179 12.8092C2.85279 12.8427 2.89383 12.884 3.0034 12.9936C3.11272 13.1029 3.15429 13.1442 3.18777 13.1752C4.14561 14.0603 5.62381 14.0608 6.58178 13.1758C6.61532 13.1448 6.65722 13.1032 6.76685 12.9935L8.73077 11.0296C8.83999 10.9204 8.88142 10.8787 8.91238 10.8452C9.79744 9.88728 9.7969 8.40911 8.91173 7.45124C8.88074 7.41775 8.83944 7.3762 8.73011 7.26687C8.62082 7.15757 8.58061 7.11623 8.54712 7.08526C8.37347 6.92477 8.18243 6.79361 7.98088 6.69165L9.00289 5.66964C9.17506 5.78373 9.34035 5.91265 9.49663 6.05703C9.55538 6.11135 9.62026 6.17652 9.72036 6.27662C9.82094 6.3772 9.88686 6.4428 9.94133 6.50173Z"
+ fill="currentColor"
+ />
+ <path
+ d="M6.06816 9.49196C4.68626 7.99724 4.68667 5.68942 6.06885 4.19487C6.12268 4.13671 6.18789 4.07306 6.28706 3.9739L8.24541 2.01416C8.34478 1.91479 8.41018 1.85055 8.46845 1.79665C9.96301 0.414902 12.2689 0.414922 13.7635 1.79665C13.8217 1.85051 13.8866 1.91559 13.9858 2.01486C14.0849 2.11394 14.1502 2.17769 14.204 2.23583C15.5861 3.7304 15.5866 6.03823 14.2047 7.53291C14.1508 7.59125 14.0854 7.65638 13.9858 7.75595L12.1994 9.54098C12.2614 8.92982 12.2185 8.30587 12.0634 7.69657L12.9956 6.76573C13.1044 6.65692 13.1458 6.61529 13.1765 6.58205C14.0621 5.62404 14.0621 4.1454 13.1765 3.18738C13.1458 3.15419 13.104 3.1135 12.9956 3.00508C12.8877 2.89716 12.8471 2.85551 12.814 2.82485C11.8559 1.9389 10.376 1.93886 9.41794 2.82485C9.38479 2.85554 9.34381 2.89622 9.23564 3.00439L7.27728 4.96413C7.16875 5.07265 7.12708 5.11322 7.09636 5.14643C6.21074 6.10441 6.21153 7.58236 7.09705 8.5404C7.12775 8.57357 7.16826 8.61575 7.27659 8.72408C7.38456 8.83205 7.42647 8.87227 7.45958 8.90293C7.62849 9.0591 7.81309 9.1881 8.00856 9.28894L6.98795 10.3095C6.82111 10.1978 6.66052 10.0715 6.50872 9.93114C6.45057 9.87733 6.38547 9.81341 6.28637 9.71431C6.1871 9.61504 6.12202 9.55018 6.06816 9.49196Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_right_up_outline_14 */
+export const IconRightUpOutline14 = ({ size = 8, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 8 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M6.54199 8.62824C6.54199 8.44193 6.54146 8.28829 6.53906 8.15851L1.11719 13.5814L0.728516 13.1927L0.339844 12.803L5.76172 7.38019C5.63201 7.3778 5.47812 7.37824 5.29199 7.37824H1.43555V6.27863H5.29199C5.65471 6.27863 5.97167 6.27814 6.22852 6.30597C6.49541 6.33493 6.76232 6.3998 7.00293 6.57452C7.13452 6.67013 7.25108 6.78571 7.34668 6.9173C7.52157 7.15808 7.5863 7.4256 7.61523 7.69269C7.64305 7.94948 7.64258 8.26562 7.64258 8.62824V12.4857H6.54199V8.62824Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_right_up_outline_16 */
+export const IconRightUpOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M13.588429 5.147807C13.588429 4.739638 13.587271 4.403003 13.582013 4.118684L1.703098 15.99968L0.85155 15.148178L0 14.294485L11.878915 2.413442C11.594721 2.408199 11.257569 2.409154 10.849776 2.409154H2.400594V0.000001H10.849776C11.644471 0.000001 12.338899 -0.001059 12.901622 0.059909C13.486363 0.123352 14.071136 0.265493 14.598303 0.648292C14.886598 0.857751 15.141981 1.110984 15.351433 1.399281C15.734578 1.926807 15.876362 2.512925 15.939743 3.098105C16.000775 3.660718 15.99968 4.353347 15.99968 5.147807V13.599133H13.588429V5.147807Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_enhance_outline_16 */
+export const IconEnhanceOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M14.9943 1.92389V3.32428H1.00598V1.92389H14.9943Z" fill="currentColor" />
+ <path d="M14.9943 5.50784V6.90823H1.00598V5.50784H14.9943Z" fill="currentColor" />
+ <path d="M14.9943 9.09177V10.4922H1.00598V9.09177H14.9943Z" fill="currentColor" />
+ <path d="M8.93274 12.6757V14.0761H1.00598V12.6757H8.93274Z" fill="currentColor" />
+ </svg>
+)
+
+/** ic_ds_trash_outline_16 */
+export const IconTrashOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M14.4782 4.84067L14.2138 10.1152C14.1102 12.1872 14.067 13.0115 13.3866 13.9607C13.1044 14.3546 12.7498 14.6912 12.3424 14.9535C11.8239 15.2872 11.2415 15.4316 10.5585 15.4998C9.88727 15.5668 9.04946 15.5656 7.99998 15.5656C6.95051 15.5656 6.1127 15.5668 5.44142 15.4998C4.75851 15.4316 4.17602 15.2872 3.65753 14.9535C3.25012 14.6912 2.89559 14.3546 2.61332 13.9607C1.93296 13.0115 1.88979 12.1872 1.78619 10.1152L1.52179 4.84067L2.89006 4.77277L3.15343 10.0463C3.26221 12.2218 3.32452 12.6015 3.72646 13.1624C3.90825 13.4161 4.13686 13.6334 4.39927 13.8023C4.66204 13.9714 5.00263 14.0792 5.57825 14.1367C6.16562 14.1953 6.92298 14.1963 7.99998 14.1963C9.07699 14.1963 9.83434 14.1953 10.4217 14.1367C10.9973 14.0792 11.3379 13.9714 11.6007 13.8023C11.8631 13.6334 12.0917 13.4161 12.2735 13.1624C12.6755 12.6015 12.7378 12.2218 12.8465 10.0463L13.1099 4.77277L14.4782 4.84067ZM5.43011 6.22849H6.7994V11.3909H5.43011V6.22849ZM9.20056 6.22849H10.5699V11.3909H9.20056V6.22849ZM8.53597 0.434431C9.17976 0.434431 9.6522 0.426926 10.0966 0.571258C10.2357 0.616451 10.3717 0.672554 10.502 0.738948C10.9182 0.951107 11.2464 1.29099 11.7015 1.74612L12.4978 2.54136H15.3742V3.91169H0.625732V2.54136H3.50218L4.29845 1.74612C4.75358 1.29099 5.08174 0.951107 5.49801 0.738948C5.62831 0.672554 5.76425 0.616451 5.90334 0.571258C6.34776 0.426926 6.82021 0.434431 7.46399 0.434431H8.53597ZM7.46399 1.80476C6.73208 1.80476 6.51641 1.81187 6.32617 1.87369C6.25545 1.89667 6.18668 1.92533 6.12041 1.95907C5.96398 2.03878 5.82348 2.16253 5.44142 2.54136H10.5585C10.1765 2.16253 10.036 2.03878 9.87955 1.95907C9.81329 1.92533 9.74452 1.89667 9.6738 1.87369C9.48356 1.81187 9.26789 1.80476 8.53597 1.80476H7.46399Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_warning_outline_16 */
+export const IconWarningOutline16 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M6.3002 3.32843L7.69986 3.32843L7.69986 7.79657H6.3002L6.3002 3.32843Z"
+ fill="currentColor"
+ />
+ <path d="M6.3002 9.01935H7.69986V10.6711H6.3002V9.01935Z" fill="currentColor" />
+ <path
+ d="M12.6328 6.99976C12.6328 3.88874 10.111 1.36694 7 1.36694C3.88899 1.36695 1.3672 3.88875 1.36719 6.99976C1.36719 10.1108 3.88899 12.6326 7 12.6326C10.111 12.6326 12.6328 10.1108 12.6328 6.99976ZM13.8582 6.99976C13.8582 10.7873 10.7876 13.8579 7 13.8579C3.21244 13.8579 0.141846 10.7873 0.141846 6.99976C0.141857 3.2122 3.21245 0.141612 7 0.141602C10.7876 0.141602 13.8581 3.21219 13.8582 6.99976Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_user_outline_16 */
+export const IconUserOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M11.0307 5.46369C11.0305 3.78995 9.6734 2.43357 7.99961 2.43357C6.32601 2.43379 4.96972 3.79009 4.96949 5.46369C4.96949 7.13748 6.32587 8.49455 7.99961 8.49477C9.67354 8.49477 11.0307 7.13762 11.0307 5.46369ZM12.3163 5.46369C12.3163 7.84777 10.3837 9.78042 7.99961 9.78042C5.61572 9.7802 3.68288 7.84763 3.68288 5.46369C3.6831 3.07993 5.61586 1.14718 7.99961 1.14695C10.3836 1.14695 12.3161 3.0798 12.3163 5.46369Z"
+ fill="currentColor"
+ />
+ <path
+ d="M8.00002 10.3316C11.7343 10.3316 14.1864 11.8997 15.0387 14.4445L14.4292 14.6483L13.8197 14.8531C13.1955 12.9893 11.3673 11.6182 8.00002 11.6182C4.63277 11.6182 2.80455 12.9893 2.18031 14.8531L1.5708 14.6483L0.961304 14.4445C1.81368 11.8997 4.26579 10.3316 8.00002 10.3316Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_send_outline_16 */
+export const IconSendOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M8.3125 0.981587C8.66767 1.0545 8.97902 1.20558 9.2627 1.43374C9.48724 1.61438 9.73029 1.85933 9.97949 2.10854L14.707 6.83608L13.293 8.25014L9 3.95717V15.0431H7V3.95717L2.70703 8.25014L1.29297 6.83608L6.02051 2.10854C6.26971 1.85933 6.51277 1.61438 6.7373 1.43374C6.97662 1.24126 7.28445 1.04542 7.6875 0.981587C7.8973 0.94841 8.1031 0.956564 8.3125 0.981587Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_stop_fill_16 */
+export const IconStopFill16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M2 4.88C2 3.68009 2 3.08013 2.30557 2.65954C2.40426 2.52371 2.52371 2.40426 2.65954 2.30557C3.08013 2 3.68009 2 4.88 2H11.12C12.3199 2 12.9199 2 13.3405 2.30557C13.4763 2.40426 13.5957 2.52371 13.6944 2.65954C14 3.08013 14 3.68009 14 4.88V11.12C14 12.3199 14 12.9199 13.6944 13.3405C13.5957 13.4763 13.4763 13.5957 13.3405 13.6944C12.9199 14 12.3199 14 11.12 14H4.88C3.68009 14 3.08013 14 2.65954 13.6944C2.52371 13.5957 2.40426 13.4763 2.30557 13.3405C2 12.9199 2 12.3199 2 11.12V4.88Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_paperclip_outline_16 */
+export const IconPaperclipOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M5.5498 9.75V5H6.9502V9.75C6.9502 10.3299 7.4201 10.7998 8 10.7998C8.5799 10.7998 9.0498 10.3299 9.0498 9.75V4.5C9.0498 2.9536 7.7964 1.7002 6.25 1.7002C4.7036 1.7002 3.4502 2.9536 3.4502 4.5V9.75C3.4502 12.2629 5.4871 14.2998 8 14.2998C10.5129 14.2998 12.5498 12.2629 12.5498 9.75V4H13.9502V9.75C13.9502 13.0361 11.2861 15.7002 8 15.7002C4.71391 15.7002 2.0498 13.0361 2.0498 9.75V4.5C2.04981 2.1804 3.9304 0.299806 6.25 0.299805C8.5696 0.299805 10.4502 2.1804 10.4502 4.5V9.75C10.4502 11.1031 9.3531 12.2002 8 12.2002C6.6469 12.2002 5.5498 11.1031 5.5498 9.75Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_loading_outline_16 */
+export const IconLoadingOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M2.871 13.1286C0.0387669 10.2962 0.0387669 5.70383 2.871 2.87141C5.70341 0.0390029 10.2957 0.0391154 13.1282 2.87141L12.1387 3.86094C9.85292 1.57538 6.1469 1.57596 3.86123 3.86163C1.57573 6.14732 1.57573 9.85269 3.86123 12.1384C6.1469 14.424 9.85292 14.4246 12.1387 12.1391L13.1282 13.1286C10.2957 15.9609 5.70341 15.961 2.871 13.1286Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_download_outline_16 */
+export const IconDownloadOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M15.3695 11.411L15.1234 12.8866C14.8869 14.3042 13.6603 15.3436 12.223 15.3436H3.77673C2.33958 15.3434 1.1128 14.3042 0.876343 12.8866L0.630249 11.411L2.05408 11.1747L2.29919 12.6493C2.41973 13.3713 3.04475 13.9001 3.77673 13.9003H12.223C12.9551 13.9002 13.58 13.3713 13.7006 12.6493L13.9457 11.1747L15.3695 11.411ZM8.72205 8.994C8.77717 8.93934 8.83792 8.88106 8.90271 8.81627L12.4828 5.23424L13.5043 6.25572L9.92224 9.8358C9.6395 10.1185 9.38763 10.3732 9.15857 10.5575C8.91892 10.7503 8.63953 10.9224 8.2865 10.9784C8.09711 11.0083 7.90363 11.0083 7.71423 10.9784C7.36106 10.9224 7.0809 10.7503 6.84119 10.5575C6.61215 10.3732 6.36022 10.1185 6.07751 9.8358L2.49646 6.25572L3.51697 5.23424L7.09705 8.81627C7.16219 8.88142 7.22331 8.94006 7.27869 8.99498V1.3065H8.72205V8.994Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_play_outline_16 */
+export const IconPlayOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M14.1446 8C14.1446 4.6062 11.3938 1.85539 8 1.85539C4.6062 1.85539 1.85539 4.6062 1.85539 8C1.85539 11.3938 4.6062 14.1446 8 14.1446C11.3938 14.1446 14.1446 11.3938 14.1446 8ZM15.511 8C15.511 12.148 12.148 15.511 8 15.511C3.85202 15.511 0.489014 12.148 0.489014 8C0.489014 3.85202 3.85202 0.489014 8 0.489014C12.148 0.489014 15.511 3.85202 15.511 8Z"
+ fill="currentColor"
+ />
+ <path
+ d="M10.5617 8.42578C10.852 8.21614 10.852 7.78386 10.5617 7.57422L7.25708 5.18751C6.90974 4.93666 6.42436 5.18484 6.42436 5.61329V10.3867C6.42436 10.8152 6.90974 11.0633 7.25708 10.8125L10.5617 8.42578Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_pause_outline_16 */
+export const IconPauseOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M14.1448 8.00024C14.1448 4.60644 11.394 1.85563 8.00024 1.85563C4.60644 1.85563 1.85563 4.60644 1.85563 8.00024C1.85563 11.394 4.60644 14.1448 8.00024 14.1448C11.394 14.1448 14.1448 11.394 14.1448 8.00024ZM15.5112 8.00024C15.5112 12.1482 12.1482 15.5112 8.00024 15.5112C3.85226 15.5112 0.489258 12.1482 0.489258 8.00024C0.489258 3.85226 3.85226 0.489258 8.00024 0.489258C12.1482 0.489258 15.5112 3.85226 15.5112 8.00024Z"
+ fill="currentColor"
+ />
+ <path d="M7.14244 5.14258V10.8569H5.71387V5.14258H7.14244Z" fill="currentColor" />
+ <path d="M10.286 5.14258V10.8569H8.85742V5.14258H10.286Z" fill="currentColor" />
+ </svg>
+)
+
+/** ic_ds_fullscreen_outline_16 */
+export const IconFullscreenOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M2.58875 12.3407L6.59167 8.33777L7.66296 9.40808L3.66003 13.411H7.99988V14.8065H3.05457C2.02633 14.8065 1.19324 13.9734 1.19324 12.9452V7.99988H2.58875V12.3407Z"
+ fill="currentColor"
+ />
+ <path
+ d="M12.9452 1.19324C13.9734 1.19324 14.8065 2.02633 14.8065 3.05457V7.99988H13.411V3.66003L9.40808 7.66296L8.33777 6.59167L12.3407 2.58875H7.99988V1.19324H12.9452Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_code_outline_16 */
+export const IconCodeOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M12.3368 1.53569L11.931 4.43172H14.8086V5.79673H11.7404L11.1962 9.67859H14.2839V11.0436H11.0056L10.4994 14.6529L9.14873 14.4643L9.62731 11.0436H5.75876L5.25252 14.6529L3.90186 14.4643L4.38043 11.0436H1.69141V9.67859H4.57104L5.11417 5.79673H2.21609V4.43172H5.30581L5.73724 1.34713L7.08995 1.53569L6.68414 4.43172H10.5527L10.9841 1.34713L12.3368 1.53569ZM5.94937 9.67859H9.81791L10.361 5.79673H6.49353L5.94937 9.67859Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_cordis_plugin_outline_14 */
+export const IconCordisPluginOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <g clipPath="url(#clip0_1840_45990)">
+ <path
+ d="M3.03426 5.66661L1.70084 7.00003L3.0315 8.33069L2.14762 9.21457L-0.0669245 7.00003L2.15038 4.78273L3.03426 5.66661ZM7 14.067L4.77924 11.8462L5.66313 10.9623L7 12.2992L8.33342 10.9658L9.2173 11.8496L7 14.067ZM11.8489 9.21803L10.965 8.33414L12.2992 7.00003L10.9623 5.66316L11.8462 4.77927L14.0669 7.00003L11.8489 9.21803ZM8.33066 3.03153L7 1.70087L5.66589 3.03498L4.782 2.1511L7 -0.0668945L9.21454 2.14765L8.33066 3.03153Z"
+ fill="currentColor"
+ />
+ <rect x="5.98535" y="5.98535" width="2.02942" height="2.02942" fill="currentColor" />
+ </g>
+ <defs>
+ <clipPath id="clip0_1840_45990">
+ <rect width="14" height="14" fill="currentColor" />
+ </clipPath>
+ </defs>
+ </svg>
+)
+
+/** ic_ds_api_outline (figma extract) */
+export const IconApiOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none">
+ <path transform="translate(0.6689 1.073)" d="M11.4818 5.57813C11.4818 4.45301 11.4807 3.66237 11.4075 3.05908C11.3359 2.46953 11.2024 2.13852 10.9939 1.89441C10.9247 1.81341 10.8493 1.73801 10.7683 1.66882C10.5242 1.46033 10.1932 1.32686 9.60364 1.25525C9.00034 1.18198 8.20974 1.18091 7.0846 1.18091L5.57813 1.18091C4.45301 1.18091 3.66238 1.18198 3.05908 1.25525C2.46953 1.32686 2.13852 1.46033 1.89441 1.66882C1.81341 1.73801 1.73801 1.81341 1.66882 1.89441C1.46033 2.13852 1.32686 2.46953 1.25525 3.05908C1.18198 3.66238 1.18091 4.45301 1.18091 5.57813L1.18091 6.2771C1.18091 7.40218 1.18197 8.19288 1.25525 8.79614C1.32687 9.38553 1.46036 9.71674 1.66882 9.96082C1.73797 10.0417 1.81347 10.1173 1.89441 10.1864C2.13851 10.3948 2.46965 10.5275 3.05908 10.5991C3.66238 10.6724 4.45298 10.6735 5.57813 10.6735L7.0846 10.6735C8.20977 10.6735 9.00033 10.6724 9.60364 10.5991C10.1931 10.5275 10.5242 10.3948 10.7683 10.1864C10.8493 10.1173 10.9247 10.0417 10.9939 9.96082C11.2024 9.71674 11.3358 9.38553 11.4075 8.79614C11.4808 8.19288 11.4818 7.40218 11.4818 6.2771L11.4818 5.57813ZM12.6627 6.2771C12.6627 7.37222 12.6637 8.247 12.5798 8.93799C12.4942 9.64284 12.3133 10.2359 11.8928 10.7282C11.7834 10.8562 11.6637 10.9751 11.5356 11.0845C11.0434 11.5049 10.4511 11.6867 9.74634 11.7723C9.05525 11.8563 8.17999 11.8552 7.0846 11.8552L5.57813 11.8552C4.48273 11.8552 3.60747 11.8563 2.91638 11.7723C2.21157 11.6867 1.61933 11.5049 1.12708 11.0845C0.99901 10.9751 0.879281 10.8562 0.769898 10.7282C0.349454 10.2359 0.168506 9.64284 0.0828864 8.93799C-0.00101964 8.247 4.88512e-07 7.37222 6.47206e-07 6.2771L6.47206e-07 5.57813C6.47206e-07 4.48273 -0.00106163 3.60747 0.0828864 2.91638C0.168502 2.21168 0.349594 1.61928 0.769898 1.12708C0.879302 0.998981 0.998981 0.879302 1.12708 0.769898C1.61928 0.349594 2.21168 0.168502 2.91638 0.0828864C3.60747 -0.00106163 4.48273 6.47206e-07 5.57813 6.47206e-07L7.0846 6.47206e-07C8.17999 6.47206e-07 9.05525 -0.00106163 9.74634 0.0828864C10.451 0.168505 11.0434 0.349587 11.5356 0.769898C11.6637 0.879302 11.7834 0.998981 11.8928 1.12708C12.3131 1.61928 12.4942 2.21169 12.5798 2.91638C12.6638 3.60747 12.6627 4.48273 12.6627 5.57813L12.6627 6.2771Z" fill="currentColor"/>
+ <path transform="translate(0.6689 1.073)" d="M6.02607 5.50955L6.44306 5.9274L3.84284 8.52762L3.425 8.11063L3.00715 7.69278L4.77253 5.9274L3.00715 4.16202L3.84284 3.32633L6.02607 5.50955Z" fill="currentColor"/>
+ <path transform="translate(0.6689 1.073)" d="M9.23789 7.35397L9.23789 8.53488L6.96238 8.53488L6.96238 7.35397L9.23789 7.35397Z" fill="currentColor"/>
+ </svg>
+)
+
+/** ic_ds_personalization_outline_16 (figma extract) */
+export const IconPersonalizationOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none">
+ <path transform="translate(1.292 1.3)" d="M10.3232 9.18164C11.2868 9.18164 12.0985 9.82833 12.3506 10.7109L13.415 10.7109L13.415 11.8711L12.3496 11.8711C12.0971 12.7532 11.2864 13.3994 10.3232 13.3994C9.36031 13.3992 8.55012 12.7531 8.29785 11.8711L0 11.8711L0 10.7109L8.29688 10.7109C8.54876 9.82845 9.35988 9.18186 10.3232 9.18164ZM10.3232 10.3418C9.7999 10.3421 9.37534 10.7667 9.375 11.29C9.375 11.8137 9.79969 12.239 10.3232 12.2393C10.847 12.2393 11.2725 11.8138 11.2725 11.29C11.2721 10.7666 10.8468 10.3418 10.3232 10.3418ZM12.4326 11.291C12.4326 11.3549 12.4284 11.418 12.4229 11.4805C12.4287 11.4181 12.4326 11.355 12.4326 11.291ZM8.21484 11.2832C8.21484 11.2856 8.21484 11.2886 8.21484 11.291L8.21484 11.29C8.21484 11.2878 8.21484 11.2855 8.21484 11.2832ZM3.08301 4.59082C4.04605 4.59095 4.85696 5.23717 5.10938 6.11914L13.415 6.11914L13.415 7.2793L5.11035 7.2793C4.85833 8.16202 4.04648 8.80846 3.08301 8.80859C2.11972 8.80843 1.30963 8.16179 1.05762 7.2793L0 7.2793L0 6.11914L1.05762 6.11914C1.30994 5.23728 2.12006 4.59098 3.08301 4.59082ZM3.08301 5.75098C2.55962 5.75117 2.13512 6.17587 2.13477 6.69922C2.13477 7.22287 2.5594 7.64824 3.08301 7.64844C3.60665 7.64828 4.03223 7.2229 4.03223 6.69922C4.03187 6.17585 3.60643 5.75113 3.08301 5.75098ZM5.19238 6.69922C5.19238 6.763 5.18816 6.82633 5.18262 6.88867C5.18846 6.82629 5.19238 6.76313 5.19238 6.69922C5.19236 6.63495 5.18853 6.57152 5.18262 6.50879C5.18826 6.57154 5.19236 6.635 5.19238 6.69922ZM0.982422 6.52344C0.977382 6.58136 0.97463 6.63999 0.974609 6.69922C0.974609 6.75775 0.977496 6.81579 0.982422 6.87305C0.977758 6.81579 0.974609 6.75767 0.974609 6.69922C0.974628 6.64 0.977618 6.58142 0.982422 6.52344ZM10.3232 0C11.2869 0 12.0986 0.646596 12.3506 1.5293L13.415 1.5293L13.415 2.68945L12.3496 2.68945C12.363 2.64266 12.3754 2.59488 12.3857 2.54688C12.1838 3.50118 11.3376 4.21777 10.3232 4.21777C9.36037 4.21756 8.55018 3.57139 8.29785 2.68945L0 2.68945L0 1.5293L8.29688 1.5293C8.5487 0.646717 9.35981 0.00021854 10.3232 0ZM10.3232 1.16016C9.79984 1.16042 9.37524 1.58499 9.375 2.1084C9.375 2.63201 9.79969 3.05735 10.3232 3.05762C10.847 3.05762 11.2725 2.63217 11.2725 2.1084C11.2722 1.58483 10.8469 1.16016 10.3232 1.16016ZM12.4229 2.29883C12.4287 2.23641 12.4326 2.17331 12.4326 2.10938C12.4326 2.17327 12.4284 2.23638 12.4229 2.29883ZM8.21484 2.10938L8.21484 2.1084L8.21484 2.10938ZM8.22266 1.93359C8.21785 1.98897 8.21506 2.04499 8.21484 2.10156C8.21503 2.04501 8.2181 1.98902 8.22266 1.93359ZM8.22266 11.1162C8.2179 11.1713 8.21507 11.227 8.21484 11.2832C8.21504 11.227 8.21814 11.1713 8.22266 11.1162Z" fill="currentColor"/>
+ </svg>
+)
+
+/** ic_ds_project_add_outline_16 (figma extract) */
+export const IconProjectAddOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none">
+ <path transform="translate(9.52 2.52)" d="M3.55246 0L3.55246 2.44252L6 2.44252L6 3.55748L3.55246 3.55748L3.55246 6L2.43834 6L2.43834 3.55748L0 3.55748L0 2.44252L2.43834 2.44252L2.43834 0L3.55246 0Z" fill="currentColor"/>
+ <path transform="translate(0.3496 2.35)" d="M4.76367 0C5.36861 1.80598e-05 5.93113 0.310294 6.25488 0.821289L6.78027 1.64941C6.79685 1.67558 6.81791 1.69775 6.83887 1.71973C6.72186 2.15521 6.65702 2.61192 6.65137 3.08301C6.25601 2.96045 5.90909 2.70478 5.68164 2.3457L5.15723 1.5166C5.07183 1.38189 4.92318 1.3008 4.76367 1.30078L2.32422 1.30078C1.7589 1.30078 1.30078 1.7589 1.30078 2.32422L1.30078 10.1338C1.30078 10.6991 1.7589 11.1572 2.32422 11.1572L11.9766 11.1572C12.5419 11.1572 13 10.6991 13 10.1338L13 8.58398C13.4545 8.5135 13.8903 8.38748 14.3008 8.21289L14.3008 10.1338C14.3008 11.4171 13.2598 12.458 11.9766 12.458L2.32422 12.458C1.04093 12.458 0 11.4171 0 10.1338L0 2.32422C0 1.04093 1.04093 0 2.32422 0L4.76367 0Z" fill="currentColor"/>
+ </svg>
+)
+
+/**
+ * folder_open_16, outline layer only: the duotone original above reads a rung
+ * heavier than the …Outline16 family, so an icon-button row mixing them looks
+ * mismatched — this is the same geometry without the 20%-opacity inner fill.
+ */
+export const IconFolderOpenOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none">
+ <path d="M5.19629 1.57104C5.81144 1.5711 6.38623 1.8786 6.72754 2.39038L7.19922 3.09839C7.28454 3.22635 7.42824 3.30344 7.58203 3.30347H12.1699C13.5039 3.30348 14.5859 4.38548 14.5859 5.71948V6.62671C15.2694 7.02689 15.6605 7.85012 15.4385 8.68726L14.3848 12.658C14.1037 13.7164 13.1449 14.4527 12.0498 14.4529H2.91699C1.51651 14.4529 0.451662 13.2814 0.501954 11.9519V3.98706C0.501954 2.65305 1.58396 1.57104 2.91797 1.57104H5.19629ZM3.7793 7.75562C3.30994 7.75562 2.89883 8.07153 2.77832 8.52515L1.91602 11.7722C1.74167 12.4291 2.23734 13.073 2.91699 13.073H12.0498C12.5191 13.0728 12.9304 12.757 13.0508 12.3035L14.1045 8.33374C14.1819 8.04202 13.9619 7.756 13.6602 7.75562H3.7793ZM2.91797 2.9519C2.34625 2.9519 1.88281 3.41534 1.88281 3.98706V7.2937C2.33068 6.7269 3.02249 6.37476 3.7793 6.37476H13.2051V5.71948C13.2051 5.14777 12.7416 4.68434 12.1699 4.68433H7.58203C6.96675 4.6843 6.39209 4.37595 6.05078 3.86401L5.5791 3.15601C5.49379 3.02821 5.34995 2.95196 5.19629 2.9519H2.91797Z" fill="currentColor"/>
+ </svg>
+)
+
+/** folder_open_16 (figma extract): outline at full ink + 20%-opacity inner fill riding the same currentColor. */
+export const IconFolderOpen16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none">
+ <path d="M5.19629 1.57104C5.81144 1.5711 6.38623 1.8786 6.72754 2.39038L7.19922 3.09839C7.28454 3.22635 7.42824 3.30344 7.58203 3.30347H12.1699C13.5039 3.30348 14.5859 4.38548 14.5859 5.71948V6.62671C15.2694 7.02689 15.6605 7.85012 15.4385 8.68726L14.3848 12.658C14.1037 13.7164 13.1449 14.4527 12.0498 14.4529H2.91699C1.51651 14.4529 0.451662 13.2814 0.501954 11.9519V3.98706C0.501954 2.65305 1.58396 1.57104 2.91797 1.57104H5.19629ZM3.7793 7.75562C3.30994 7.75562 2.89883 8.07153 2.77832 8.52515L1.91602 11.7722C1.74167 12.4291 2.23734 13.073 2.91699 13.073H12.0498C12.5191 13.0728 12.9304 12.757 13.0508 12.3035L14.1045 8.33374C14.1819 8.04202 13.9619 7.756 13.6602 7.75562H3.7793ZM2.91797 2.9519C2.34625 2.9519 1.88281 3.41534 1.88281 3.98706V7.2937C2.33068 6.7269 3.02249 6.37476 3.7793 6.37476H13.2051V5.71948C13.2051 5.14777 12.7416 4.68434 12.1699 4.68433H7.58203C6.96675 4.6843 6.39209 4.37595 6.05078 3.86401L5.5791 3.15601C5.49379 3.02821 5.34995 2.95196 5.19629 2.9519H2.91797Z" fill="currentColor"/>
+ <path opacity="0.2" d="M13.6602 7.75525C13.9618 7.7556 14.1815 8.04179 14.1045 8.33337L13.0508 12.3031C12.9304 12.7567 12.5191 13.0725 12.0498 13.0726H2.91701C2.23744 13.0725 1.7417 12.4287 1.91603 11.7719L2.77834 8.52478C2.89898 8.07146 3.31018 7.75532 3.77931 7.75525H13.6602ZM5.1963 2.95154C5.34985 2.95159 5.49377 3.02803 5.57912 3.15564L6.0508 3.86365C6.39205 4.37553 6.96685 4.68385 7.58205 4.68396H12.1699C12.7416 4.68396 13.2049 5.14754 13.2051 5.71912V6.37439H3.77931C3.02267 6.37444 2.33067 6.72671 1.88283 7.29333V3.98669C1.88299 3.4152 2.34649 2.95168 2.91798 2.95154H5.1963Z" fill="currentColor"/>
+ </svg>
+)
+
+/** folder_close_16 (figma extract) */
+export const IconFolderClose16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none">
+ <path transform="translate(1.5 2.429)" d="M5.05582 0.518756L4.50669 0.86654L5.05582 0.518756ZM13 9.4837L13.65 9.4837L13.65 3.53962L13 3.53962L12.35 3.53962L12.35 9.4837L13 9.4837ZM11.3264 1.86603L11.3264 1.21603L6.52313 1.21603L6.52313 1.86603L6.52313 2.51603L11.3264 2.51603L11.3264 1.86603ZM5.58054 1.34727L6.12968 0.999489L5.60495 0.170972L5.05582 0.518756L4.50669 0.86654L5.03141 1.69506L5.58054 1.34727ZM4.11323 1.23058e-13L4.11323 -0.65L1.67359 -0.65L1.67359 5.00699e-14L1.67359 0.65L4.11323 0.65L4.11323 1.23058e-13ZM0 1.67359L-0.65 1.67359L-0.65 9.4837L0 9.4837L0.65 9.4837L0.65 1.67359L0 1.67359ZM11.3264 11.1573L11.3264 10.5073L1.67359 10.5073L1.67359 11.1573L1.67359 11.8073L11.3264 11.8073L11.3264 11.1573ZM0 9.4837L-0.65 9.4837C-0.65 10.767 0.390308 11.8073 1.67359 11.8073L1.67359 11.1573L1.67359 10.5073C1.10828 10.5073 0.65 10.049 0.65 9.4837L0 9.4837ZM1.67359 5.00699e-14L1.67359 -0.65C0.390307 -0.65 -0.65 0.390309 -0.65 1.67359L0 1.67359L0.65 1.67359C0.65 1.10828 1.10828 0.65 1.67359 0.65L1.67359 5.00699e-14ZM5.05582 0.518756L5.60495 0.170972C5.28121 -0.340193 4.71829 -0.65 4.11323 -0.65L4.11323 1.23058e-13L4.11323 0.65C4.27282 0.65 4.4213 0.731715 4.50669 0.86654L5.05582 0.518756ZM6.52313 1.86603L6.52313 1.21603C6.36354 1.21603 6.21507 1.13431 6.12968 0.999489L5.58054 1.34727L5.03141 1.69506C5.35515 2.20622 5.91808 2.51603 6.52313 2.51603L6.52313 1.86603ZM13 3.53962L13.65 3.53962C13.65 2.25634 12.6097 1.21603 11.3264 1.21603L11.3264 1.86603L11.3264 2.51603C11.8917 2.51603 12.35 2.97431 12.35 3.53962L13 3.53962ZM13 9.4837L12.35 9.4837C12.35 10.049 11.8917 10.5073 11.3264 10.5073L11.3264 11.1573L11.3264 11.8073C12.6097 11.8073 13.65 10.767 13.65 9.4837L13 9.4837Z" fill="currentColor"/>
+ </svg>
+)
+
+/** tree_corner_8x10 (figma extract; session-tree "L" connector, stroke geometry pre-expanded) */
+export const IconTreeCorner8x10 = ({ size = 10, className }: IconProps) => (
+ <svg width={(size * 8) / 10} height={size} className={className} viewBox="-0.5 0 8.5 10.5" fill="none">
+ <path d="M0 0L-0.5 0L-0.5 7L0 7L0.5 7L0.5 0L0 0ZM3 10L3 10.5L8 10.5L8 10L8 9.5L3 9.5L3 10ZM0 7L-0.5 7C-0.5 8.933 1.067 10.5 3 10.5L3 10L3 9.5C1.61929 9.5 0.5 8.38071 0.5 7L0 7Z" fill="currentColor"/>
+ </svg>
+)
+
+/** ic_ds_light_outline_16 */
+export const IconLightOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M11.3496 8C11.3496 6.14985 9.85015 4.65039 8 4.65039C6.14985 4.65039 4.65039 6.14985 4.65039 8C4.65039 9.85015 6.14985 11.3496 8 11.3496C9.85015 11.3496 11.3496 9.85015 11.3496 8ZM12.6504 8C12.6504 10.5681 10.5681 12.6504 8 12.6504C5.43188 12.6504 3.34961 10.5681 3.34961 8C3.34961 5.43188 5.43188 3.34961 8 3.34961C10.5681 3.34961 12.6504 5.43188 12.6504 8Z"
+ fill="currentColor"
+ />
+ <path d="M8.65039 0.5V2.5H7.34961V0.5H8.65039Z" fill="currentColor" />
+ <path d="M8.65039 13.5V15.5H7.34961V13.5H8.65039Z" fill="currentColor" />
+ <path
+ d="M3.15808 2.24035L4.57229 3.65456L3.6525 4.57435L2.23829 3.16014L3.15808 2.24035Z"
+ fill="currentColor"
+ />
+ <path
+ d="M12.3505 11.4327L13.7647 12.8469L12.8449 13.7667L11.4307 12.3525L12.3505 11.4327Z"
+ fill="currentColor"
+ />
+ <path
+ d="M2.24537 12.8469L3.65958 11.4327L4.57937 12.3525L3.16516 13.7667L2.24537 12.8469Z"
+ fill="currentColor"
+ />
+ <path
+ d="M11.4377 3.65455L12.852 2.24033L13.7718 3.16012L12.3575 4.57434L11.4377 3.65455Z"
+ fill="currentColor"
+ />
+ <path d="M0.5 7.35461H2.5V8.6554H0.5L0.5 7.35461Z" fill="currentColor" />
+ <path d="M13.5 7.35461H15.5V8.6554H13.5V7.35461Z" fill="currentColor" />
+ </svg>
+)
+
+/** ic_ds_dark_outline_16 */
+export const IconDarkOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M13.2764 9.52324C12.5607 9.97754 11.7177 10.242 10.7812 10.242C8.11386 10.2419 5.95042 8.07997 5.9502 5.41289C5.9502 4.48128 6.21453 3.61071 6.67188 2.87285C4.30332 3.4658 2.54992 5.60845 2.5498 8.16093C2.5498 11.1712 4.99103 13.6102 8 13.6102C10.5383 13.6102 12.6709 11.8724 13.2764 9.52324ZM7.05078 5.41289C7.051 7.47224 8.72116 9.1423 10.7812 9.14238C11.9248 9.14238 12.887 8.63397 13.5781 7.8084C13.7266 7.63106 13.9701 7.56547 14.1875 7.64433C14.4049 7.72329 14.5497 7.9297 14.5498 8.16093C14.5498 11.7766 11.6161 14.7098 8 14.7098C4.38402 14.7098 1.4502 11.7792 1.4502 8.16093C1.45033 4.54322 4.3812 1.61015 8 1.61015C8.23027 1.61015 8.43585 1.75352 8.51562 1.96953C8.59536 2.18554 8.53241 2.42829 8.35742 2.57793C7.55573 3.26311 7.05078 4.27876 7.05078 5.41289Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_followsystem_outline_16 */
+export const IconFollowsystemOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M12.1665 13.5811V14.7803H3.66651V13.5811H12.1665Z" fill="currentColor" />
+ <path
+ d="M13.4453 7.02379C13.4453 6.04702 13.4452 5.3616 13.3887 4.83434C13.3333 4.31828 13.2302 4.02378 13.0723 3.80309C12.9446 3.62475 12.7877 3.46883 12.6094 3.34117C12.3887 3.18328 12.0942 3.08007 11.5781 3.02477C11.0508 2.96829 10.3655 2.96715 9.38867 2.96715H6.61035C5.63359 2.96715 4.94816 2.96827 4.4209 3.02477C3.90486 3.0801 3.61034 3.18321 3.38965 3.34117C3.21143 3.46878 3.05534 3.62487 2.92774 3.80309C2.76977 4.02377 2.66667 4.3183 2.61133 4.83434C2.55483 5.3616 2.55371 6.04702 2.55371 7.02379C2.55371 8.0006 2.55485 8.68596 2.61133 9.21324C2.66663 9.72936 2.76983 10.0238 2.92774 10.2445C3.0554 10.4228 3.21131 10.5797 3.38965 10.7074C3.61034 10.8654 3.90484 10.9685 4.4209 11.0238C4.94816 11.0803 5.63359 11.0804 6.61035 11.0804H9.38867C10.3654 11.0804 11.0508 11.0803 11.5781 11.0238C12.0941 10.9685 12.3887 10.8652 12.6094 10.7074C12.7877 10.5797 12.9446 10.4229 13.0723 10.2445C13.2301 10.0238 13.3334 9.72927 13.3887 9.21324C13.4452 8.68596 13.4453 8.00058 13.4453 7.02379ZM14.6455 7.02379C14.6455 7.97428 14.646 8.73509 14.5811 9.34117C14.5149 9.95828 14.3756 10.4858 14.0479 10.9437C13.8436 11.229 13.5938 11.4788 13.3086 11.683C12.8507 12.0108 12.3232 12.15 11.7061 12.2162C11.1 12.2811 10.3391 12.2806 9.38867 12.2806H6.61035C5.66018 12.2806 4.89991 12.2811 4.29395 12.2162C3.67684 12.15 3.14935 12.0108 2.69141 11.683C2.40613 11.4788 2.15639 11.229 1.95215 10.9437C1.62436 10.4858 1.4841 9.95828 1.41797 9.34117C1.35305 8.73511 1.35449 7.97424 1.35449 7.02379C1.35449 6.07366 1.35308 5.31333 1.41797 4.70738C1.4841 4.09028 1.62436 3.56279 1.95215 3.10485C2.15638 2.81956 2.40613 2.56982 2.69141 2.36559C3.14935 2.03779 3.67684 1.89753 4.29395 1.83141C4.8999 1.76652 5.66022 1.76793 6.61035 1.76793H9.38867C10.3391 1.76793 11.1 1.76649 11.7061 1.83141C12.3232 1.89753 12.8507 2.03779 13.3086 2.36559C13.5939 2.56982 13.8436 2.81957 14.0479 3.10485C14.3756 3.56279 14.5149 4.09028 14.5811 4.70738C14.646 5.31335 14.6455 6.07362 14.6455 7.02379Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_data_outline_16 */
+export const IconDataOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M12.0997 8.54554C12.2905 8.54989 12.3541 8.58056 12.4535 8.74614L12.8849 9.46387C12.9851 9.63071 13.0464 9.66013 13.2388 9.66447H14.1138C14.3417 9.66448 14.3512 9.66937 14.4686 9.86507L14.892 10.5717C14.9942 10.7422 14.9948 10.8247 14.892 10.9961L14.4756 11.6906C14.3741 11.8677 14.3694 11.9379 14.4756 12.115L14.892 12.8096C14.9942 12.9801 14.9947 13.0625 14.892 13.234L14.4686 13.9406C14.3643 14.1028 14.3063 14.1354 14.1138 14.1412H13.2388C13.0465 14.1456 12.985 14.1752 12.8849 14.3418L12.4535 15.0595C12.353 15.2195 12.2895 15.2558 12.0997 15.2601H11.2237C10.9962 15.2601 10.9871 15.2548 10.8699 15.0595L10.4384 14.3418C10.3383 14.175 10.2767 14.1456 10.0846 14.1412H9.2096C9.01854 14.1355 8.95761 14.1006 8.85477 13.9406L8.43139 13.234C8.32562 13.0576 8.33148 12.9862 8.43139 12.8096L8.84771 12.115C8.95165 11.9416 8.94659 11.863 8.84771 11.6906L8.43139 10.9961C8.32767 10.8232 8.33411 10.7437 8.43139 10.5717L8.85477 9.86507C8.95447 9.69891 9.01875 9.67017 9.2096 9.66447H10.0846C10.2741 9.66441 10.3414 9.62547 10.4384 9.46387L10.8699 8.74614C10.987 8.55106 10.9963 8.54554 11.2237 8.54554H12.0997ZM11.6612 10.232C11.3326 10.7798 10.8155 11.0948 10.1743 11.106C10.4443 11.61 10.4425 12.1976 10.1743 12.6987C10.803 12.7096 11.3391 13.0359 11.6612 13.5727C11.9855 13.0323 12.5131 12.7098 13.148 12.6987C12.879 12.196 12.8789 11.6086 13.148 11.106C12.5076 11.0948 11.9894 10.7794 11.6612 10.232Z"
+ fill="currentColor"
+ />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M7.51205 0.790627C9.19055 0.790649 10.7401 1.0691 11.892 1.54364C12.4664 1.78029 12.9719 2.07885 13.3436 2.4408C13.7171 2.80467 13.9916 3.27253 13.9918 3.82384V7.90442C13.6067 7.69532 13.1907 7.53597 12.7529 7.43366V5.66454C12.4928 5.82898 12.2028 5.97601 11.892 6.10405C10.74 6.57865 9.19071 6.85706 7.51205 6.85706C5.8337 6.85703 4.285 6.57852 3.13309 6.10405C2.82215 5.97593 2.53164 5.8291 2.27121 5.66454V7.4135C2.27134 7.75678 2.6066 8.27106 3.62502 8.73405C4.58641 9.17097 5.95762 9.45591 7.50499 9.45681C7.24582 9.83133 7.03684 10.2434 6.88706 10.6826C5.44388 10.6162 4.12516 10.3216 3.11192 9.86104C2.81708 9.72698 2.53185 9.56866 2.27121 9.38928V11.2542C2.27158 11.5974 2.60697 12.1109 3.62502 12.5737C4.41933 12.9347 5.4937 13.1898 6.71569 13.2693C6.80349 13.7128 6.9513 14.1345 7.14814 14.5273C5.60324 14.4862 4.18593 14.1889 3.11192 13.7007C2.01039 13.1998 1.03366 12.3814 1.03333 11.2542V3.82384C1.03352 3.27273 1.30721 2.80461 1.68049 2.4408C2.05211 2.07893 2.55887 1.78026 3.13309 1.54364C4.28492 1.06926 5.83393 0.790683 7.51205 0.790627ZM7.51205 2.02851C5.95492 2.02857 4.57354 2.29079 3.60486 2.68979C3.11958 2.88977 2.76667 3.11253 2.5454 3.32788C2.32671 3.54101 2.2714 3.7089 2.27121 3.82384C2.27121 3.93882 2.32624 4.10625 2.5454 4.3198C2.76667 4.53527 3.11927 4.75781 3.60486 4.9579C4.5736 5.35699 5.95467 5.61914 7.51205 5.61918C9.06942 5.61918 10.4505 5.35695 11.4192 4.9579C11.9051 4.75773 12.2584 4.53536 12.4797 4.3198C12.6988 4.10627 12.7529 3.93882 12.7529 3.82384C12.7527 3.70889 12.6984 3.54104 12.4797 3.32788C12.2584 3.11239 11.9049 2.88989 11.4192 2.68979C10.4505 2.29079 9.06925 2.02853 7.51205 2.02851Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_send_outline_14 (figma extract): thin-stroke upward send arrow. */
+export const IconSendOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M7.24707 1.01771C7.52897 1.07653 7.77619 1.19694 8.00391 1.38001C8.19202 1.53136 8.39884 1.73784 8.61914 1.95814L12.6396 5.9806L11.6299 6.99134L7.71484 3.0763V13.0001H6.28516V3.0763L2.36914 6.99134L1.35938 5.9806L5.38086 1.95814C5.60116 1.73784 5.80798 1.53136 5.99609 1.38001C6.19476 1.22027 6.4385 1.06739 6.75195 1.01771C6.91296 0.992304 7.07471 0.997504 7.24707 1.01771Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_queue_outline_14 (figma extract): open chat bubble with two queued lines. */
+export const IconQueueOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M7.00049 0.199829C3.24488 0.199829 0.199952 3.24408 0.199707 6.99963C0.199707 8.0414 0.434087 9.03061 0.854004 9.91467L1.11279 10.4576L2.19775 9.94202L1.94092 9.39905L1.81787 9.12268C1.5498 8.46885 1.40186 7.75171 1.40186 6.99963C1.4021 3.90808 3.90888 1.40198 7.00049 1.40198C10.0919 1.40219 12.5979 3.90821 12.5981 6.99963C12.5981 10.0913 10.0921 12.5981 7.00049 12.5983C6.36734 12.5983 5.90348 12.5535 5.49268 12.4401C5.08803 12.3283 4.7041 12.1414 4.24463 11.8209C3.57111 11.3511 2.60588 11.1855 1.81006 11.6881L1.79736 11.6959L1.78467 11.7047L1.25537 12.0778L1.65381 13.2672L2.46045 12.6989C2.75029 12.5214 3.18004 12.5442 3.55615 12.8063C4.10063 13.1861 4.60863 13.4423 5.17334 13.5983C5.73194 13.7525 6.31665 13.8004 7.00049 13.8004C10.7561 13.8002 13.8003 10.7553 13.8003 6.99963C13.8 3.24421 10.7559 0.200041 7.00049 0.199829ZM3.81201 7.47327V8.67542H7.11572V7.47327H3.81201ZM3.81201 6.34924H10.2173V5.14709H3.81201V6.34924Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_checklist_outline_14 (figma extract): two rings + two list bars. */
+export const IconChecklistOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M13.3277 9.69629V10.976H7.28086V9.69629H13.3277Z" fill="currentColor" />
+ <path d="M13.3277 2.97256V4.25225H7.28086V2.97256H13.3277Z" fill="currentColor" />
+ <path d="M4.64512 10.336C4.64505 9.62755 4.07081 9.05322 3.3623 9.05322C2.65386 9.05329 2.07956 9.62759 2.07949 10.336C2.07949 11.0445 2.65382 11.6188 3.3623 11.6188C4.07085 11.6188 4.64512 11.0446 4.64512 10.336ZM5.92559 10.336C5.92559 11.7515 4.77777 12.8993 3.3623 12.8993C1.94689 12.8993 0.799805 11.7515 0.799805 10.336C0.799871 8.92066 1.94693 7.7736 3.3623 7.77354C4.77773 7.77354 5.92552 8.92062 5.92559 10.336Z" fill="currentColor" />
+ <path d="M4.64531 3.6123C4.6453 2.90382 4.07098 2.32949 3.3625 2.32949C2.65403 2.32951 2.0797 2.90383 2.07969 3.6123C2.07969 4.32079 2.65402 4.8951 3.3625 4.89512C4.07099 4.89512 4.64531 4.3208 4.64531 3.6123ZM5.925 3.6123C5.925 5.02772 4.77792 6.1748 3.3625 6.1748C1.9471 6.17479 0.8 5.02771 0.8 3.6123C0.800013 2.19691 1.9471 1.04982 3.3625 1.0498C4.77791 1.0498 5.92499 2.1969 5.925 3.6123Z" fill="currentColor" />
+ </svg>
+)
+
+/** ic_ds_List_Pen_outline_16 */
+export const IconListPenOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M10.8239 3.54733V4.78443H4.63437V3.54733H10.8239Z" fill="currentColor" />
+ <path d="M10.8239 6.12629V7.36338H4.63437V6.12629H10.8239Z" fill="currentColor" />
+ <path d="M9.073 8.70524V9.94234H4.63437V8.70524H9.073Z" fill="currentColor" />
+ <path
+ d="M9.13321 0.573526C10.0076 0.573525 10.7179 0.572522 11.285 0.63397C11.8645 0.696791 12.3743 0.831648 12.8193 1.1548C13.0776 1.34246 13.3056 1.57047 13.4933 1.82875C13.8164 2.2737 13.9513 2.7836 14.0141 3.36303C14.0755 3.93015 14.0745 4.64049 14.0745 5.51485V6.1757L12.7327 7.5629V5.51485C12.7327 4.61092 12.732 3.9862 12.6803 3.5081C12.6298 3.0427 12.5379 2.79497 12.4083 2.61654C12.3033 2.47211 12.176 2.34472 12.0315 2.23977C11.8531 2.11016 11.6054 2.01823 11.14 1.96777C10.6618 1.91601 10.0372 1.91539 9.13321 1.91539H6.32658C5.42262 1.91539 4.79796 1.91604 4.31983 1.96777C3.85451 2.01819 3.60672 2.11029 3.42827 2.23977C3.28392 2.34465 3.15643 2.47223 3.0515 2.61654C2.9219 2.79496 2.82997 3.04274 2.7795 3.5081C2.72774 3.9862 2.72712 4.61092 2.72712 5.51485V10.023C2.72712 10.9273 2.72773 11.5525 2.7795 12.0307C2.82992 12.4959 2.92205 12.7429 3.0515 12.9213C3.15645 13.0657 3.28384 13.1931 3.42827 13.2981C3.60676 13.4277 3.85408 13.5206 4.31983 13.5711C4.79797 13.6228 5.42259 13.6234 6.32658 13.6234H6.87057L5.57707 14.9593C5.03527 14.9556 4.57031 14.9467 4.17476 14.9039C3.59508 14.841 3.08558 14.7063 2.64048 14.383C2.38215 14.1953 2.15422 13.9684 1.96653 13.7101C1.64319 13.2649 1.50851 12.7546 1.4457 12.1748C1.38432 11.6076 1.38525 10.8974 1.38525 10.023V5.51485C1.38525 4.64049 1.38426 3.93015 1.4457 3.36303C1.50853 2.78363 1.64341 2.27368 1.96653 1.82875C2.15417 1.57059 2.38228 1.34239 2.64048 1.1548C3.08544 0.831805 3.59533 0.696762 4.17476 0.63397C4.74193 0.572552 5.45218 0.573525 6.32658 0.573526H9.13321Z"
+ fill="currentColor"
+ />
+ <path d="M14.2193 14.9553H10.0124L11.3744 13.6134H14.2193V14.9553Z" fill="currentColor" />
+ <path
+ d="M8.24493 13.3711L7.49015 14.8806C7.40148 15.058 7.58961 15.2461 7.76695 15.1574L9.27651 14.4027L14.6147 9.09934L13.5832 8.06775L8.24493 13.3711Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_goal_outline_16 (goal strip leading glyph: dartboard with a landed arrow) */
+export const IconGoalOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M8 0C8.31451 0 8.62464 0.019379 8.92969 0.0546875C8.48228 0.403371 8.0952 0.825758 7.78809 1.30469C4.18586 1.41664 1.2998 4.37061 1.2998 8C1.2998 11.7003 4.29969 14.7002 8 14.7002C11.6297 14.7002 14.5829 11.8136 14.6943 8.21094C15.1734 7.90377 15.5956 7.51688 15.9443 7.06934C15.9797 7.37473 16 7.68512 16 8C16 12.4183 12.4183 16 8 16C3.58172 16 0 12.4183 0 8C0 3.58172 3.58172 0 8 0ZM7.0166 3.6084C7.00658 3.73765 7 3.86817 7 4C7 4.31845 7.03098 4.62973 7.08789 4.93164C5.76489 5.32438 4.7998 6.54958 4.7998 8C4.7998 9.76731 6.23269 11.2002 8 11.2002C9.45065 11.2002 10.6749 10.2345 11.0674 8.91113C11.3696 8.96818 11.6812 9 12 9C12.1315 9 12.2617 8.99239 12.3906 8.98242C11.9423 10.995 10.1477 12.5 8 12.5C5.51472 12.5 3.5 10.4853 3.5 8C3.5 5.85255 5.00435 4.05702 7.0166 3.6084Z"
+ fill="currentColor"
+ />
+ <path d="M7.5 8.62109L9.12109 7" stroke="currentColor" strokeWidth="1.3" />
+ <path
+ d="M9.08245 3.35798L11.8651 0.575334C11.895 0.545384 11.9463 0.56391 11.9502 0.606086L12.2362 3.69859C12.2384 3.72259 12.2574 3.74159 12.2814 3.74378L15.3697 4.02583C15.4119 4.02968 15.4305 4.08101 15.4005 4.11098L12.618 6.89351C12.6086 6.90289 12.5959 6.90816 12.5826 6.90816L9.11781 6.90815C9.09019 6.90816 9.06781 6.88577 9.06781 6.85816L9.06781 3.39333C9.06781 3.38007 9.07308 3.36735 9.08245 3.35798Z"
+ stroke="currentColor"
+ strokeWidth="1.3"
+ />
+ </svg>
+)
+
+/** sparkle_16 (Others tool-row leading glyph; hand-authored three-star
+ * approximation — the figma 43:31850 glyph is an SF Symbols "sparkles" text glyph,
+ * not extractable as vector data) */
+export const IconSparkle16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M6.1 3.1Q6.6 7.8 11.3 8.3Q6.6 8.8 6.1 13.5Q5.6 8.8 0.9 8.3Q5.6 7.8 6.1 3.1Z" fill="currentColor" />
+ <path d="M11.9 1Q12.2 3.7 14.9 4Q12.2 4.3 11.9 7Q11.6 4.3 8.9 4Q11.6 3.7 11.9 1Z" fill="currentColor" />
+ <path d="M12.5 9.4Q12.7 11.4 14.7 11.6Q12.7 11.8 12.5 13.8Q12.3 11.8 10.3 11.6Q12.3 11.4 12.5 9.4Z" fill="currentColor" />
+ </svg>
+)
+
+/** inspect_outline_12 (shared tool-row trajectory affordance glyph) */
+export const IconInspectOutline12 = ({ size = 12, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden>
+ <path d="M16 8L10.8571 12V10.552L14.1383 8L10.8571 5.448V4L16 8ZM5.14286 10.552L1.86171 8L5.14286 5.448V4L0 8L5.14286 12V10.552ZM9.02514 4L5.59657 12H6.84057L10.2691 4H9.02514Z" fill="currentColor" />
+ </svg>
+)
+
+/** skill_outline_16 (skill tool-row glyph; document instructions + sparkle) */
+export const IconSkillOutline16 = ({ size = 16, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M12.5113 15.4067C12.4395 15.6249 12.1308 15.6249 12.059 15.4067L11.643 14.1416C11.454 13.567 11.0033 13.1164 10.4288 12.9274L9.16369 12.5113C8.94544 12.4395 8.94544 12.1308 9.16369 12.059L10.4288 11.643C11.0033 11.454 11.454 11.0033 11.643 10.4288L12.059 9.16369C12.1308 8.94544 12.4395 8.94544 12.5113 9.16369L12.9274 10.4288C13.1164 11.0033 13.567 11.454 14.1416 11.643L15.4067 12.059C15.6249 12.1308 15.6249 12.4395 15.4067 12.5113L14.1416 12.9274C13.567 13.1164 13.1164 13.567 12.9274 14.1416L12.5113 15.4067Z"
+ fill="currentColor"
+ />
+ <path
+ d="M9.02246 0.546878C9.9822 0.546878 10.7564 0.545403 11.374 0.612307C12.0042 0.680586 12.5515 0.826244 13.0273 1.17188C13.3052 1.37376 13.5501 1.61868 13.752 1.89649C14.0975 2.37225 14.2432 2.91984 14.3115 3.54981C14.3784 4.16727 14.377 4.94206 14.377 5.90137V8.51367C13.9611 8.29533 13.5071 8.13985 13.0273 8.06055V5.90137C13.0273 4.9121 13.0259 4.22322 12.9688 3.69532C12.9129 3.18044 12.8098 2.89782 12.6592 2.69043C12.5406 2.52724 12.3966 2.38326 12.2334 2.26465C12.026 2.11404 11.7437 2.0109 11.2285 1.95508C10.7005 1.89789 10.0122 1.89649 9.02246 1.89649H6.55371C5.56395 1.89649 4.87569 1.89787 4.34766 1.95508C3.83242 2.01092 3.55022 2.11398 3.34278 2.26465C3.17953 2.38329 3.03564 2.52719 2.91699 2.69043C2.76642 2.89782 2.66325 3.18042 2.60742 3.69532C2.55027 4.22322 2.54883 4.9121 2.54883 5.90137V10.0986C2.54883 11.0878 2.55031 11.7768 2.60742 12.3047C2.66326 12.8196 2.76642 13.1032 2.91699 13.3105C3.03558 13.4736 3.17966 13.6178 3.34278 13.7363C3.5502 13.8869 3.83265 13.9901 4.34766 14.0459C4.87568 14.1031 5.56398 14.1035 6.55371 14.1035H8.08399C8.27443 14.6025 8.55077 15.0585 8.89551 15.4541H6.55371C5.59402 15.4541 4.81976 15.4546 4.20215 15.3877C3.57204 15.3194 3.02468 15.1738 2.54883 14.8281C2.27111 14.6263 2.02606 14.3813 1.82422 14.1035C1.47883 13.6278 1.33293 13.08 1.26465 12.4502C1.19783 11.8327 1.19922 11.0579 1.19922 10.0986V5.90137C1.19922 4.94206 1.1978 4.16727 1.26465 3.54981C1.33295 2.91984 1.47867 2.37225 1.82422 1.89649C2.02613 1.61864 2.27098 1.37379 2.54883 1.17188C3.02472 0.826181 3.57197 0.6806 4.20215 0.612307C4.81976 0.545393 5.594 0.546877 6.55371 0.546878H9.02246ZM9.19629 9.14649H4.5459V7.84571H9.19629V9.14649ZM11.0303 6.10645H4.5459V4.80567H11.0303V6.10645Z"
+ fill="currentColor"
+ />
+ </svg>
+)
+
+/** ic_ds_question_outline_14 (figma extract): ring + question glyph. */
+export const IconQuestionOutline14 = ({ size = 14, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ d="M12.5757 7.00012C12.5757 3.92085 10.0794 1.42463 7.00012 1.42456C3.9208 1.42456 1.42456 3.9208 1.42456 7.00012C1.42463 10.0794 3.92085 12.5757 7.00012 12.5757C10.0793 12.5756 12.5756 10.0793 12.5757 7.00012ZM13.8002 7.00012C13.8001 10.7559 10.7559 13.8001 7.00012 13.8002C3.2443 13.8002 0.199291 10.7559 0.199219 7.00012C0.199219 3.24426 3.24426 0.199219 7.00012 0.199219C10.7559 0.199291 13.8002 3.2443 13.8002 7.00012Z"
+ fill="currentColor"
+ />
+ <path
+ d="M6.18042 8.68184C6.18043 8.09153 6.32893 7.34655 6.92127 6.8481C7.28566 6.54148 7.76104 6.27318 8.0022 6.10811C8.28964 5.91137 8.42234 5.76562 8.48328 5.58944C8.57774 5.31609 8.53121 5.00904 8.34912 4.76741C8.17409 4.53522 7.83879 4.32222 7.28186 4.32222C5.99668 4.32225 5.46969 5.11832 5.46949 5.78939H4.24414C4.24436 4.39942 5.36327 3.09691 7.28186 3.09688C8.17773 3.09688 8.89489 3.45606 9.32752 4.02999C9.75287 4.59438 9.86938 5.32775 9.64026 5.99019C9.44847 6.5444 9.04722 6.87743 8.69434 7.11898C8.29506 7.39226 8.02318 7.52192 7.70996 7.78548C7.51943 7.94582 7.40577 8.24899 7.40577 8.68184V8.75533H6.18042V8.68184Z"
+ fill="currentColor"
+ />
+ <path d="M7.39455 9.44026V10.8109H6.16921V9.44026H7.39455Z" fill="currentColor" />
+ </svg>
+)
+
+/** ic_ds_archive_outline_20 (figma extract): lidded box + label slot. The export's
+ * 0.11px stroke ring around the box contour is dropped — it restates the same
+ * contour in the same ink, which currentColor already carries. */
+export const IconArchiveOutline20 = ({ size = 20, className }: IconProps) => (
+ <svg width={size} height={size} className={className} viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M15.8659 2.05975C17.2603 2.05995 18.3913 3.19096 18.3914 4.58527V5.4874C18.3914 6.02747 18.2192 6.52672 17.9303 6.93735C17.9336 6.96524 17.9388 6.99318 17.9388 7.02195V12.8884C17.9388 13.6345 17.9395 14.2379 17.8996 14.7254C17.8642 15.1593 17.7936 15.5499 17.6373 15.9141L17.5654 16.0685C17.278 16.6328 16.8405 17.1046 16.3038 17.434L16.0679 17.5661C15.66 17.7739 15.2196 17.8598 14.7237 17.9003C14.2362 17.9401 13.6327 17.9405 12.8867 17.9405H7.11122C6.36511 17.9405 5.76171 17.9401 5.27418 17.9003C4.84051 17.8649 4.44949 17.7952 4.08545 17.6391L3.93104 17.5661C3.36673 17.2785 2.89392 16.8414 2.56465 16.3044L2.43245 16.0685C2.22473 15.6608 2.13878 15.2211 2.09825 14.7254C2.05841 14.2379 2.05912 13.6345 2.05912 12.8884V7.02195C2.05912 6.99284 2.06422 6.96449 2.06758 6.93629C1.77931 6.52592 1.60858 6.02687 1.60858 5.4874V4.58527C1.60876 3.19084 2.73962 2.05975 4.1341 2.05975H15.8659ZM16.4984 7.92936C16.296 7.98169 16.0847 8.01288 15.8659 8.01291H4.1341C3.91478 8.01291 3.70246 7.98194 3.49955 7.92936V12.8884C3.49955 13.6582 3.50053 14.1927 3.53445 14.608C3.56769 15.0146 3.62923 15.244 3.71635 15.415L3.7925 15.5514C3.98339 15.8627 4.25749 16.1165 4.58464 16.2833L4.72529 16.3435C4.88095 16.3993 5.08638 16.4402 5.39158 16.4651C5.80685 16.4991 6.34138 16.5001 7.11122 16.5001H12.8867C13.6564 16.5001 14.1911 16.499 14.6063 16.4651C15.0128 16.432 15.2423 16.3703 15.4133 16.2833L15.5508 16.2061C15.8618 16.0152 16.116 15.7419 16.2827 15.415L16.3429 15.2732C16.3985 15.1177 16.4396 14.9128 16.4645 14.608C16.4985 14.1927 16.4984 13.6583 16.4984 12.8884V7.92936ZM4.1341 3.50019C3.53511 3.50019 3.0492 3.98631 3.04902 4.58527V5.4874C3.04902 6.08649 3.535 6.57248 4.1341 6.57248H15.8659C16.4648 6.57228 16.951 6.08638 16.951 5.4874V4.58527C16.9509 3.98644 16.4647 3.50038 15.8659 3.50019H4.1341Z"
+ fill="currentColor"
+ />
+ <path d="M12.7962 12.5661V11.0832H7.20548V12.5661L12.7962 12.5661Z" fill="currentColor" />
+ </svg>
+)
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/icons/props.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/icons/props.ts
new file mode 100644
index 0000000000..01d12ccf63
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/icons/props.ts
@@ -0,0 +1,10 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Shared props for every ic_ds_* icon component. */
+export interface IconProps {
+ /** Square edge in px; defaults to the glyph's own drawn size. */
+ size?: number | undefined
+ /** Extra class for layout placement; color rides currentColor.
+ * (`| undefined` for exactOptionalPropertyTypes: callers forward their own optional prop.) */
+ className?: string | undefined
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/index.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/index.ts
new file mode 100644
index 0000000000..a2cac38f26
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/index.ts
@@ -0,0 +1,13 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** UI primitives copied into the standalone viewer. */
+
+export { JsonTree } from './JsonTree.tsx'
+export type { JsonTreeLabels, JsonTreeProps } from './JsonTree.tsx'
+export { Tooltip } from './Tooltip.tsx'
+export type { TooltipSide } from './Tooltip.tsx'
+export { MarkdownText } from './markdown/MarkdownText.tsx'
+export type { MarkdownCodeLabels, MarkdownFileMentions } from './markdown/MarkdownText.tsx'
+export { extractMarkdownPlainText } from './markdown/plain-text.ts'
+export type { MarkdownPlainTextMode, MarkdownPlainTextOptions } from './markdown/plain-text.ts'
+export * from './icons/index.tsx'
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/CodeBlock.module.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/CodeBlock.module.css
new file mode 100644
index 0000000000..fc9e1a52e3
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/CodeBlock.module.css
@@ -0,0 +1,98 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+/* Visual baseline: deepsuite `@deepseek/md` code-block.css. Highlight colors
+ stay on the existing shiki `--shiki-*` sheet (not Prism highlight.css). */
+
+.block {
+ --dsl-code-block-banner-background-color: var(--dsw-alias-markdown-code-block-banner);
+ --dsl-code-block-border-radius: 12px;
+ --dsl-code-block-banner-font: var(--dsw-font-xs-13);
+ --dsl-code-block-content-font: var(--dsw-font-markdown-code-block);
+
+ position: relative;
+ margin: 16px 0;
+ color: var(--dsw-alias-label-primary);
+ background: var(--dsw-alias-markdown-code-block);
+ border-radius: var(--dsl-code-block-border-radius);
+}
+
+.block:not(:last-child) {
+ margin-bottom: 11px;
+}
+
+.bannerWrap {
+ position: sticky;
+ top: 0;
+ z-index: 6;
+ background-color: var(--dsw-alias-bg-base);
+ border-top-left-radius: var(--dsl-code-block-border-radius);
+ border-top-right-radius: var(--dsl-code-block-border-radius);
+}
+
+.banner {
+ background: var(--dsl-code-block-banner-background-color);
+ padding: 9px 14px;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 12px;
+ font: var(--dsl-code-block-banner-font);
+ border-top-left-radius: var(--dsl-code-block-border-radius);
+ border-top-right-radius: var(--dsl-code-block-border-radius);
+}
+
+.infostring {
+ color: var(--dsw-alias-label-primary);
+ font-family: var(--ds-font-family-code);
+ font-size: 12px;
+ line-height: 18px;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.action {
+ display: flex;
+ align-items: center;
+ flex-shrink: 0;
+}
+
+.copyButton {
+ background-color: transparent;
+ border: none;
+ padding: 0;
+ margin: 0;
+ color: inherit;
+ cursor: pointer;
+ font: inherit;
+}
+
+.block :where(pre) {
+ font: var(--dsl-code-block-content-font);
+ padding: 16px;
+ margin: 0 !important;
+ overflow-x: auto;
+ white-space: pre-wrap;
+ word-break: break-all;
+ background: var(--dsw-alias-markdown-code-block);
+ /* Bottom radii live on <pre>: overflow:hidden on .block would kill the
+ sticky banner, and this opaque fill otherwise squares off the wrapper. */
+ border-bottom-left-radius: var(--dsl-code-block-border-radius);
+ border-bottom-right-radius: var(--dsl-code-block-border-radius);
+}
+
+/* Shiki inlines its theme background var; route it to the repo token. */
+.block :where(pre.shiki) {
+ background: var(--dsw-alias-markdown-code-block) !important;
+}
+
+.block :where(pre) code {
+ font: inherit;
+ background: none;
+ padding: 0;
+}
+
+.plain {
+ color: var(--dsw-alias-label-primary);
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/CodeBlock.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/CodeBlock.tsx
new file mode 100644
index 0000000000..34b125b3d7
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/CodeBlock.tsx
@@ -0,0 +1,76 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+// CodeBlock: one code surface for every consumer — markdown fences, the
+// run_code program body, and the details panel's raw args/output — with
+// shiki highlighting for the registered grammars and an identical-geometry
+// plain fallback for everything else. Chrome (language banner + copy) matches
+// deepsuite `@deepseek/md` code blocks; token colors stay on `--shiki-*`.
+
+import { useCallback, useMemo, useRef, useState, useSyncExternalStore } from 'react'
+import clsx from 'clsx'
+import { writeClipboard } from '../clipboard.ts'
+import { grammarLoadCount, highlightToHtml, subscribeGrammarLoaded } from './highlight.ts'
+import css from './CodeBlock.module.css'
+
+export interface CodeBlockProps {
+ /** The source text, rendered verbatim (trailing newline trimmed for display). */
+ code: string
+ /** Grammar hint (markdown fence info string or a fixed caller id); unknown = plain. */
+ lang?: string | undefined
+ /** Extra class merged onto the wrapper (callers position; this component draws). */
+ className?: string | undefined
+ /** Copy-button idle label; the owner passes localized copy (this package is cordis-free, so copy arrives via props). */
+ copyLabel?: string | undefined
+ /** Copy-button label during the post-copy confirmation window. */
+ copiedLabel?: string | undefined
+}
+
+export function CodeBlock({ code, lang, className, copyLabel = '复制', copiedLabel = '复制成功' }: CodeBlockProps) {
+ const trimmed = code.endsWith('\n') ? code.slice(0, -1) : code
+ // Re-render when a lazy grammar finishes loading, so a fence that showed plain
+ // text while its language's grammar imported picks up highlighting. The
+ // snapshot value is opaque; only its change across renders drives the memo.
+ const loaded = useSyncExternalStore(subscribeGrammarLoaded, grammarLoadCount, grammarLoadCount)
+ const html = useMemo(() => highlightToHtml(trimmed, lang), [trimmed, lang, loaded])
+ const rootRef = useRef<HTMLDivElement>(null)
+ const [copied, setCopied] = useState(false)
+
+ const onCopy = useCallback(() => {
+ if (copied) return
+ /* v8 ignore next -- both arms always mount a <pre>; trimmed is the
+ typed fallback if the DOM shape ever diverges. */
+ const text = rootRef.current?.querySelector('pre')?.textContent ?? trimmed
+ void writeClipboard(text).then((ok) => {
+ if (!ok) return
+ setCopied(true)
+ window.setTimeout(() => { setCopied(false) }, 1000)
+ })
+ }, [copied, trimmed])
+
+ const body = html === undefined
+ ? (
+ <pre className={css.plain}><code>{trimmed}</code></pre>
+ )
+ : (
+ // shiki's output is a static span tree it generated from `code` (no user
+ // HTML passes through), the sanctioned innerHTML consumption path per
+ // shiki's own docs.
+ <div dangerouslySetInnerHTML={{ __html: html }} />
+ )
+
+ return (
+ <div ref={rootRef} className={clsx(css.block, 'md-code-block', className)}>
+ <div className={css.bannerWrap}>
+ <div className={css.banner}>
+ <div className={css.infostring}>{lang ?? ''}</div>
+ <div className={css.action}>
+ <button type="button" className={css.copyButton} onClick={onCopy}>
+ {copied ? copiedLabel : copyLabel}
+ </button>
+ </div>
+ </div>
+ </div>
+ {body}
+ </div>
+ )
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/MarkdownText.module.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/MarkdownText.module.css
new file mode 100644
index 0000000000..e620d1c592
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/MarkdownText.module.css
@@ -0,0 +1,267 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+/* Visual baseline: deepsuite `@deepseek/md` markdown.css, adapted to CSS
+ Modules. Cite pills, header anchors, and thinking-small variants are
+ intentionally absent (no matching DOM). Token names match that sheet. */
+
+.markdown {
+ min-width: 0;
+ overflow-wrap: anywhere;
+ font: var(--dsw-font-markdown-base);
+ color: var(--dsw-alias-label-primary);
+}
+
+.markdown strong {
+ font-weight: 600;
+}
+
+.markdown h1 {
+ font: var(--dsw-font-markdown-h1);
+ margin: 32px 0 16px;
+}
+
+.markdown h2 {
+ font: var(--dsw-font-markdown-h2);
+ margin: 32px 0 16px;
+}
+
+.markdown h3 {
+ font: var(--dsw-font-markdown-h3);
+ margin: 32px 0 16px;
+}
+
+.markdown h4 {
+ font: var(--dsw-font-markdown-h4);
+ margin: 16px 0;
+}
+
+.markdown :where(h5, h6) {
+ font: var(--dsw-font-markdown-base-strong);
+ margin: 16px 0;
+}
+
+.markdown :where(h1, h2, h3, h4, h5, h6) strong {
+ font-weight: inherit;
+}
+
+.markdown p {
+ margin: 16px 0;
+}
+
+/* Tighten h4–h6 against a following list (design: 8px gap). */
+.markdown :where(h4, h5, h6) + :where(ul, ol) {
+ margin-top: 8px;
+}
+
+.markdown :where(h4, h5, h6):has(+ :where(ul, ol)) {
+ margin-bottom: 8px;
+}
+
+.markdown a {
+ /* deepsuite markdown.css uses brand-text (blue in newDesign); this sheet
+ keeps design-platform brand-text as near-black, so links use the blue
+ business-primary alias instead. */
+ color: var(--dsw-alias-state-business-primary);
+ transition: box-shadow var(--ds-transition-duration) var(--ds-ease-in-out);
+ position: relative;
+ text-decoration: none;
+ /* Transparent hit-area padding; literal zero-alpha only (no painted color). */
+ border-left: 3px solid transparent;
+ border-right: 3px solid transparent;
+ border-top: 2px solid transparent;
+ border-bottom: 2px solid transparent;
+ margin-left: -3px;
+ margin-right: -3px;
+}
+
+.markdown a:hover,
+.markdown a:focus {
+ outline: none;
+ text-decoration: underline var(--dsw-alias-state-business-primary);
+}
+
+.markdown a:focus-visible {
+ box-shadow: 0 0 0 2px var(--dsw-alias-state-business-primary);
+}
+
+.markdown :where(ul, ol) {
+ margin: 16px 0;
+ padding-left: 18px;
+}
+
+.markdown li:not(:first-child) {
+ margin-top: 6px;
+}
+
+.markdown li > :where(ul, ol) {
+ margin-top: 4px;
+}
+
+.markdown li::marker {
+ line-height: 28px;
+ color: var(--dsw-alias-label-secondary);
+}
+
+/* Nested ol under ul/ol: markers inside (models sometimes emit this shape). */
+.markdown :where(ul, ol) ol {
+ list-style-position: inside;
+ padding-left: 0;
+}
+
+.markdown :where(ul, ol) ol li p {
+ display: inline;
+}
+
+.markdown li > p {
+ margin: 8px 0;
+}
+
+.markdown li > *:first-child {
+ margin-top: 0;
+}
+
+/* Keep list-nested code-block vertical margins (design: +4px vs other last children). */
+.markdown li > *:last-child:not(:global(.md-code-block)) {
+ margin-bottom: 0;
+}
+
+.markdown hr {
+ display: block;
+ border: none;
+ height: 1px;
+ margin: 32px 0;
+ background: var(--dsw-alias-border-l2);
+}
+
+.markdown blockquote {
+ border-left: 2px solid var(--dsw-alias-label-caption);
+ margin: 16px 0 0;
+ padding-left: 14px;
+}
+
+.markdown pre {
+ margin: 16px 0;
+ font-family: var(--ds-font-family-code);
+ overflow: auto;
+}
+
+.markdown :not(pre) > code {
+ display: inline-flex;
+ align-items: center;
+ box-sizing: border-box;
+ font: var(--dsw-font-markdown-code);
+ font-family: var(--ds-font-family-code);
+ font-size: 0.875em !important;
+ background-color: var(--dsw-alias-markdown-inline-code);
+ border-radius: 6px;
+ padding: 0 5px;
+}
+
+.markdown :where(h1, h2, h3, h4, h5, h6) code {
+ font: inherit;
+ font-family: var(--ds-font-family-code);
+}
+
+.markdown :global(.katex-display) {
+ max-width: 100%;
+ overflow-x: auto;
+ overflow-y: hidden;
+}
+
+.markdown input[type='checkbox'] {
+ margin: 0 8px 0 0;
+ accent-color: var(--dsw-alias-label-secondary);
+}
+
+.tableScroll {
+ max-width: 100%;
+ overflow-x: auto;
+ overscroll-behavior-x: contain;
+}
+
+.tableScroll table {
+ border-collapse: collapse;
+ width: max-content;
+ max-width: max-content;
+}
+
+.tableScroll th {
+ text-align: start;
+ padding: 10px 16px;
+ border-bottom: 1px solid var(--dsw-alias-border-l3);
+ border-top: none;
+ font: var(--dsw-font-markdown-table-head);
+ max-width: 320px;
+ max-width: min(30vw, 320px);
+ min-width: 100px;
+}
+
+.tableScroll td {
+ padding: 10px 16px;
+ border-bottom: 1px solid var(--dsw-alias-border-l2);
+ font: var(--dsw-font-markdown-table);
+ max-width: 320px;
+ max-width: min(30vw, 320px);
+ min-width: 100px;
+}
+
+.tableScroll th:first-child,
+.tableScroll td:first-child {
+ padding-left: 0;
+}
+
+.tableScroll td:last-child {
+ padding-right: 0;
+}
+
+.tableScroll table code {
+ font-size: 13px;
+}
+
+.markdown > *:first-child,
+.markdown p:first-child {
+ margin-top: 0 !important;
+}
+
+.markdown > *:last-child,
+.markdown p:last-child {
+ margin-bottom: 0 !important;
+}
+
+.imageAlt {
+ color: var(--dsw-alias-label-tertiary);
+ font-style: italic;
+}
+
+.image {
+ display: block;
+ width: auto;
+ max-width: 100%;
+ height: auto;
+ margin: 0;
+ border-radius: 8px;
+ background: var(--dsw-alias-bg-base);
+ object-fit: contain;
+}
+
+/* Inline file mention: the same link language this sheet gives anchors (and
+ thereby URL-promoted inline code) — link-blue at rest, underline only on
+ hover/focus. An underline at rest reads badly inside the code chip, where
+ it collides with monospace descenders and the pill background. */
+.fileMention {
+ margin: 0;
+ padding: 0;
+ border: none;
+ background: none;
+ font: inherit;
+ color: var(--dsw-alias-state-business-primary);
+ text-decoration: none;
+ cursor: pointer;
+}
+
+.fileMention:hover,
+.fileMention:focus {
+ outline: none;
+ text-decoration: underline var(--dsw-alias-state-business-primary);
+ text-underline-offset: 3px;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/MarkdownText.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/MarkdownText.tsx
new file mode 100644
index 0000000000..b172bb2cf6
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/MarkdownText.tsx
@@ -0,0 +1,178 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Untrusted assistant-Markdown renderer over the direct mdast pipeline:
+ * `parse.ts` grammars, the incremental streaming parser, and `render.tsx`.
+ * While a message streams, all but the trailing two blocks freeze as cached
+ * React elements and only the source tail behind them re-parses per chunk,
+ * so per-chunk work tracks the tail size instead of the whole reply. Frozen
+ * blocks keep their source-offset keys when they cross the freeze boundary,
+ * so React reconciles instead of remounting. Known deviation while
+ * streaming: a reference-style link or footnote whose definition sits on the
+ * other side of the freeze boundary renders literally until the settled
+ * full parse self-heals it.
+ */
+
+import { memo, useMemo, useRef } from 'react'
+import type { ReactNode } from 'react'
+import { IncrementalMarkdownParser } from './incremental.ts'
+import { parseGfm, parseGfmWithMath } from './parse.ts'
+import {
+ collectReferenceTargets, createReferenceTargets, renderBlocks, renderFootnoteSection,
+ wrapBlockChildren,
+} from './render.tsx'
+import type { MarkdownCodeLabels, MarkdownFileMentions, MarkdownRenderContext, ReferenceTargets } from './render.tsx'
+import 'katex/dist/katex.min.css'
+import css from './MarkdownText.module.css'
+
+export type { MarkdownCodeLabels, MarkdownFileMentions } from './render.tsx'
+
+/** One settled full render: parse with math, resolve references, append the footnote section. */
+function renderSettled(
+ text: string,
+ codeLabels: MarkdownCodeLabels | undefined,
+ fileMentions: MarkdownFileMentions | undefined,
+): ReactNode[] {
+ const root = parseGfmWithMath(text)
+ const targets = createReferenceTargets()
+ collectReferenceTargets(root.children, targets)
+ const context: MarkdownRenderContext = {
+ streaming: false,
+ codeLabels,
+ fileMentions,
+ targets,
+ footnoteOrder: [],
+ footnoteCounts: new Map(),
+ }
+ const blocks = wrapBlockChildren(
+ renderBlocks(root.children.map((node, index) => ({ node, key: index })), context),
+ false,
+ )
+ const section = renderFootnoteSection(context)
+ return section === null ? blocks : [...blocks, '\n', section]
+}
+
+/**
+ * Streaming render state for one growing message: the incremental parser,
+ * the frozen blocks' cached elements, and the reference/footnote state their
+ * rendering consumed (footnote numbering assigned to frozen references is
+ * final, so the tail continues from a copy of it each frame).
+ */
+class StreamingRenderer {
+ private readonly parser = new IncrementalMarkdownParser(parseGfm)
+ private generation = -1
+ private frozenCount = 0
+ private frozenElements: ReactNode[] = []
+ private frozenTargets: ReferenceTargets = createReferenceTargets()
+ private frozenFootnoteOrder: string[] = []
+ private frozenFootnoteCounts = new Map<string, number>()
+ private lastText: string | null = null
+ private lastRendered: ReactNode[] = []
+
+ /** @param codeLabels - Fence copy labels baked into cached elements; the owner replaces the renderer when they change. */
+ constructor(private readonly codeLabels: MarkdownCodeLabels | undefined) {}
+
+ /**
+ * Render the current accumulated text. Idempotent per text value, so React
+ * may re-execute the calling render freely.
+ * @param text - The full accumulated markdown source.
+ * @returns Frozen elements, re-rendered tail, and the footnote section.
+ */
+ render(text: string): ReactNode[] {
+ if (text === this.lastText) return this.lastRendered
+ const { frozen, tail, generation } = this.parser.update(text)
+ if (generation !== this.generation) {
+ this.generation = generation
+ this.frozenCount = 0
+ this.frozenElements = []
+ this.frozenTargets = createReferenceTargets()
+ this.frozenFootnoteOrder = []
+ this.frozenFootnoteCounts = new Map()
+ }
+ const newlyFrozen = frozen.slice(this.frozenCount)
+ collectReferenceTargets(newlyFrozen.map(block => block.node), this.frozenTargets)
+ // Targets visible this frame: everything frozen so far plus the current
+ // tail parse — a newly frozen block's references resolved against the
+ // same parse tree its definitions came from.
+ const frameTargets: ReferenceTargets = {
+ definitions: new Map(this.frozenTargets.definitions),
+ footnotes: new Map(this.frozenTargets.footnotes),
+ }
+ collectReferenceTargets(tail.map(block => block.node), frameTargets)
+ if (newlyFrozen.length > 0) {
+ const frozenContext: MarkdownRenderContext = {
+ streaming: true,
+ codeLabels: this.codeLabels,
+ fileMentions: undefined,
+ targets: frameTargets,
+ footnoteOrder: this.frozenFootnoteOrder,
+ footnoteCounts: this.frozenFootnoteCounts,
+ }
+ // Separator newlines are cached alongside the elements so the
+ // assembled children match the settled pipeline's block wrapping.
+ const batch = [...this.frozenElements]
+ for (const element of renderBlocks(newlyFrozen, frozenContext)) {
+ if (batch.length > 0) batch.push('\n')
+ batch.push(element)
+ }
+ this.frozenElements = batch
+ this.frozenCount = frozen.length
+ }
+ const tailContext: MarkdownRenderContext = {
+ streaming: true,
+ codeLabels: this.codeLabels,
+ fileMentions: undefined,
+ targets: frameTargets,
+ footnoteOrder: [...this.frozenFootnoteOrder],
+ footnoteCounts: new Map(this.frozenFootnoteCounts),
+ }
+ const children = [...this.frozenElements]
+ for (const element of renderBlocks(tail, tailContext)) {
+ if (children.length > 0) children.push('\n')
+ children.push(element)
+ }
+ const section = renderFootnoteSection(tailContext)
+ if (section !== null) children.push('\n', section)
+ this.lastText = text
+ this.lastRendered = children
+ return this.lastRendered
+ }
+}
+
+/**
+ * Render untrusted assistant-authored Markdown as semantic React elements.
+ * @param props - Markdown source text preserved by the session projection;
+ * `streaming` renders fences and TeX plain (highlighting and KaTeX land on
+ * the finalize swap) and parses incrementally across chunks; `codeLabels`
+ * forwards localized copy-button labels to fence CodeBlocks — pass a
+ * reference-stable object (memoized per locale revision), because a new
+ * identity discards the streaming render cache mid-message. `fileMentions`
+ * links inline-code tokens its resolver recognizes as real files; this is
+ * the single streaming gate — it applies to settled renders only, because a
+ * streaming message's vocabulary is not final and frozen cached elements
+ * must not bake in handlers that could go stale.
+ * @returns A GFM document with TeX math rendered through KaTeX; raw HTML,
+ * relative links, and unsafe protocols are disabled, while absolute HTTP(S)
+ * images render directly.
+ */
+export const MarkdownText = memo(function MarkdownText({ text, streaming = false, codeLabels, fileMentions }: {
+ text: string
+ streaming?: boolean
+ codeLabels?: MarkdownCodeLabels | undefined
+ fileMentions?: MarkdownFileMentions | undefined
+}) {
+ const streamRef = useRef<StreamingRenderer | null>(null)
+ const streamLabelsRef = useRef<MarkdownCodeLabels | undefined>(codeLabels)
+ const children = useMemo(() => {
+ if (!streaming) {
+ streamRef.current = null
+ return renderSettled(text, codeLabels, fileMentions)
+ }
+ if (streamRef.current === null || streamLabelsRef.current !== codeLabels) {
+ streamRef.current = new StreamingRenderer(codeLabels)
+ streamLabelsRef.current = codeLabels
+ }
+ return streamRef.current.render(text)
+ }, [text, streaming, codeLabels, fileMentions])
+ return <div className={css.markdown}>{children}</div>
+})
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/cjkFriendlyStrong.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/cjkFriendlyStrong.ts
new file mode 100644
index 0000000000..ba736b53be
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/cjkFriendlyStrong.ts
@@ -0,0 +1,85 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Let asterisk strong emphasis close after punctuation when CJK prose continues without whitespace. */
+
+import { attention } from 'micromark-core-commonmark'
+import { unicodePunctuation } from 'micromark-util-character'
+import { classifyCharacter } from 'micromark-util-classify-character'
+import { codes, constants } from 'micromark-util-symbol'
+import type { Construct, Extension, State, Tokenizer } from 'micromark-util-types'
+
+const cjkCharacter = new RegExp([
+ '\\p{Script_Extensions=Han}',
+ '\\p{Script_Extensions=Hiragana}',
+ '\\p{Script_Extensions=Katakana}',
+ '\\p{Script_Extensions=Hangul}',
+ '\\p{Script_Extensions=Bopomofo}',
+].join('|'), 'u')
+
+function isCjkCharacter(code: number | null): boolean {
+ return code !== null && code >= 0 && cjkCharacter.test(String.fromCodePoint(code))
+}
+
+const tokenizeCjkFriendlyAttention: Tokenizer = function (effects, ok, nok) {
+ const configuredAttentionMarkers = this.parser.constructs.attentionMarkers.null
+ if (configuredAttentionMarkers === undefined) {
+ throw new Error('micromark CommonMark attention markers are unavailable')
+ }
+ const attentionMarkers = configuredAttentionMarkers
+ const previous = this.previous
+ const before = classifyCharacter(previous)
+ let marker: number | null = codes.eof
+
+ return start
+
+ function start(code: number | null): State | undefined {
+ /* v8 ignore next -- this text construct is dispatched only for an asterisk. */
+ if (code !== codes.asterisk) return nok(code)
+ marker = code
+ effects.enter('attentionSequence')
+ return inside(code)
+ }
+
+ function inside(code: number | null): State | undefined {
+ if (code === marker) {
+ effects.consume(code)
+ return inside
+ }
+
+ const token = effects.exit('attentionSequence')
+ const after = classifyCharacter(code)
+ const open = !after || (after === constants.characterGroupPunctuation && Boolean(before))
+ || attentionMarkers.includes(code)
+ const commonMarkClose = !before
+ || (before === constants.characterGroupPunctuation && Boolean(after))
+ || attentionMarkers.includes(previous)
+ const markerCount = token.end.offset - token.start.offset
+ const cjkStrongClose = markerCount >= 2
+ && unicodePunctuation(previous)
+ && isCjkCharacter(code)
+ const close = commonMarkClose || cjkStrongClose
+
+ token._open = open
+ token._close = close
+ return ok(code)
+ }
+}
+
+const cjkFriendlyAttention: Construct = {
+ name: 'cjkFriendlyAttention',
+ resolveAll: attention.resolveAll,
+ tokenize: tokenizeCjkFriendlyAttention,
+}
+
+const cjkFriendlyStrongExtension: Extension = {
+ text: { [codes.asterisk]: cjkFriendlyAttention },
+}
+
+/**
+ * Extend CommonMark asterisk strong emphasis for punctuation-delimited CJK
+ * prose, as a micromark syntax extension for `fromMarkdown`.
+ * @returns The micromark syntax extension.
+ */
+export function cjkFriendlyStrong(): Extension {
+ return cjkFriendlyStrongExtension
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/highlight.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/highlight.ts
new file mode 100644
index 0000000000..2f97b889c2
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/highlight.ts
@@ -0,0 +1,313 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * The client's ONE syntax highlighter: a synchronous fine-grained shiki core
+ * (JavaScript regex engine — no oniguruma WASM, bundle-friendly) with an
+ * explicit grammar allowlist and a CSS-variables theme. Colors live in the
+ * theme package's token sheets as `--shiki-*` custom properties (light and
+ * dark blocks), never here — the repo's tokens-only styling rule.
+ *
+ * Only the three markdown-fence and `run_code` grammars (TypeScript, shell,
+ * JSON) load into the singleton at boot — the set every session renders. The
+ * read card's wider extension set (the file-extension language hints the read
+ * tool's `langFromPath` emits — `packages/fs/tool-fs`: python, rust, yaml,
+ * markup, …) is imported lazily and registered the first time such a language
+ * is requested, so a session that never opens a read card in one of those
+ * languages pays neither the ~1.6 MB of grammar modules nor their synchronous
+ * init. The first render of a lazy language falls back to plain text while its
+ * grammar loads, then {@link onGrammarLoaded} notifies subscribers to re-render
+ * with highlighting. An unknown or absent language falls back to plain text (no
+ * highlighting, still monospace) — never an error.
+ */
+
+import { createHighlighterCoreSync, createCssVariablesTheme } from 'shiki/core'
+import { createJavaScriptRegexEngine, defaultJavaScriptRegexConstructor } from 'shiki/engine/javascript'
+import langTs from '@shikijs/langs/typescript'
+import langBash from '@shikijs/langs/shellscript'
+import langJson from '@shikijs/langs/json'
+import type { HighlighterCore } from 'shiki/core'
+import type { CSSProperties } from 'react'
+
+/** A shiki grammar module's default export (a `LanguageRegistration[]`), taken
+ * from a boot grammar so no direct `@shikijs/types` dependency is needed. */
+type LangModule = { default: typeof langTs }
+
+/**
+ * Grammars the singleton loads at boot; each entry's own `name` is the id
+ * `codeToTokens`/`codeToHtml` resolve. The JS-family aliases (js/jsx/ts/tsx)
+ * resolve to the TypeScript grammar rather than a separate one: it tokenizes
+ * plain TS/JS exactly, and JSX/TSX approximately (shiki's TS grammar is not the
+ * dedicated TSX grammar, so JSX elements tokenize imperfectly) — an accepted
+ * trade to keep the boot set to one JS-family grammar. The read card's wider
+ * set loads lazily through {@link LAZY_GRAMMARS}.
+ */
+const LANGS = [langTs, langBash, langJson]
+
+/**
+ * The read card's extension grammars, each behind a dynamic import so its
+ * module stays out of the boot chunk until a read of that language renders.
+ * Keyed by the grammar id (`LanguageRegistration.name`) the aliases resolve to.
+ * `@shikijs/langs`' default export is a `LanguageRegistration[]`; the loader
+ * hands the whole array to `loadLanguageSync`, which registers each entry
+ * (including embedded sub-grammars). The three boot grammars are absent —
+ * already loaded, so no alias value ever points at a missing entry here.
+ */
+const LAZY_GRAMMARS = new Map<string, () => Promise<LangModule>>([
+ ['python', () => import('@shikijs/langs/python')],
+ ['ruby', () => import('@shikijs/langs/ruby')],
+ ['go', () => import('@shikijs/langs/go')],
+ ['rust', () => import('@shikijs/langs/rust')],
+ ['java', () => import('@shikijs/langs/java')],
+ ['c', () => import('@shikijs/langs/c')],
+ ['cpp', () => import('@shikijs/langs/cpp')],
+ ['csharp', () => import('@shikijs/langs/csharp')],
+ ['kotlin', () => import('@shikijs/langs/kotlin')],
+ ['swift', () => import('@shikijs/langs/swift')],
+ ['php', () => import('@shikijs/langs/php')],
+ ['yaml', () => import('@shikijs/langs/yaml')],
+ ['toml', () => import('@shikijs/langs/toml')],
+ ['ini', () => import('@shikijs/langs/ini')],
+ ['markdown', () => import('@shikijs/langs/markdown')],
+ ['mdx', () => import('@shikijs/langs/mdx')],
+ ['html', () => import('@shikijs/langs/html')],
+ ['css', () => import('@shikijs/langs/css')],
+ ['scss', () => import('@shikijs/langs/scss')],
+ ['less', () => import('@shikijs/langs/less')],
+ ['sql', () => import('@shikijs/langs/sql')],
+ ['xml', () => import('@shikijs/langs/xml')],
+ ['lua', () => import('@shikijs/langs/lua')],
+])
+
+/**
+ * Language ids (and aliases) the highlighter accepts; everything else renders
+ * plain. A Map, not an object: fence info strings are assistant-authored, so
+ * a label like `constructor` or `__proto__` must miss instead of resolving an
+ * inherited property and crashing the renderer inside shiki. Keys cover both
+ * the markdown-fence aliases `CodeBlock` uses and the file-extension hint ids
+ * the read tool's `langFromPath` emits, so both callers resolve the same
+ * grammars. The JS family maps to the TypeScript grammar (see {@link LANGS} for
+ * the JSX/TSX approximation). A value not in {@link LANGS} names a
+ * {@link LAZY_GRAMMARS} entry loaded on first use.
+ */
+const LANG_ALIASES = new Map<string, string>([
+ ['typescript', 'typescript'],
+ ['ts', 'typescript'],
+ ['tsx', 'typescript'],
+ ['javascript', 'typescript'],
+ ['js', 'typescript'],
+ ['jsx', 'typescript'],
+ ['shellscript', 'shellscript'],
+ ['bash', 'shellscript'],
+ ['sh', 'shellscript'],
+ ['shell', 'shellscript'],
+ ['zsh', 'shellscript'],
+ ['json', 'json'],
+ ['jsonc', 'json'],
+ ['py', 'python'],
+ ['python', 'python'],
+ ['rb', 'ruby'],
+ ['ruby', 'ruby'],
+ ['go', 'go'],
+ ['rs', 'rust'],
+ ['rust', 'rust'],
+ ['java', 'java'],
+ ['c', 'c'],
+ ['cpp', 'cpp'],
+ ['cs', 'csharp'],
+ ['csharp', 'csharp'],
+ ['kotlin', 'kotlin'],
+ ['swift', 'swift'],
+ ['php', 'php'],
+ ['yaml', 'yaml'],
+ ['yml', 'yaml'],
+ ['toml', 'toml'],
+ ['ini', 'ini'],
+ ['md', 'markdown'],
+ ['markdown', 'markdown'],
+ ['mdx', 'mdx'],
+ ['html', 'html'],
+ ['css', 'css'],
+ ['scss', 'scss'],
+ ['less', 'less'],
+ ['sql', 'sql'],
+ ['xml', 'xml'],
+ ['lua', 'lua'],
+])
+
+/** All token colors resolve through `--shiki-*` custom properties (theme package sheets). */
+const cssVariablesTheme = createCssVariablesTheme({
+ name: 'css-variables',
+ variablePrefix: '--shiki-',
+ fontStyle: true,
+})
+
+/**
+ * The client regex engine compiles each TextMate pattern when its scanner is
+ * created. Shiki otherwise defers patterns longer than 3,000 characters until
+ * their first match; that compilation counts against Shiki's 500 ms per-line
+ * budget and can return a partial token stream under host contention. Eager
+ * compilation leaves the same budget in place for scanning user content.
+ */
+const regexEngine = createJavaScriptRegexEngine({
+ forgiving: true,
+ regexConstructor: pattern => defaultJavaScriptRegexConstructor(pattern, {
+ lazyCompileLength: Number.POSITIVE_INFINITY,
+ }),
+})
+
+let singleton: HighlighterCore | undefined
+
+/** Representative paths through every boot grammar, compiled before user content is timed. */
+const BOOT_GRAMMAR_WARMUPS = [
+ { lang: 'typescript', code: 'const answer: number = 42' },
+ { lang: 'shellscript', code: 'printf \'%s\\n\' "$HOME"' },
+ { lang: 'json', code: '{"ready":true}' },
+] as const
+
+/** Construct and pre-tokenize the boot grammars outside the user-content scan budget. */
+function createHighlighter(): HighlighterCore {
+ const instance = createHighlighterCoreSync({
+ themes: [cssVariablesTheme],
+ langs: LANGS,
+ engine: regexEngine,
+ })
+ for (const sample of BOOT_GRAMMAR_WARMUPS) {
+ instance.codeToTokens(sample.code, {
+ lang: sample.lang,
+ theme: 'css-variables',
+ tokenizeTimeLimit: 0,
+ })
+ }
+ return instance
+}
+
+/** The synchronous highlighter (one instance per document); pre-warmed below, lazy as the fallback. */
+function highlighter(): HighlighterCore {
+ singleton ??= createHighlighter()
+ return singleton
+}
+
+/** Grammar ids whose lazy import is in flight or done, so it is requested once. */
+const requested = new Set<string>()
+/** Subscribers re-rendered after a lazy grammar registers (React callers). */
+const listeners = new Set<() => void>()
+/** Bumped on each lazy-grammar load; the `useSyncExternalStore` snapshot. */
+let loadCount = 0
+
+/**
+ * Subscribe to lazy-grammar load completions; `listener` fires after a
+ * {@link LAZY_GRAMMARS} grammar finishes registering on the singleton, so a
+ * caller that rendered its plain fallback while the grammar loaded can
+ * re-highlight. Uses the `useSyncExternalStore` subscribe signature; pair it with
+ * {@link grammarLoadCount} as the snapshot. Returns an unsubscribe function.
+ * @param listener - invoked (no args) on each grammar-load completion.
+ * @returns a disposer that removes the listener.
+ */
+export function subscribeGrammarLoaded(listener: () => void): () => void {
+ listeners.add(listener)
+ return () => { listeners.delete(listener) }
+}
+
+/**
+ * The lazy-grammar load counter — a value that changes on every load, so a
+ * `useSyncExternalStore` snapshot re-renders the subscriber when a grammar
+ * registers. Opaque: only its identity across renders matters.
+ * @returns the current load count.
+ */
+export function grammarLoadCount(): number {
+ return loadCount
+}
+
+/**
+ * Ensure the grammar `resolved` names is registered. A boot grammar (not in
+ * {@link LAZY_GRAMMARS}) and an already-loaded lazy grammar report ready
+ * synchronously; a lazy grammar not yet loaded starts its import (once) and
+ * reports not-ready, so the caller renders plain until a
+ * {@link subscribeGrammarLoaded} listener fires.
+ * @param resolved - the grammar id an alias resolved to.
+ * @returns whether the grammar is registered and ready to tokenize now.
+ */
+function ensureGrammar(resolved: string): boolean {
+ const load = LAZY_GRAMMARS.get(resolved)
+ // A boot grammar (already registered) has no lazy loader; it is always ready.
+ if (load === undefined) return true
+ if (highlighter().getLoadedLanguages().includes(resolved)) return true
+ if (!requested.has(resolved)) {
+ requested.add(resolved)
+ void load().then((mod) => {
+ highlighter().loadLanguageSync(mod.default)
+ loadCount += 1
+ for (const listener of listeners) listener()
+ })
+ }
+ return false
+}
+
+// Engine + grammar construction costs a long task (~120-175ms); building it
+// during the first finalized fence's render would jank exactly when a stream
+// completes. Warm the singleton in a deferred task at module load (= plugin
+// boot) instead; the lazy path above stays as the correctness fallback for a
+// fence that renders before the timer fires. `unref` (Node-only) keeps a
+// non-browser import from pinning the event loop.
+const warmupTimer = setTimeout(() => { highlighter() }, 0)
+;(warmupTimer as { unref?: () => void }).unref?.()
+
+/**
+ * Highlight `code` into shiki's HTML (a single `<pre class="shiki">` tree)
+ * when `lang` maps to a registered grammar; `undefined` means the caller
+ * renders its plain fallback. A lazy grammar not yet loaded returns `undefined`
+ * for this call and loads in the background; subscribe with
+ * {@link onGrammarLoaded} to re-highlight once it registers.
+ * @param code - the source text.
+ * @param lang - the language hint (a markdown fence info string or a fixed caller id).
+ * @returns the highlighted HTML, or `undefined` for unknown or not-yet-loaded languages.
+ */
+export function highlightToHtml(code: string, lang: string | undefined): string | undefined {
+ const resolved = lang === undefined ? undefined : LANG_ALIASES.get(lang.toLowerCase())
+ if (resolved === undefined) return undefined
+ if (!ensureGrammar(resolved)) return undefined
+ return highlighter().codeToHtml(code, { lang: resolved, theme: 'css-variables' })
+}
+
+/**
+ * One highlighted run of a line: the text and the inline style shiki assigned
+ * it. The css-variables theme colors every run through a `--shiki-*` custom
+ * property, so `style.color` is always present; it is held as a style object
+ * rather than a bare color so a run spreads onto a `<span style>` uniformly.
+ */
+export interface HighlightSpan {
+ text: string
+ style: CSSProperties
+}
+
+/**
+ * Tokenize `code` into per-line highlighted runs when `lang` maps to a
+ * registered grammar; `undefined` means the caller renders its plain fallback.
+ * A line-numbered view needs the token runs split per line (one gutter number
+ * per line), which the single-`<pre>` {@link highlightToHtml} does not expose,
+ * so this returns shiki's own 2D line/token structure narrowed to what a run
+ * renders. Each run's color is a `--shiki-*` custom property, keeping token
+ * colors on the theme package's sheets exactly as the HTML path does; the
+ * css-variables theme carries no font-style bits, matching that path's
+ * color-only output. The trailing newline shiki appends as a final empty line
+ * is dropped so the run count matches the caller's own line array.
+ * @param code - the source text.
+ * @param lang - the language hint (a file-extension-derived language id).
+ * @returns one entry per source line (each an array of runs), or `undefined` for unknown or not-yet-loaded languages.
+ */
+export function highlightLines(code: string, lang: string | undefined): HighlightSpan[][] | undefined {
+ const resolved = lang === undefined ? undefined : LANG_ALIASES.get(lang.toLowerCase())
+ if (resolved === undefined) return undefined
+ if (!ensureGrammar(resolved)) return undefined
+ const { tokens } = highlighter().codeToTokens(code, { lang: resolved, theme: 'css-variables' })
+ // shiki tokenizes `a\nb` into two lines; a trailing newline (`a\n`) adds a
+ // third, empty line the caller's own line array does not carry. Drop that
+ // one terminator line so the two structures stay in step. The explicit
+ // `last !== undefined` (over `tokens[...]?.length`) keeps a single branch for
+ // per-file coverage, matching TerminalBlock's terminator check.
+ const last = tokens[tokens.length - 1]
+ const lines = tokens.length > 1 && last !== undefined && last.length === 0
+ ? tokens.slice(0, -1)
+ : tokens
+ return lines.map(line => line.map(token => ({ text: token.content, style: { color: token.color } })))
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/incremental.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/incremental.ts
new file mode 100644
index 0000000000..9aa48de469
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/incremental.ts
@@ -0,0 +1,132 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Incremental block-level markdown parsing for an append-only text stream.
+ *
+ * Re-parsing the whole accumulated document on every streaming chunk is
+ * quadratic in the final reply length. CommonMark block parsing is line-based
+ * and appended text can only reshape the parse frontier — the last top-level
+ * block (a paragraph becoming a setext heading or a table, a list continuing
+ * after a blank line, an unclosed fence swallowing lines) — so earlier blocks
+ * are final. This parser therefore freezes all but the trailing
+ * {@link UNSTABLE_TAIL_BLOCKS} blocks and re-parses only the source tail
+ * behind them: each source region is parsed O(1) times over the stream
+ * instead of once per chunk.
+ *
+ * The freeze boundary comes from the parser's own `position` offsets, never
+ * from custom source scanning. The cut sits at the *end offset* of the last
+ * frozen block (not the next block's start): a following block's start offset
+ * excludes up to three spaces of insignificant leading indentation, which is
+ * harmless to drop, but cutting at the previous end also keeps the
+ * inter-block blank lines in the tail so the sliced source stays verbatim.
+ *
+ * Known deviation, shared with any prefix-freeze scheme: micromark resolves
+ * reference-style links and footnotes document-wide at parse time, so a
+ * reference whose definition lands on the other side of the freeze boundary
+ * renders literally until the settled full parse self-heals it.
+ */
+
+import type { Root, RootContent } from 'mdast'
+
+/**
+ * Trailing blocks kept unstable. Appended text reshapes at most the last
+ * block; the second-to-last is retained as safety margin so a freeze decision
+ * never has to reason about the parse frontier.
+ */
+const UNSTABLE_TAIL_BLOCKS = 2
+
+/** A top-level mdast block plus a render key that is stable across chunks. */
+export interface PositionedBlock {
+ /** The parsed block. Positions inside it are relative to its parse slice. */
+ readonly node: RootContent
+ /**
+ * The block's start offset in the full source text. Stable from the frame
+ * a block first appears through freezing, so React reconciles rather than
+ * remounts when a block crosses the freeze boundary.
+ */
+ readonly key: number
+}
+
+/** One {@link IncrementalMarkdownParser.update} result. */
+export interface IncrementalBlocks {
+ /** Blocks that can no longer change; grows monotonically per generation. */
+ readonly frozen: readonly PositionedBlock[]
+ /** The re-parsed unstable tail (at most {@link UNSTABLE_TAIL_BLOCKS} blocks plus growth). */
+ readonly tail: readonly PositionedBlock[]
+ /** Bumped whenever non-append input discards the frozen prefix; callers drop caches keyed on it. */
+ readonly generation: number
+}
+
+/**
+ * A block's render key: its absolute source start offset. A position-less
+ * node (a grammar is free to omit positions) falls back to a negative
+ * list-index key — unique within one update's tail, which is the only place
+ * the fallback can occur: freezing requires the cut block's position, so a
+ * position-less parse keeps every block in the tail (real grammars always
+ * stamp positions and never take this path).
+ */
+function blockKey(node: RootContent, base: number, index: number): number {
+ const offset = node.position?.start.offset
+ return offset === undefined ? -(index + 1) : base + offset
+}
+
+/**
+ * Append-only incremental parser over a caller-supplied grammar. One instance
+ * accumulates one streaming document; non-append input resets it.
+ */
+export class IncrementalMarkdownParser {
+ private prevText = ''
+ private tailStart = 0
+ private frozen: PositionedBlock[] = []
+ private generation = 0
+ private cached: IncrementalBlocks | null = null
+
+ /** @param parse - Grammar shared with whatever renders the blocks, so boundaries agree. */
+ constructor(private readonly parse: (text: string) => Root) {}
+
+ /**
+ * Fold the current accumulated text and return the frozen/tail split.
+ * Idempotent for identical input (the previous result is returned as-is),
+ * so callers may invoke it from render paths that re-execute.
+ * @param text - The full accumulated markdown source.
+ * @returns Frozen and tail blocks with stream-stable render keys.
+ */
+ update(text: string): IncrementalBlocks {
+ if (this.cached !== null && text === this.prevText) return this.cached
+ // Deliberate O(prefix) memcmp per update: sound divergence detection has
+ // to verify the whole retained prefix, and startsWith compares bytes two
+ // orders of magnitude faster than parsing them — the cost this class
+ // exists to remove. Passing append/reset deltas instead would push
+ // append bookkeeping across the session-projection update boundary for a check
+ // that stays sub-millisecond at realistic reply sizes.
+ if (!text.startsWith(this.prevText)) {
+ this.prevText = ''
+ this.tailStart = 0
+ this.frozen = []
+ this.generation += 1
+ }
+ this.prevText = text
+ const base = this.tailStart
+ const blocks = this.parse(text.slice(base)).children
+ let firstUnstable = Math.max(0, blocks.length - UNSTABLE_TAIL_BLOCKS)
+ if (firstUnstable > 0) {
+ const cutEnd = blocks[firstUnstable - 1]?.position?.end.offset
+ if (cutEnd === undefined) {
+ // A grammar that omits positions leaves nothing to cut at; keep the
+ // whole parse in the tail rather than guessing a boundary.
+ firstUnstable = 0
+ } else {
+ for (const node of blocks.slice(0, firstUnstable)) {
+ this.frozen.push({ node, key: blockKey(node, base, this.frozen.length) })
+ }
+ this.tailStart = base + cutEnd
+ }
+ }
+ const tail = blocks.slice(firstUnstable).map((node, index) => ({
+ node,
+ key: blockKey(node, base, index),
+ }))
+ this.cached = { frozen: [...this.frozen], tail, generation: this.generation }
+ return this.cached
+ }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/katex.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/katex.tsx
new file mode 100644
index 0000000000..83dc74a5d3
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/katex.tsx
@@ -0,0 +1,92 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * TeX-to-React via KaTeX, replicating the rehype-katex pipeline this renderer
+ * replaced: the same three-arm error chain (strict render, `strict: 'ignore'`
+ * retry, error span) and a DOM-identical element tree, so settled math keeps
+ * its exact markup. KaTeX emits an HTML string; the browser's own HTML parser
+ * (`DOMParser`, applying the spec's SVG/MathML foreign-content attribute
+ * adjustments KaTeX output relies on) turns it into a tree this module maps
+ * onto React elements — KaTeX output is a static span/MathML/SVG vocabulary
+ * with no raw user HTML, the same trust shiki's tree gets in CodeBlock.
+ *
+ * React 18 has no MathML support, so the `.katex-mathml` subtree's elements
+ * land in the HTML namespace — exactly as they did under the replaced
+ * hast-util-to-jsx-runtime pipeline. The visual arm is the `.katex-html`
+ * span tree; the MathML arm serves assistive technology, which reads it by
+ * tag name regardless of namespace.
+ */
+
+import { createElement } from 'react'
+import type { CSSProperties, ReactNode } from 'react'
+import katex from 'katex'
+
+/**
+ * Convert one inline `style` attribute string into React's style object.
+ * KaTeX emits only plain kebab-case declarations (no custom properties and no
+ * nameless declarations), so camel-casing the property is the whole mapping.
+ */
+function styleObject(css: string): CSSProperties {
+ const style: Record<string, string> = {}
+ for (const declaration of css.split(';')) {
+ const colon = declaration.indexOf(':')
+ if (colon === -1) continue
+ const name = declaration.slice(0, colon).trim()
+ const key = name.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase())
+ style[key] = declaration.slice(colon + 1).trim()
+ }
+ return style
+}
+
+/** Map one parsed DOM node onto a React element (text nodes pass through). */
+function domToReact(node: ChildNode, key: number): ReactNode {
+ if (node.nodeType === Node.TEXT_NODE) return node.textContent
+ /* v8 ignore next 2 -- KaTeX output holds only elements and text; other
+ node kinds cannot appear in its serialized vocabulary. */
+ if (node.nodeType !== Node.ELEMENT_NODE) return null
+ const element = node as Element
+ const props: Record<string, unknown> = { key }
+ for (const attribute of element.attributes) {
+ if (attribute.name === 'class') props['className'] = attribute.value
+ else if (attribute.name === 'style') props['style'] = styleObject(attribute.value)
+ else props[attribute.name] = attribute.value
+ }
+ const children = [...element.childNodes].map(domToReact)
+ return children.length === 0
+ ? createElement(element.localName, props)
+ : createElement(element.localName, props, ...children)
+}
+
+/**
+ * Render TeX source to React elements through KaTeX.
+ * @param value - The TeX source (math node value; fenced `math` blocks append
+ * their trailing newline to match the replaced pipeline's text extraction).
+ * @param displayMode - Display (block) versus inline rendering.
+ * @returns KaTeX's element tree, or the error span when the source does not
+ * parse (colored with KaTeX's stock `errorColor`, matching rehype-katex).
+ */
+export function renderTexToReact(value: string, displayMode: boolean): ReactNode {
+ let html: string
+ try {
+ html = katex.renderToString(value, { displayMode, throwOnError: true })
+ } catch (error) {
+ try {
+ html = katex.renderToString(value, { displayMode, strict: 'ignore', throwOnError: false })
+ } catch {
+ // KaTeX renders ParseErrors itself under throwOnError: false; only its
+ // internal errors reach here, so mirror rehype-katex's manual span.
+ /* v8 ignore next 8 */
+ return (
+ <span
+ className="katex-error"
+ style={{ color: 'var(--trajectory-math-error)' }}
+ title={String(error)}
+ >
+ {value}
+ </span>
+ )
+ }
+ }
+ const parsed = new DOMParser().parseFromString(html, 'text/html')
+ return [...parsed.body.childNodes].map(domToReact)
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/mathCompatibility.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/mathCompatibility.ts
new file mode 100644
index 0000000000..8ceedf5bb5
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/mathCompatibility.ts
@@ -0,0 +1,351 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Extend upstream dollar-only math syntax with TeX delimiters while reusing its token vocabulary. */
+
+import { factorySpace } from 'micromark-factory-space'
+import type {} from 'micromark-extension-math'
+import { markdownLineEnding } from 'micromark-util-character'
+import { codes, constants, types } from 'micromark-util-symbol'
+import type { Construct, Extension, Previous, State, Tokenizer } from 'micromark-util-types'
+
+// oxlint-disable typescript/no-this-alias -- micromark binds tokenizer context only on the outer callback.
+
+const previousBackslash: Previous = function (code) {
+ if (code !== codes.backslash) return true
+ const tail = this.events.at(-1)
+ /* v8 ignore next -- a previous code necessarily has a preceding event. */
+ if (tail === undefined) return false
+ return tail[1].type === types.characterEscape
+}
+
+const tokenizeBackslashMathText: Tokenizer = function (effects, ok, nok) {
+ return start
+
+ function start(code: number | null): State | undefined {
+ /* v8 ignore next -- the text construct is dispatched only for a backslash. */
+ if (code !== codes.backslash) return nok(code)
+ effects.enter('mathText')
+ effects.enter('mathTextSequence')
+ effects.consume(code)
+ return open
+ }
+
+ function open(code: number | null): State | undefined {
+ if (code !== codes.leftParenthesis) return nok(code)
+ effects.consume(code)
+ effects.exit('mathTextSequence')
+ return between
+ }
+
+ function between(code: number | null): State | undefined {
+ if (code === codes.eof) return nok(code)
+ if (code === codes.backslash) {
+ return effects.attempt({ partial: true, tokenize: tokenizeClose }, close, afterCloseAttempt)(code)
+ }
+ if (markdownLineEnding(code)) {
+ effects.enter(types.lineEnding)
+ effects.consume(code)
+ effects.exit(types.lineEnding)
+ return between
+ }
+ return dataStart(code)
+ }
+
+ function afterCloseAttempt(code: number | null): State | undefined {
+ return effects.check({ partial: true, tokenize: tokenizeOpen }, nok, dataStart)(code)
+ }
+
+ function dataStart(code: number | null): State | undefined {
+ effects.enter('mathTextData')
+ effects.consume(code)
+ return code === codes.backslash ? afterDataBackslash : data
+ }
+
+ function afterDataBackslash(code: number | null): State | undefined {
+ if (code === codes.backslash) {
+ effects.consume(code)
+ return data
+ }
+ return data(code)
+ }
+
+ function data(code: number | null): State | undefined {
+ if (code === codes.eof || code === codes.backslash || markdownLineEnding(code)) {
+ effects.exit('mathTextData')
+ return between(code)
+ }
+ effects.consume(code)
+ return data
+ }
+
+ function close(code: number | null): State | undefined {
+ effects.exit('mathText')
+ return ok(code)
+ }
+
+ function tokenizeClose(closeEffects: Parameters<Tokenizer>[0], closeOk: State, closeNok: State): State {
+ return slash
+
+ function slash(code: number | null): State | undefined {
+ /* v8 ignore next -- this partial construct is attempted only at a backslash. */
+ if (code !== codes.backslash) return closeNok(code)
+ closeEffects.enter('mathTextSequence')
+ closeEffects.consume(code)
+ return parenthesis
+ }
+
+ function parenthesis(code: number | null): State | undefined {
+ if (code !== codes.rightParenthesis) return closeNok(code)
+ closeEffects.consume(code)
+ closeEffects.exit('mathTextSequence')
+ return closeOk
+ }
+ }
+
+ function tokenizeOpen(openEffects: Parameters<Tokenizer>[0], openOk: State, openNok: State): State {
+ return slash
+
+ function slash(code: number | null): State | undefined {
+ /* v8 ignore next -- the opening check follows a failed close attempt at a backslash. */
+ if (code !== codes.backslash) return openNok(code)
+ openEffects.enter(types.chunkString)
+ openEffects.consume(code)
+ return parenthesis
+ }
+
+ function parenthesis(code: number | null): State | undefined {
+ if (code !== codes.leftParenthesis) return openNok(code)
+ openEffects.consume(code)
+ openEffects.exit(types.chunkString)
+ return openOk
+ }
+ }
+}
+
+function createMathFlow(marker: number, openMarker: number, closeMarker: number, multiline: boolean): Construct {
+ const tokenize: Tokenizer = function (effects, ok, nok) {
+ const self = this
+ let oddBackslashRun = false
+ const tail = self.events.at(-1)
+ const initialSize = tail?.[1].type === types.linePrefix
+ ? tail[2].sliceSerialize(tail[1], true).length
+ : 0
+
+ return start
+
+ function start(code: number | null): State | undefined {
+ /* v8 ignore next -- the flow construct is dispatched only for its marker. */
+ if (code !== marker) return nok(code)
+ effects.enter('mathFlow')
+ effects.enter('mathFlowFence')
+ effects.enter('mathFlowFenceSequence')
+ effects.consume(code)
+ return open
+ }
+
+ function open(code: number | null): State | undefined {
+ if (code !== openMarker) return nok(code)
+ effects.consume(code)
+ effects.exit('mathFlowFenceSequence')
+ effects.exit('mathFlowFence')
+ return marker === codes.dollarSign ? afterDollarOpen : content
+ }
+
+ function afterDollarOpen(code: number | null): State | undefined {
+ return code === codes.dollarSign ? nok(code) : content(code)
+ }
+
+ function content(code: number | null): State | undefined {
+ if (code === codes.eof) return nok(code)
+ if (code === marker && (marker !== codes.dollarSign || !oddBackslashRun)) {
+ return effects.attempt(
+ { partial: true, tokenize: tokenizeClosingFence },
+ closed,
+ afterClosingFenceAttempt,
+ )(code)
+ }
+ if (markdownLineEnding(code)) {
+ return multiline
+ ? effects.attempt(nonLazyContinuation, afterContinuation, nok)(code)
+ : nok(code)
+ }
+ return valueStart(code)
+ }
+
+ function afterClosingFenceAttempt(code: number | null): State | undefined {
+ return marker === codes.backslash
+ ? effects.check({ partial: true, tokenize: tokenizeOpeningFence }, nok, markerValueStart)(code)
+ : markerValueStart(code)
+ }
+
+ function afterContinuation(code: number | null): State | undefined {
+ return effects.attempt(
+ { partial: true, tokenize: tokenizeClosingFence },
+ closed,
+ initialSize
+ ? factorySpace(effects, content, types.linePrefix, initialSize + 1)
+ : content,
+ )(code)
+ }
+
+ function valueStart(code: number | null): State | undefined {
+ effects.enter('mathFlowValue')
+ oddBackslashRun = code === codes.backslash
+ effects.consume(code)
+ return value
+ }
+
+ function markerValueStart(code: number | null): State | undefined {
+ effects.enter('mathFlowValue')
+ oddBackslashRun = false
+ effects.consume(code)
+ return valueAfterMarker
+ }
+
+ function valueAfterMarker(code: number | null): State | undefined {
+ if (code === marker) {
+ effects.consume(code)
+ return value
+ }
+ return value(code)
+ }
+
+ function value(code: number | null): State | undefined {
+ if (code === codes.eof || code === marker || markdownLineEnding(code)) {
+ effects.exit('mathFlowValue')
+ return content(code)
+ }
+ oddBackslashRun = code === codes.backslash ? !oddBackslashRun : false
+ effects.consume(code)
+ return value
+ }
+
+ function closed(code: number | null): State | undefined {
+ effects.exit('mathFlow')
+ return ok(code)
+ }
+
+ function tokenizeClosingFence(
+ closeEffects: Parameters<Tokenizer>[0],
+ closeOk: State,
+ closeNok: State,
+ ): State {
+ return factorySpace(closeEffects, sequenceStart, types.linePrefix, constants.tabSize)
+
+ function sequenceStart(code: number | null): State | undefined {
+ if (code !== marker) return closeNok(code)
+ closeEffects.enter('mathFlowFence')
+ closeEffects.enter('mathFlowFenceSequence')
+ closeEffects.consume(code)
+ return sequenceEnd
+ }
+
+ function sequenceEnd(code: number | null): State | undefined {
+ if (code !== closeMarker) return closeNok(code)
+ closeEffects.consume(code)
+ closeEffects.exit('mathFlowFenceSequence')
+ return factorySpace(closeEffects, after, types.whitespace)
+ }
+
+ function after(code: number | null): State | undefined {
+ if (code !== codes.eof && !markdownLineEnding(code)) return closeNok(code)
+ closeEffects.exit('mathFlowFence')
+ return closeOk(code)
+ }
+ }
+
+ function tokenizeOpeningFence(
+ openEffects: Parameters<Tokenizer>[0],
+ openOk: State,
+ openNok: State,
+ ): State {
+ return sequenceStart
+
+ function sequenceStart(code: number | null): State | undefined {
+ /* v8 ignore next -- the opening check follows a failed close attempt at the marker. */
+ if (code !== marker) return openNok(code)
+ openEffects.enter(types.chunkString)
+ openEffects.consume(code)
+ return sequenceEnd
+ }
+
+ function sequenceEnd(code: number | null): State | undefined {
+ if (code !== openMarker) return openNok(code)
+ openEffects.consume(code)
+ openEffects.exit(types.chunkString)
+ return openOk
+ }
+ }
+ }
+
+ return {
+ concrete: true,
+ name: marker === codes.dollarSign ? 'sameLineDollarMathFlow' : 'backslashMathFlow',
+ tokenize,
+ }
+}
+
+const tokenizeNonLazyContinuation: Tokenizer = function (effects, ok, nok) {
+ const self = this
+
+ return start
+
+ function start(code: number | null): State | undefined {
+ /* v8 ignore next -- continuation constructs are attempted only after a line ending. */
+ if (code === codes.eof) return ok(code)
+ /* v8 ignore next -- continuation constructs are attempted only after a line ending. */
+ if (!markdownLineEnding(code)) return nok(code)
+ effects.enter(types.lineEnding)
+ effects.consume(code)
+ effects.exit(types.lineEnding)
+ return lineStart
+ }
+
+ function lineStart(code: number | null): State | undefined {
+ return self.parser.lazy[self.now().line] ? nok(code) : ok(code)
+ }
+}
+
+const nonLazyContinuation: Construct = {
+ partial: true,
+ tokenize: tokenizeNonLazyContinuation,
+}
+
+const backslashMathText: Construct = {
+ name: 'backslashMathText',
+ previous: previousBackslash,
+ tokenize: tokenizeBackslashMathText,
+}
+
+const backslashMathFlow = createMathFlow(
+ codes.backslash,
+ codes.leftSquareBracket,
+ codes.rightSquareBracket,
+ true,
+)
+
+const sameLineDollarMathFlow = createMathFlow(
+ codes.dollarSign,
+ codes.dollarSign,
+ codes.dollarSign,
+ false,
+)
+
+const backslashMath: Extension = {
+ flow: {
+ [codes.backslash]: backslashMathFlow,
+ [codes.dollarSign]: sameLineDollarMathFlow,
+ },
+ text: { [codes.backslash]: backslashMathText },
+}
+
+/**
+ * TeX backslash delimiters and same-line display-dollar blocks as a micromark
+ * syntax extension reusing `micromark-extension-math`'s token vocabulary; the
+ * caller must also register `math()` on the same parse so the emitted tokens
+ * compile to standard math nodes.
+ * @returns The micromark syntax extension.
+ */
+export function mathCompatibility(): Extension {
+ return backslashMath
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/parse.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/parse.ts
new file mode 100644
index 0000000000..f54886b7cf
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/parse.ts
@@ -0,0 +1,46 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * The markdown renderer's two mdast grammars, one per rendering arm. Each
+ * arm is internally consistent — the incremental tail parses, the one-shot
+ * parses, and the plain-text projection of a given grammar always agree on
+ * where blocks start and end — and the settled grammar is the streaming one
+ * plus the math extensions, so the arms differ only where TeX delimiters
+ * begin a math construct (a `$$` block is a paragraph while streaming and a
+ * math block once settled, by design).
+ */
+
+import type { Root } from 'mdast'
+import { fromMarkdown } from 'mdast-util-from-markdown'
+import { gfmFromMarkdown } from 'mdast-util-gfm'
+import { mathFromMarkdown } from 'mdast-util-math'
+import { gfm } from 'micromark-extension-gfm'
+import { math } from 'micromark-extension-math'
+import { cjkFriendlyStrong } from './cjkFriendlyStrong.ts'
+import { mathCompatibility } from './mathCompatibility.ts'
+
+/**
+ * Parse GFM markdown (the streaming arm's grammar: no math, so incomplete
+ * TeX never flashes KaTeX errors mid-stream).
+ * @param text - Markdown source.
+ * @returns The mdast root.
+ */
+export function parseGfm(text: string): Root {
+ return fromMarkdown(text, {
+ extensions: [gfm(), cjkFriendlyStrong()],
+ mdastExtensions: [gfmFromMarkdown()],
+ })
+}
+
+/**
+ * Parse GFM markdown plus TeX math with the compatibility delimiters
+ * (the settled arm's grammar).
+ * @param text - Markdown source.
+ * @returns The mdast root.
+ */
+export function parseGfmWithMath(text: string): Root {
+ return fromMarkdown(text, {
+ extensions: [gfm(), cjkFriendlyStrong(), mathCompatibility(), math()],
+ mdastExtensions: [gfmFromMarkdown(), mathFromMarkdown()],
+ })
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/plain-text.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/plain-text.ts
new file mode 100644
index 0000000000..e457b42159
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/plain-text.ts
@@ -0,0 +1,123 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Markdown-to-plain-text projection for compact summaries and labels.
+ * Parsing shares the renderer's streaming GFM grammar ({@link parseGfm}), so
+ * the projection strips exactly the markup the renderer would draw; raw HTML
+ * stays literal, links keep their labels, images keep alt text, and code
+ * keeps its source text.
+ */
+
+import { parseGfm } from './parse.ts'
+
+/** Amount of parsed Markdown content returned by the extractor. */
+export type MarkdownPlainTextMode = 'all' | 'first-line' | 'first-paragraph'
+
+/** Options for {@link extractMarkdownPlainText}. */
+export interface MarkdownPlainTextOptions {
+ /** Projection boundary; defaults to the complete document. */
+ mode?: MarkdownPlainTextMode
+}
+
+interface MarkdownNode {
+ type: string
+ value?: string
+ alt?: string
+ children?: MarkdownNode[]
+}
+
+function inlineText(node: MarkdownNode): string {
+ switch (node.type) {
+ case 'text':
+ case 'inlineCode':
+ case 'code':
+ return node.value ?? ''
+ case 'image':
+ case 'imageReference':
+ return node.alt ?? ''
+ case 'break':
+ return '\n'
+ case 'html':
+ return node.value ?? ''
+ default:
+ return node.children?.map(inlineText).join('') ?? ''
+ }
+}
+
+function compactInline(text: string): string {
+ return text.replace(/\s+/g, ' ').trim()
+}
+
+function blockText(node: MarkdownNode): string {
+ switch (node.type) {
+ case 'root':
+ case 'blockquote':
+ return node.children?.map(blockText).filter(Boolean).join('\n\n') ?? ''
+ case 'paragraph':
+ case 'heading':
+ return compactInline(inlineText(node))
+ case 'code':
+ return node.value?.trim() ?? ''
+ case 'list':
+ return node.children?.map(blockText).filter(Boolean).join('\n') ?? ''
+ case 'listItem':
+ return node.children?.map(blockText).filter(Boolean).join(' ') ?? ''
+ case 'table':
+ return node.children?.map(blockText).filter(Boolean).join('\n') ?? ''
+ case 'tableRow':
+ return node.children?.map(blockText).join('\t') ?? ''
+ case 'tableCell':
+ return compactInline(inlineText(node))
+ case 'html':
+ return node.value ?? ''
+ case 'thematicBreak':
+ case 'definition':
+ return ''
+ default:
+ return compactInline(inlineText(node))
+ }
+}
+
+function findFirstParagraph(node: MarkdownNode): string | undefined {
+ if (node.type === 'paragraph') {
+ const text = compactInline(inlineText(node))
+ if (text !== '') return text
+ }
+ for (const child of node.children ?? []) {
+ const text = findFirstParagraph(child)
+ if (text !== undefined) return text
+ }
+ return undefined
+}
+
+function fullText(root: MarkdownNode): string {
+ return blockText(root)
+ .split('\n')
+ .map(line => line.trim())
+ .join('\n')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim()
+}
+
+/**
+ * Parse GFM Markdown, remove its presentation markup, and preserve raw HTML literally.
+ * @param markdown - Markdown source.
+ * @param options - Optional extraction boundary.
+ * @returns Plain text for the whole document, first visible line, or first semantic paragraph.
+ */
+export function extractMarkdownPlainText(
+ markdown: string,
+ options: MarkdownPlainTextOptions = {},
+): string {
+ const { mode = 'all' } = options
+ const root = parseGfm(markdown) as MarkdownNode
+ const all = fullText(root)
+ switch (mode) {
+ case 'all':
+ return all
+ case 'first-line':
+ return all.split('\n').find(line => line !== '') ?? ''
+ case 'first-paragraph':
+ return findFirstParagraph(root) ?? all.split('\n').find(line => line !== '') ?? ''
+ }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/render.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/render.tsx
new file mode 100644
index 0000000000..781828db4d
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/markdown/render.tsx
@@ -0,0 +1,585 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Direct mdast→React markdown renderer. Replaces the react-markdown /
+ * remark-rehype pipeline with one switch over parsed nodes so streaming can
+ * cache frozen blocks as React elements; the rendered DOM is pinned
+ * byte-for-byte by `tests/fixtures/markdown-dom` and must not drift.
+ *
+ * Untrusted-output policy (unchanged from the replaced pipeline): link and
+ * image destinations pass a protocol allowlist, images additionally require
+ * absolute HTTP(S), raw HTML renders as literal text (no HTML enters the
+ * DOM), and KaTeX runs without trusted commands. Fragment-anchor URLs fail
+ * the allowlist, so footnote references and back-references render as plain
+ * text rather than in-page links.
+ *
+ * Merge-extensible node unions fall through the documented default (render
+ * nothing) rather than ending in assertNever: grammars registered elsewhere
+ * may add node types this renderer has no mapping for.
+ */
+
+import { Fragment, createElement } from 'react'
+import type { Key, ReactNode } from 'react'
+import type * as Md from 'mdast'
+import type {} from 'mdast-util-math'
+import { normalizeUri } from 'micromark-util-sanitize-uri'
+import { CodeBlock } from './CodeBlock.tsx'
+import { renderTexToReact } from './katex.tsx'
+import type { PositionedBlock } from './incremental.ts'
+import css from './MarkdownText.module.css'
+
+/** Copy-button labels forwarded to fence CodeBlocks (this package is cordis-free, so copy arrives via props). */
+export interface MarkdownCodeLabels {
+ /** Copy-button idle label. */
+ copyLabel?: string | undefined
+ /** Copy-button label during the post-copy confirmation window. */
+ copiedLabel?: string | undefined
+}
+
+function sanitizeUrl(url: string): string {
+ try {
+ switch (new URL(url).protocol) {
+ case 'http:':
+ case 'https:':
+ case 'mailto:':
+ return url
+ default:
+ return ''
+ }
+ } catch {
+ // Relative and otherwise unparsable destinations are disallowed alongside
+ // disallowed protocols; new URL() has no other failure mode for strings.
+ return ''
+ }
+}
+
+function remoteImageUrl(url: string): string | undefined {
+ try {
+ const protocol = new URL(url).protocol
+ return protocol === 'http:' || protocol === 'https:' ? url : undefined
+ } catch {
+ // Same single failure mode as above: not an absolute URL.
+ return undefined
+ }
+}
+
+/** Link/image reference targets collected from a document (first definition per identifier wins, as in CommonMark). */
+export interface ReferenceTargets {
+ /** Link/image definitions keyed by upper-cased identifier. */
+ definitions: Map<string, Md.Definition>
+ /** Footnote definitions keyed by upper-cased identifier. */
+ footnotes: Map<string, Md.FootnoteDefinition>
+}
+
+/**
+ * Create an empty {@link ReferenceTargets}.
+ * @returns Fresh empty maps.
+ */
+export function createReferenceTargets(): ReferenceTargets {
+ return { definitions: new Map(), footnotes: new Map() }
+}
+
+/**
+ * Record every definition and footnote definition under `nodes` into
+ * `targets`, depth-first, keeping the first definition per identifier.
+ * @param nodes - Subtrees to walk (top-level blocks or any nested children).
+ * @param targets - Accumulator, typically shared across incremental segments.
+ */
+export function collectReferenceTargets(
+ nodes: readonly Md.RootContent[],
+ targets: ReferenceTargets,
+): void {
+ for (const node of nodes) {
+ if (node.type === 'definition') {
+ const id = node.identifier.toUpperCase()
+ if (!targets.definitions.has(id)) targets.definitions.set(id, node)
+ } else if (node.type === 'footnoteDefinition') {
+ const id = node.identifier.toUpperCase()
+ if (!targets.footnotes.has(id)) targets.footnotes.set(id, node)
+ }
+ if ('children' in node) collectReferenceTargets(node.children, targets)
+ }
+}
+
+/**
+ * File-mention affordance for inline code: the owner resolves an authored
+ * token to the file it names, using its own vocabulary of real files — the
+ * renderer never guesses at what looks like a path.
+ */
+export interface MarkdownFileMentions {
+ /**
+ * Resolve one inline-code token.
+ * @param value - The authored token, exactly as written.
+ * @returns The opener with its accessible label and full-path title, or
+ * undefined when the token names no known file — it then stays inert code.
+ */
+ resolve(value: string): { open: () => void; label: string; title: string } | undefined
+}
+
+/**
+ * One render pass's state: immutable options and targets plus the footnote
+ * numbering accumulated in document order while references render.
+ */
+export interface MarkdownRenderContext {
+ /** Streaming arm: fences render plain and TeX stays literal. */
+ readonly streaming: boolean
+ /** Localized fence copy-button labels. */
+ readonly codeLabels: MarkdownCodeLabels | undefined
+ /** Inline-code file mentions; absent wherever no opener vocabulary exists. */
+ readonly fileMentions: MarkdownFileMentions | undefined
+ /** Inside an anchor's children: interactive mentions must not nest there. */
+ readonly inLink?: boolean
+ /** Reference targets visible to this pass. */
+ readonly targets: ReferenceTargets
+ /** Footnote identifiers in first-reference order; a footnote's number is its 1-based index here. */
+ readonly footnoteOrder: string[]
+ /** References rendered per identifier; drives the section's back-reference count. */
+ readonly footnoteCounts: Map<string, number>
+}
+
+/**
+ * Render top-level blocks. Nodes that render nothing (definitions, unmapped
+ * types) are dropped rather than kept as null placeholders, matching the
+ * replaced pipeline's child lists so separator newlines land identically.
+ * @param blocks - Blocks with their stream-stable render keys.
+ * @param context - The pass state; footnote numbering mutates in document order.
+ * @returns One React node per rendered block.
+ */
+export function renderBlocks(
+ blocks: readonly PositionedBlock[],
+ context: MarkdownRenderContext,
+): ReactNode[] {
+ return blocks
+ .map(block => renderNode(block.node, block.key, context))
+ .filter(element => element !== null)
+}
+
+/**
+ * Interleave the newline text nodes the replaced pipeline emitted between
+ * block-level children. They are invisible between elements but coalesce
+ * into adjacent literal raw-HTML text, where the DOM parity fixtures pin
+ * them.
+ * @param elements - Rendered block children with empty renders already dropped.
+ * @param edges - Also emit the leading and trailing newline (hast's loose wrap).
+ * @returns The interleaved children.
+ */
+export function wrapBlockChildren(elements: readonly ReactNode[], edges: boolean): ReactNode[] {
+ const wrapped: ReactNode[] = []
+ for (const element of elements) {
+ if (edges || wrapped.length > 0) wrapped.push('\n')
+ wrapped.push(element)
+ }
+ if (edges && elements.length > 0) wrapped.push('\n')
+ return wrapped
+}
+
+/**
+ * A block child rendered for a parent that must tell paragraphs apart from
+ * other blocks (list items unwrap them when tight; footnote bodies receive
+ * their back-references inside the trailing paragraph).
+ */
+type BlockEntry = { paragraph: ReactNode[] } | { element: ReactNode }
+
+/** Render container children into {@link BlockEntry} values, dropping empty renders. */
+function renderBlockEntries(
+ blocks: readonly Md.RootContent[],
+ context: MarkdownRenderContext,
+): BlockEntry[] {
+ const entries: BlockEntry[] = []
+ for (const [index, block] of blocks.entries()) {
+ if (block.type === 'paragraph') {
+ entries.push({ paragraph: renderChildren(block.children, context) })
+ } else {
+ const element = renderNode(block, index, context)
+ if (element !== null) entries.push({ element })
+ }
+ }
+ return entries
+}
+
+function renderChildren(
+ nodes: readonly Md.RootContent[],
+ context: MarkdownRenderContext,
+): ReactNode[] {
+ return nodes.map((node, index) => renderNode(node, index, context))
+}
+
+function renderNode(node: Md.RootContent, key: Key, context: MarkdownRenderContext): ReactNode {
+ switch (node.type) {
+ case 'text':
+ return node.value
+ case 'paragraph':
+ return <p key={key}>{renderChildren(node.children, context)}</p>
+ case 'heading':
+ return createElement(`h${node.depth}`, { key }, ...renderChildren(node.children, context))
+ case 'blockquote':
+ return (
+ <blockquote key={key}>
+ {wrapBlockChildren(renderChildren(node.children, context).filter(child => child !== null), true)}
+ </blockquote>
+ )
+ case 'thematicBreak':
+ return <hr key={key} />
+ case 'break':
+ // The replaced pipeline emitted a newline text node after each <br>.
+ return <Fragment key={key}><br />{'\n'}</Fragment>
+ case 'strong':
+ return <strong key={key}>{renderChildren(node.children, context)}</strong>
+ case 'emphasis':
+ return <em key={key}>{renderChildren(node.children, context)}</em>
+ case 'delete':
+ return <del key={key}>{renderChildren(node.children, context)}</del>
+ case 'inlineCode': {
+ // Parity with mdast-util-to-hast: inline code renders line endings as spaces.
+ const value = node.value.replace(/\r?\n|\r/g, ' ')
+ // An inline-code token that is entirely an absolute HTTP(S) URL keeps
+ // its code chrome and gains the same safe external anchor as a link;
+ // commands, partial URLs, and other schemes stay inert. The value is
+ // authored text, not a parsed destination, so no normalizeUri: port,
+ // path, and query render unchanged.
+ const href = inlineCodeHttpUrl(value)
+ if (href !== undefined) return <code key={key}>{renderSafeLink(href, [value], 'link')}</code>
+ // A token the owner's file-mention vocabulary recognizes opens that
+ // file; the resolver, not this renderer, decides what names a file.
+ // Inside an anchor the token stays inert — a button cannot nest there.
+ const mention = context.inLink === true ? undefined : context.fileMentions?.resolve(value)
+ if (mention !== undefined) {
+ return (
+ <code key={key}>
+ <button
+ type="button"
+ className={css.fileMention}
+ title={mention.title}
+ aria-label={mention.label}
+ onClick={mention.open}
+ >
+ {value}
+ </button>
+ </code>
+ )
+ }
+ return <code key={key}>{value}</code>
+ }
+ case 'html':
+ // No HTML parser enters the pipeline: raw HTML stays literal text.
+ return node.value
+ case 'code':
+ return renderCode(node, key, context)
+ case 'math':
+ return <Fragment key={key}>{renderTexToReact(node.value, true)}</Fragment>
+ case 'inlineMath':
+ return <Fragment key={key}>{renderTexToReact(node.value, false)}</Fragment>
+ case 'list':
+ return renderList(node, key, context)
+ case 'listItem':
+ // Reachable only in hand-built trees: the grammar emits items inside lists.
+ return renderListItem(node, listItemLoose(node), key, context)
+ case 'table':
+ return renderTable(node, key, context)
+ case 'link':
+ return renderAnchor(node.url, renderChildren(node.children, { ...context, inLink: true }), key)
+ case 'linkReference':
+ return renderLinkReference(node, key, context)
+ case 'image':
+ return renderImage(node.url, node.alt ?? '', key)
+ case 'imageReference':
+ return renderImageReference(node, key, context)
+ case 'footnoteReference':
+ return renderFootnoteReference(node, key, context)
+ case 'definition':
+ case 'footnoteDefinition':
+ // Targets render elsewhere: definitions resolve references in place;
+ // footnote bodies render in the trailing section.
+ return null
+ default:
+ // Documented default for the merge-extensible union: node types without
+ // a mapping (tableRow/tableCell outside a table, frontmatter, future
+ // grammar contributions) render nothing.
+ return null
+ }
+}
+
+function renderCode(node: Md.Code, key: Key, context: MarkdownRenderContext): ReactNode {
+ const language = node.lang ?? undefined
+ if (node.value === '') {
+ // Parity: the replaced pipeline kept the stock <pre> for an empty fence.
+ return (
+ <pre key={key}>
+ <code className={language === undefined ? undefined : `language-${language}`} />
+ </pre>
+ )
+ }
+ // The replaced pipeline recovered the grammar id from the hast class with
+ // /language-([\w-]+)/, which truncates at the first non-word character.
+ const lang = language === undefined ? undefined : /^[\w-]+/.exec(language)?.[0]
+ if (!context.streaming && lang === 'math') {
+ // ```math fences render as display TeX once settled (rehype-katex parity);
+ // its text extraction saw the code block's trailing newline.
+ return <Fragment key={key}>{renderTexToReact(`${node.value}\n`, true)}</Fragment>
+ }
+ return (
+ <CodeBlock
+ key={key}
+ // The replaced hast pipeline appended one synthetic newline that
+ // CodeBlock's display trim removes; feeding the bare value would make
+ // that trim eat a REAL trailing blank line inside the fence instead.
+ code={`${node.value}\n`}
+ lang={context.streaming ? undefined : lang}
+ copyLabel={context.codeLabels?.copyLabel}
+ copiedLabel={context.codeLabels?.copiedLabel}
+ />
+ )
+}
+
+/** A list is loose when it or any of its items is spread; every item then keeps its paragraphs. */
+function listLoose(list: Md.List): boolean {
+ return (list.spread ?? false) || list.children.some(listItemLoose)
+}
+
+function listItemLoose(item: Md.ListItem): boolean {
+ return item.spread ?? item.children.length > 1
+}
+
+function renderList(node: Md.List, key: Key, context: MarkdownRenderContext): ReactNode {
+ const loose = listLoose(node)
+ const properties: { start?: number; className?: string } = {}
+ if (typeof node.start === 'number' && node.start !== 1) properties.start = node.start
+ if (node.children.some(item => typeof item.checked === 'boolean')) {
+ properties.className = 'contains-task-list'
+ }
+ return createElement(
+ node.ordered === true ? 'ol' : 'ul',
+ { key, ...properties },
+ ...node.children.map((item, index) => renderListItem(item, loose, index, context)),
+ )
+}
+
+function renderListItem(
+ item: Md.ListItem,
+ loose: boolean,
+ key: Key,
+ context: MarkdownRenderContext,
+): ReactNode {
+ const entries = renderBlockEntries(item.children, context)
+ const task = typeof item.checked === 'boolean'
+ if (task) {
+ const checkbox = <input key="task-checkbox" type="checkbox" checked={item.checked === true} disabled />
+ const head = entries[0]
+ if (head !== undefined && 'paragraph' in head) {
+ head.paragraph = head.paragraph.length > 0 ? [checkbox, ' ', ...head.paragraph] : [checkbox]
+ } else {
+ entries.unshift({ paragraph: [checkbox] })
+ }
+ }
+ // Newline placement and tight-paragraph unwrapping mirror
+ // mdast-util-to-hast's list-item handler: a newline before every child
+ // except a tight leading paragraph, and after a trailing non-paragraph
+ // (or any trailing child when loose).
+ const parts: ReactNode[] = []
+ for (const [index, entry] of entries.entries()) {
+ const isParagraph = 'paragraph' in entry
+ if (loose || index !== 0 || !isParagraph) parts.push('\n')
+ if (!isParagraph) parts.push(entry.element)
+ else if (loose) parts.push(<p key={`p-${index}`}>{entry.paragraph}</p>)
+ else parts.push(<Fragment key={`p-${index}`}>{entry.paragraph}</Fragment>)
+ }
+ const tail = entries[entries.length - 1]
+ if (tail !== undefined && (loose || !('paragraph' in tail))) parts.push('\n')
+ return (
+ <li key={key} className={task ? 'task-list-item' : undefined}>
+ {parts}
+ </li>
+ )
+}
+
+function renderTable(node: Md.Table, key: Key, context: MarkdownRenderContext): ReactNode {
+ const align = node.align ?? null
+ const [headRow, ...bodyRows] = node.children
+ return (
+ <div key={key} className={css.tableScroll}>
+ <table>
+ {headRow !== undefined && <thead>{renderTableRow(headRow, 'th', align, 0, context)}</thead>}
+ {bodyRows.length > 0 && (
+ <tbody>
+ {bodyRows.map((row, index) => renderTableRow(row, 'td', align, index + 1, context))}
+ </tbody>
+ )}
+ </table>
+ </div>
+ )
+}
+
+function renderTableRow(
+ row: Md.TableRow,
+ cellTag: 'th' | 'td',
+ align: readonly Md.AlignType[] | null,
+ key: Key,
+ context: MarkdownRenderContext,
+): ReactNode {
+ // With column alignment present, every row renders exactly one cell per
+ // column, padding or truncating the row (mdast-util-to-hast parity).
+ const length = align === null ? row.children.length : align.length
+ const cells: ReactNode[] = []
+ for (let index = 0; index < length; index++) {
+ const cell = row.children[index]
+ const alignValue = align?.[index]
+ cells.push(createElement(
+ cellTag,
+ // hast-util-to-jsx-runtime's default tableCellAlignToStyle turned the
+ // deprecated align attribute into an inline style; keep that DOM.
+ { key: index, style: alignValue == null ? undefined : { textAlign: alignValue } },
+ ...(cell === undefined ? [] : renderChildren(cell.children, context)),
+ ))
+ }
+ return <tr key={key}>{cells}</tr>
+}
+
+/** Anchor over an already-authored href: allowlisted or unwrapped, external links get the safe attributes. */
+function renderSafeLink(href: string, children: ReactNode[], key: Key): ReactNode {
+ const safeHref = sanitizeUrl(href)
+ if (safeHref === '') return <Fragment key={key}>{children}</Fragment>
+ const external = ['http:', 'https:'].includes(new URL(safeHref).protocol)
+ return (
+ <a
+ key={key}
+ href={safeHref}
+ {...(external ? { target: '_blank', rel: 'noopener noreferrer' } : {})}
+ >
+ {children}
+ </a>
+ )
+}
+
+/** Anchor over a parsed markdown destination, which hast normalized before the allowlist saw it. */
+function renderAnchor(url: string, children: ReactNode[], key: Key): ReactNode {
+ return renderSafeLink(normalizeUri(url), children, key)
+}
+
+/**
+ * The complete inline-code value when it is exactly an absolute HTTP(S) URL
+ * (no surrounding whitespace); anything else stays inert code.
+ */
+function inlineCodeHttpUrl(value: string): string | undefined {
+ if (value.trim() !== value) return undefined
+ try {
+ const protocol = new URL(value).protocol
+ return protocol === 'http:' || protocol === 'https:' ? value : undefined
+ } catch {
+ // Not an absolute URL at all — the only way new URL() rejects a string.
+ return undefined
+ }
+}
+
+function renderImage(url: string, alt: string, key: Key): ReactNode {
+ const imageSrc = remoteImageUrl(sanitizeUrl(normalizeUri(url)))
+ if (imageSrc === undefined) {
+ return <span key={key} className={css.imageAlt}>{alt}</span>
+ }
+ return (
+ <img
+ key={key}
+ className={css.image}
+ src={imageSrc}
+ alt={alt}
+ loading="lazy"
+ decoding="async"
+ referrerPolicy="no-referrer"
+ />
+ )
+}
+
+/** The bracketed source text a reference reverts to when its definition is missing. */
+function referenceSuffix(node: Md.LinkReference | Md.ImageReference): string {
+ if (node.referenceType === 'collapsed') return '][]'
+ if (node.referenceType === 'full') return `][${node.label ?? node.identifier}]`
+ return ']'
+}
+
+function renderLinkReference(
+ node: Md.LinkReference,
+ key: Key,
+ context: MarkdownRenderContext,
+): ReactNode {
+ const definition = context.targets.definitions.get(node.identifier.toUpperCase())
+ if (definition === undefined) {
+ // The grammar only emits references whose definitions exist somewhere in
+ // the same parse, but incremental segments and hand-built trees may still
+ // present unresolved ones: revert to the bracketed source text — which is
+ // not an anchor, so mentions inside it stay live.
+ return <Fragment key={key}>{'['}{renderChildren(node.children, context)}{referenceSuffix(node)}</Fragment>
+ }
+ return renderAnchor(definition.url, renderChildren(node.children, { ...context, inLink: true }), key)
+}
+
+function renderImageReference(
+ node: Md.ImageReference,
+ key: Key,
+ context: MarkdownRenderContext,
+): ReactNode {
+ const definition = context.targets.definitions.get(node.identifier.toUpperCase())
+ if (definition === undefined) return `![${node.alt ?? ''}${referenceSuffix(node)}`
+ return renderImage(definition.url, node.alt ?? '', key)
+}
+
+function renderFootnoteReference(
+ node: Md.FootnoteReference,
+ key: Key,
+ context: MarkdownRenderContext,
+): ReactNode {
+ const id = node.identifier.toUpperCase()
+ const seen = context.footnoteCounts.get(id)
+ if (seen === undefined) context.footnoteOrder.push(id)
+ context.footnoteCounts.set(id, (seen ?? 0) + 1)
+ // The in-page anchor fails the protocol allowlist, so only the numbered
+ // superscript renders (matching the replaced pipeline's unwrapped link).
+ return <sup key={key}>{String(context.footnoteOrder.indexOf(id) + 1)}</sup>
+}
+
+/**
+ * Render the trailing footnote section for every footnote referenced during
+ * the pass, in first-reference order, with one plain-text back-reference
+ * marker per rendered reference.
+ * @param context - The pass state after all blocks rendered.
+ * @returns The section, or null when no referenced footnote has a definition.
+ */
+export function renderFootnoteSection(context: MarkdownRenderContext): ReactNode | null {
+ const items: ReactNode[] = []
+ for (const id of context.footnoteOrder) {
+ const definition = context.targets.footnotes.get(id)
+ if (definition === undefined) continue
+ const count = context.footnoteCounts.get(id) ?? 0
+ const backrefs: ReactNode[] = []
+ for (let reference = 1; reference <= count; reference++) {
+ if (backrefs.length > 0) backrefs.push(' ')
+ backrefs.push('↩')
+ if (reference > 1) backrefs.push(<sup key={`re-${reference}`}>{String(reference)}</sup>)
+ }
+ const entries = renderBlockEntries(definition.children, context)
+ const tail = entries[entries.length - 1]
+ const body: ReactNode[] = entries.map((entry, index) => (
+ 'paragraph' in entry
+ ? (
+ <p key={`p-${index}`}>
+ {entry.paragraph}
+ {entry === tail && <>{' '}{backrefs}</>}
+ </p>
+ )
+ : entry.element
+ ))
+ // Without a trailing paragraph the back-references join the block list
+ // itself (and pick up the wrap newlines), as in the replaced pipeline.
+ if (tail === undefined || !('paragraph' in tail)) body.push(...backrefs)
+ items.push(
+ <li key={id} id={`user-content-fn-${normalizeUri(id.toLowerCase())}`}>
+ {wrapBlockChildren(body, true)}
+ </li>,
+ )
+ }
+ if (items.length === 0) return null
+ return (
+ <section key="footnotes" data-footnotes className="footnotes">
+ <h2 id="footnote-label" className="sr-only">Footnotes</h2>
+ <ol>{items}</ol>
+ </section>
+ )
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/pointer-grace.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/pointer-grace.ts
new file mode 100644
index 0000000000..4851230ac3
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/primitives/pointer-grace.ts
@@ -0,0 +1,55 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+// Shared close timing for pointer-dismissed popups (HoverCard, hover-closing
+// Menu). Both float free of their anchor, so the pointer has to cross ground
+// that belongs to neither on its way in; closing on the first pointerleave
+// makes the popup unreachable. The grace turns that transit into a cancelable
+// pending close.
+
+import { useCallback, useEffect, useRef } from 'react'
+
+/**
+ * Grace before a pointer-dismissed popup closes. Covers the anchor->popup gap
+ * (8px for HoverCard, 4px for Menu) at a hand's travel speed without leaving a
+ * popup lingering once the pointer has genuinely moved on.
+ */
+export const POINTER_GRACE_MS = 200
+
+/** Cancelable delayed close for a pointer-dismissed popup. */
+export interface PointerGrace {
+ /** Schedule the close {@link POINTER_GRACE_MS} from now, replacing any pending one. */
+ arm: () => void
+ /** Abort a pending close (the pointer came back). */
+ cancel: () => void
+}
+
+/**
+ * Delay a pointer-dismissed popup's close so the pointer can cross the gap
+ * between anchor and popup. A pending close is dropped on unmount.
+ * @param close - runs when the grace elapses with no re-entry; read at fire
+ * time, so callers may pass a fresh closure each render.
+ * @returns the {@link PointerGrace} handle.
+ */
+export function usePointerGrace(close: () => void): PointerGrace {
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const closeRef = useRef(close)
+ closeRef.current = close
+
+ const cancel = useCallback(() => {
+ if (timerRef.current === null) return
+ clearTimeout(timerRef.current)
+ timerRef.current = null
+ }, [])
+
+ const arm = useCallback(() => {
+ cancel()
+ timerRef.current = setTimeout(() => {
+ timerRef.current = null
+ closeRef.current()
+ }, POINTER_GRACE_MS)
+ }, [cancel])
+
+ useEffect(() => cancel, [cancel])
+
+ return { arm, cancel }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/attribute-resolver.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/attribute-resolver.ts
new file mode 100644
index 0000000000..69454ad36e
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/attribute-resolver.ts
@@ -0,0 +1,1046 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Per-field semantic normalization for standard, OpenJiuwen, and legacy spans. */
+
+import {
+ exactAttributeMap,
+ readBooleanAttribute,
+ readInt64Attribute,
+ readNumberAttribute,
+ readStringArrayAttribute,
+ readStringAttribute,
+ structuredOtlpValue,
+} from '../semconv/attributes.ts'
+import {
+ DSH_ATTRIBUTES,
+ DSH_EVENTS,
+ DSH_REQUEST_PURPOSES,
+ DSH_STREAM_KINDS,
+ DSH_TRAJECTORY_KINDS,
+ OPENJIUWEN_ATTRIBUTES,
+ OPENJIUWEN_EVENTS,
+ STANDARD_ATTRIBUTES,
+} from '../semconv/constants.ts'
+import type { OtlpAttributeMap } from '../semconv/attributes.ts'
+import type { OtlpAnyValue, OtlpKeyValue, OtlpSpanEvent } from '../shared/otlp.ts'
+
+/** Stable facts consumed by the projector after profile-specific fallback. */
+export interface NormalizedTrajectoryAttributes {
+ raw: OtlpAttributeMap
+ sources: Readonly<Record<string, string>>
+ conversationId?: string
+ traceRoot?: boolean
+ traceSchemaVersion?: string
+ traceComplete?: boolean
+ traceForcedClose?: boolean
+ spanForcedClose?: boolean
+ spanForcedCloseReason?: string
+ operationName?: string
+ providerName?: string
+ requestId?: string
+ runId?: string
+ turnId?: string
+ agentMode?: string
+ requestModel?: string
+ responseModel?: string
+ requestMaxTokens?: bigint
+ requestTemperature?: number
+ requestTopP?: number
+ requestStopSequences?: readonly string[]
+ requestStream?: boolean
+ requestReasoningLevel?: string
+ responseId?: string
+ responseFinishReasons?: readonly string[]
+ responseTimeToFirstChunkSeconds?: number
+ usageInputTokens?: bigint
+ usageOutputTokens?: bigint
+ usageReasoningTokens?: bigint
+ usageCacheReadTokens?: bigint
+ usageCacheCreationTokens?: bigint
+ usageTotalTokens?: bigint
+ inputCost?: number
+ outputCost?: number
+ totalCost?: number
+ totalLatencyMs?: number
+ timePerOutputTokenMs?: number
+ promptTokenIds?: unknown
+ completionTokenIds?: unknown
+ logprobs?: unknown
+ parserResult?: unknown
+ providerMetadata?: unknown
+ agentId?: string
+ agentName?: string
+ agentVersion?: string
+ agentDescription?: string
+ systemInstructions?: unknown
+ inputMessages?: unknown
+ inputMessageProvenance?: unknown
+ outputMessages?: unknown
+ toolDefinitions?: unknown
+ toolName?: string
+ toolCallId?: string
+ toolType?: string
+ toolDescription?: string
+ toolResourceId?: string
+ openJiuwenToolType?: string
+ toolAuthoritative?: boolean
+ toolCallArguments?: unknown
+ toolCallResult?: unknown
+ sourceSequence?: bigint
+ turnNumber?: bigint
+ stepId?: string
+ stepNumber?: bigint
+ inferenceId?: string
+ trajectoryKind?: string
+ requestPurpose?: string
+ requestNumber?: bigint
+ requestRetryCount?: bigint
+ requestMaxRetries?: bigint
+ messageSourceKind?: string
+ messageSourcePlugin?: string
+ compactionInputTokens?: bigint
+ compactionSummary?: string
+ langfuseObservationType?: string
+ errorType?: string
+ errorMessage?: string
+}
+
+/** One replayable stream event after OpenJiuwen/DSH compatibility resolution. */
+export interface NormalizedTrajectoryStreamEvent {
+ sequence: number
+ kind: string
+ source: string
+ text?: string
+ toolCallId?: string
+ toolName?: string
+ argumentsDelta?: string
+}
+
+type MutableNormalized = Omit<NormalizedTrajectoryAttributes, 'sources'> & {
+ sources: Record<string, string>
+}
+
+interface Resolved<T> {
+ key: string
+ value: T
+}
+
+interface NormalizedPart {
+ type: string
+ content?: string
+ id?: string
+ name?: string
+ arguments?: unknown
+ response?: unknown
+}
+
+interface NormalizedMessage {
+ role: string
+ parts: readonly NormalizedPart[]
+}
+
+const LEGACY = {
+ openJiuwenSessionId: 'openjiuwen.session_id',
+ providerName: 'gen_ai.system',
+ responseFinishReason: 'gen_ai.response.finish_reason',
+ responseTimeToFirstTokenMs: 'gen_ai.response.time_to_first_token_ms',
+ usageInputTokens: 'gen_ai.usage.prompt_tokens',
+ usageOutputTokens: 'gen_ai.usage.completion_tokens',
+ usageCacheTokens: 'gen_ai.usage.cache_tokens',
+ usageReasoningTokens: 'gen_ai.usage.reasoning_tokens',
+ usageTotalTokens: 'gen_ai.usage.total_tokens',
+ toolCallId: 'gen_ai.tool.id',
+ toolCallArguments: 'gen_ai.tool.input',
+ toolCallResult: 'gen_ai.tool.output',
+ toolCalls: 'gen_ai.tool_calls',
+ promptScalar: 'gen_ai.prompt',
+ completionScalar: 'gen_ai.completion',
+ promptPrefix: 'gen_ai.prompt',
+ completionPrefix: 'gen_ai.completion',
+ langfusePromptPrefix: 'langfuse.gen_ai.prompt',
+ langfuseCompletionPrefix: 'langfuse.gen_ai.completion',
+ langfuseInput: 'langfuse.observation.input',
+ langfuseOutput: 'langfuse.observation.output',
+ langfuseObservationType: 'langfuse.observation.type',
+ agentTeamSessionId: 'agentteam.session.id',
+ deepAgentName: 'deepagent.agent.name',
+ deepAgentIteration: 'deepagent.task.iteration',
+} as const
+
+const TRAJECTORY_KINDS = new Set<string>(DSH_TRAJECTORY_KINDS)
+const REQUEST_PURPOSES = new Set<string>(DSH_REQUEST_PURPOSES)
+const STREAM_KINDS = new Set<string>(DSH_STREAM_KINDS)
+
+function parsedJson(value: string): unknown {
+ try {
+ return JSON.parse(value) as unknown
+ } catch {
+ return value
+ }
+}
+
+function flexibleValue(value: OtlpAnyValue): unknown {
+ if ('stringValue' in value) return parsedJson(value.stringValue)
+ return structuredOtlpValue(value)
+}
+
+function resolveString(attributes: OtlpAttributeMap, keys: readonly string[]): Resolved<string> | undefined {
+ for (const key of keys) {
+ const value = readStringAttribute(attributes, key)
+ if (value !== undefined) return { key, value }
+ }
+ return undefined
+}
+
+function resolveClosedString(
+ attributes: OtlpAttributeMap,
+ keys: readonly string[],
+ accepted: ReadonlySet<string>,
+): Resolved<string> | undefined {
+ for (const key of keys) {
+ const value = readStringAttribute(attributes, key)
+ if (value !== undefined && accepted.has(value)) return { key, value }
+ }
+ return undefined
+}
+
+function resolveBoolean(attributes: OtlpAttributeMap, keys: readonly string[]): Resolved<boolean> | undefined {
+ for (const key of keys) {
+ const value = readBooleanAttribute(attributes, key)
+ if (value !== undefined) return { key, value }
+ }
+ return undefined
+}
+
+function resolveNonNegativeInt64(
+ attributes: OtlpAttributeMap,
+ keys: readonly string[],
+): Resolved<bigint> | undefined {
+ for (const key of keys) {
+ const value = readInt64Attribute(attributes, key)
+ if (value !== undefined && value >= 0n) return { key, value }
+ }
+ return undefined
+}
+
+function resolvePositiveInt64(
+ attributes: OtlpAttributeMap,
+ keys: readonly string[],
+): Resolved<bigint> | undefined {
+ for (const key of keys) {
+ const value = readInt64Attribute(attributes, key)
+ if (value !== undefined && value > 0n) return { key, value }
+ }
+ return undefined
+}
+
+function resolveNumber(attributes: OtlpAttributeMap, keys: readonly string[]): Resolved<number> | undefined {
+ for (const key of keys) {
+ const value = readNumberAttribute(attributes, key)
+ if (value !== undefined && Number.isFinite(value)) return { key, value }
+ }
+ return undefined
+}
+
+function resolveNonNegativeNumber(
+ attributes: OtlpAttributeMap,
+ keys: readonly string[],
+): Resolved<number> | undefined {
+ for (const key of keys) {
+ const value = readNumberAttribute(attributes, key)
+ if (value !== undefined && Number.isFinite(value) && value >= 0) return { key, value }
+ }
+ return undefined
+}
+
+function resolveStringArray(attributes: OtlpAttributeMap, keys: readonly string[]): Resolved<readonly string[]> | undefined {
+ for (const key of keys) {
+ const value = readStringArrayAttribute(attributes, key)
+ if (value !== undefined) return { key, value }
+ const scalar = readStringAttribute(attributes, key)
+ if (scalar !== undefined) {
+ const parsed = parsedJson(scalar)
+ if (Array.isArray(parsed) && parsed.every(item => typeof item === 'string')) {
+ return { key, value: parsed }
+ }
+ return { key, value: [scalar] }
+ }
+ }
+ return undefined
+}
+
+function resolveFlexible(attributes: OtlpAttributeMap, keys: readonly string[]): Resolved<unknown> | undefined {
+ for (const key of keys) {
+ const value = attributes.get(key)
+ if (value !== undefined) return { key, value: flexibleValue(value) }
+ }
+ return undefined
+}
+
+function assign<T>(
+ target: MutableNormalized,
+ field: keyof NormalizedTrajectoryAttributes,
+ resolved: Resolved<T> | undefined,
+): void {
+ if (resolved === undefined) return
+ ;(target as unknown as Record<string, unknown>)[field] = resolved.value
+ target.sources[field] = resolved.key
+}
+
+function object(value: unknown): Record<string, unknown> | undefined {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : undefined
+}
+
+function nonNegativeInteger(value: unknown): bigint | undefined {
+ if (typeof value === 'number') {
+ return Number.isSafeInteger(value) && value >= 0 ? BigInt(value) : undefined
+ }
+ if (typeof value !== 'string' || !/^\d+$/.test(value)) return undefined
+ try {
+ return BigInt(value)
+ } catch {
+ return undefined
+ }
+}
+
+function langfuseOutput(attributes: OtlpAttributeMap): Resolved<Record<string, unknown>> | undefined {
+ const resolved = resolveFlexible(attributes, [LEGACY.langfuseOutput])
+ if (resolved === undefined) return undefined
+ const value = object(resolved.value)
+ return value === undefined ? undefined : { key: resolved.key, value }
+}
+
+function langfuseFinishReasons(
+ output: Resolved<Record<string, unknown>> | undefined,
+): Resolved<readonly string[]> | undefined {
+ if (output === undefined || !Array.isArray(output.value.choices)) return undefined
+ const reasons = output.value.choices.flatMap((candidate): string[] => {
+ const choice = object(candidate)
+ return typeof choice?.finish_reason === 'string' ? [choice.finish_reason] : []
+ })
+ return reasons.length === 0 ? undefined : { key: output.key, value: reasons }
+}
+
+function langfuseUsage(
+ output: Resolved<Record<string, unknown>> | undefined,
+ keys: readonly string[],
+): Resolved<bigint> | undefined {
+ if (output === undefined) return undefined
+ const usage = object(output.value.usage)
+ if (usage === undefined) return undefined
+ for (const key of keys) {
+ const value = nonNegativeInteger(usage[key])
+ if (value !== undefined) return { key: output.key, value }
+ }
+ return undefined
+}
+
+function text(value: unknown): string {
+ if (typeof value === 'string') return value
+ return JSON.stringify(value, null, 2) ?? String(value)
+}
+
+function normalizedToolCall(value: unknown): NormalizedPart | undefined {
+ const call = object(value)
+ if (call === undefined) return undefined
+ const functionValue = object(call.function)
+ const name = typeof call.name === 'string'
+ ? call.name
+ : typeof functionValue?.name === 'string' ? functionValue.name : undefined
+ const rawArguments = call.arguments ?? functionValue?.arguments
+ const id = typeof call.id === 'string' ? call.id : undefined
+ if (name === undefined && id === undefined && rawArguments === undefined) return undefined
+ return {
+ type: 'tool_call',
+ ...(id === undefined ? {} : { id }),
+ ...(name === undefined ? {} : { name }),
+ ...(rawArguments === undefined
+ ? {}
+ : { arguments: typeof rawArguments === 'string' ? parsedJson(rawArguments) : rawArguments }),
+ }
+}
+
+function normalizedContentParts(value: unknown, reasoning: boolean): NormalizedPart[] {
+ if (typeof value === 'string') return [{ type: reasoning ? 'reasoning' : 'text', content: value }]
+ if (!Array.isArray(value)) {
+ return value === undefined ? [] : [{ type: reasoning ? 'reasoning' : 'text', content: text(value) }]
+ }
+ const parts: NormalizedPart[] = []
+ for (const candidate of value) {
+ if (typeof candidate === 'string') {
+ parts.push({ type: reasoning ? 'reasoning' : 'text', content: candidate })
+ continue
+ }
+ const part = object(candidate)
+ if (part === undefined) {
+ parts.push({ type: reasoning ? 'reasoning' : 'text', content: text(candidate) })
+ continue
+ }
+ const typeValue = typeof part.type === 'string' ? part.type : reasoning ? 'reasoning' : 'text'
+ const content = typeof part.content === 'string'
+ ? part.content
+ : typeof part.text === 'string' ? part.text : undefined
+ const toolCall = typeValue === 'tool_call' || typeValue === 'tool-call'
+ ? normalizedToolCall(part)
+ : undefined
+ if (toolCall !== undefined) {
+ parts.push(toolCall)
+ continue
+ }
+ parts.push({
+ type: typeValue,
+ ...(content === undefined ? {} : { content }),
+ ...(typeof part.id === 'string' ? { id: part.id } : {}),
+ ...(typeof part.name === 'string' ? { name: part.name } : {}),
+ ...(part.arguments === undefined ? {} : { arguments: part.arguments }),
+ ...(part.response === undefined ? {} : { response: part.response }),
+ })
+ }
+ return parts
+}
+
+function normalizedMessage(value: unknown, defaultRole: string): NormalizedMessage | undefined {
+ const message = object(value)
+ if (message === undefined) {
+ if (value === undefined) return undefined
+ return { role: defaultRole, parts: normalizedContentParts(value, false) }
+ }
+ const role = typeof message.role === 'string' ? message.role : defaultRole
+ const reasoning = message.is_reasoning === true || role === 'reasoning'
+ const rawParts = message.parts ?? message.content ?? message.text
+ const parts = normalizedContentParts(rawParts, reasoning)
+ const calls = message.tool_calls ?? message.toolCalls
+ if (Array.isArray(calls)) {
+ for (const call of calls) {
+ const normalized = normalizedToolCall(call)
+ if (normalized !== undefined) parts.push(normalized)
+ }
+ }
+ return { role: role === 'reasoning' ? 'assistant' : role, parts }
+}
+
+function normalizedMessages(value: unknown, defaultRole: string): readonly NormalizedMessage[] {
+ const envelope = object(value)
+ if (envelope !== undefined) {
+ if (Array.isArray(envelope.choices)) {
+ return envelope.choices.flatMap((choice): readonly NormalizedMessage[] => {
+ const choiceObject = object(choice)
+ return normalizedMessages(choiceObject?.message ?? choice, defaultRole)
+ })
+ }
+ const nested = envelope.messages ?? envelope.message ?? envelope.input ?? envelope.output
+ if (nested !== undefined && nested !== value) return normalizedMessages(nested, defaultRole)
+ }
+ const candidates = Array.isArray(value) ? value : [value]
+ return candidates.flatMap((candidate): NormalizedMessage[] => {
+ const message = normalizedMessage(candidate, defaultRole)
+ return message === undefined ? [] : [message]
+ })
+}
+
+function hasMessageContentShape(message: Record<string, unknown>): boolean {
+ return message.parts !== undefined
+ || message.content !== undefined
+ || message.text !== undefined
+ || message.tool_calls !== undefined
+ || message.toolCalls !== undefined
+}
+
+function normalizedStructuredMessages(
+ value: unknown,
+ defaultRole: string,
+): readonly NormalizedMessage[] | undefined {
+ if (Array.isArray(value)) {
+ if (value.length === 0) return []
+ const messages = value.flatMap((candidate): NormalizedMessage[] => {
+ const candidateObject = object(candidate)
+ if (candidateObject === undefined || !hasMessageContentShape(candidateObject)) return []
+ const message = normalizedMessage(candidateObject, defaultRole)
+ return message === undefined ? [] : [message]
+ })
+ return messages.length === 0 ? undefined : messages
+ }
+ const envelope = object(value)
+ if (envelope === undefined) return undefined
+ if (Array.isArray(envelope.choices)) {
+ if (envelope.choices.length === 0) return []
+ const messages = envelope.choices.flatMap((choice): NormalizedMessage[] => {
+ const choiceObject = object(choice)
+ const normalized = normalizedStructuredMessages(choiceObject?.message ?? choice, defaultRole)
+ return normalized === undefined ? [] : [...normalized]
+ })
+ return messages.length === 0 ? undefined : messages
+ }
+ const nested = envelope.messages ?? envelope.message ?? envelope.input ?? envelope.output
+ if (nested !== undefined && nested !== value) {
+ return normalizedStructuredMessages(nested, defaultRole)
+ }
+ if (!hasMessageContentShape(envelope)) return undefined
+ const message = normalizedMessage(envelope, defaultRole)
+ return message === undefined ? undefined : [message]
+}
+
+function indexedMessages(
+ attributes: OtlpAttributeMap,
+ prefix: string,
+ defaultRole: string,
+): readonly NormalizedMessage[] | undefined {
+ const indexes = new Set<number>()
+ const expression = new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\.(\\d+)\\.`)
+ for (const key of attributes.keys()) {
+ const match = expression.exec(key)
+ if (match?.[1] !== undefined) indexes.add(Number(match[1]))
+ }
+ if (indexes.size === 0) return undefined
+ const messages: NormalizedMessage[] = []
+ for (const index of [...indexes].sort((left, right) => left - right)) {
+ const role = readStringAttribute(attributes, `${prefix}.${index}.role`) ?? defaultRole
+ const contentValue = attributes.get(`${prefix}.${index}.content`)
+ const content = contentValue === undefined ? undefined : flexibleValue(contentValue)
+ const reasoning = readBooleanAttribute(attributes, `${prefix}.${index}.is_reasoning`) === true
+ || role === 'reasoning'
+ const parts = normalizedContentParts(content, reasoning)
+ const toolCallsValue = attributes.get(`${prefix}.${index}.tool_calls`)
+ const toolCalls = toolCallsValue === undefined ? undefined : flexibleValue(toolCallsValue)
+ if (Array.isArray(toolCalls)) {
+ for (const toolCall of toolCalls) {
+ const normalized = normalizedToolCall(toolCall)
+ if (normalized !== undefined) parts.push(normalized)
+ }
+ }
+ messages.push({ role: role === 'reasoning' ? 'assistant' : role, parts })
+ }
+ return messages
+}
+
+function resolveMessages(
+ attributes: OtlpAttributeMap,
+ structuredKeys: readonly string[],
+ indexedPrefixes: readonly string[],
+ observationKey: string,
+ scalarKeys: readonly string[],
+ defaultRole: string,
+): Resolved<unknown> | undefined {
+ for (const key of structuredKeys) {
+ const value = attributes.get(key)
+ if (value === undefined) continue
+ const messages = normalizedStructuredMessages(flexibleValue(value), defaultRole)
+ if (messages !== undefined) return { key, value: messages }
+ }
+ for (const prefix of indexedPrefixes) {
+ const indexed = indexedMessages(attributes, prefix, defaultRole)
+ if (indexed !== undefined) return { key: `${prefix}.*`, value: indexed }
+ }
+ const observation = resolveFlexible(attributes, [observationKey])
+ if (observation !== undefined) {
+ const messages = normalizedMessages(observation.value, defaultRole)
+ if (messages.length > 0 && messages.some(message => message.parts.length > 0)) {
+ return { key: observation.key, value: messages }
+ }
+ }
+ const scalar = resolveFlexible(attributes, scalarKeys)
+ return scalar === undefined
+ ? undefined
+ : { key: scalar.key, value: normalizedMessages(scalar.value, defaultRole) }
+}
+
+function resolveStructuredParts(
+ attributes: OtlpAttributeMap,
+ keys: readonly string[],
+): Resolved<unknown> | undefined {
+ for (const key of keys) {
+ const value = attributes.get(key)
+ if (value === undefined) continue
+ const structured = flexibleValue(value)
+ if (!Array.isArray(structured)) continue
+ return { key, value: normalizedContentParts(structured, false) }
+ }
+ return undefined
+}
+
+function resolveStructuredArray(
+ attributes: OtlpAttributeMap,
+ keys: readonly string[],
+): Resolved<unknown> | undefined {
+ for (const key of keys) {
+ const value = attributes.get(key)
+ if (value === undefined) continue
+ const structured = flexibleValue(value)
+ if (Array.isArray(structured)) return { key, value: structured }
+ }
+ return undefined
+}
+
+function systemFromMessages(value: unknown): readonly NormalizedPart[] | undefined {
+ if (!Array.isArray(value)) return undefined
+ const systemParts = value.flatMap((candidate): NormalizedPart[] => {
+ const message = object(candidate)
+ if (message?.role !== 'system' || !Array.isArray(message.parts)) return []
+ return message.parts.flatMap((part): NormalizedPart[] => {
+ const valuePart = object(part)
+ return valuePart === undefined || typeof valuePart.type !== 'string'
+ ? []
+ : [valuePart as unknown as NormalizedPart]
+ })
+ })
+ return systemParts.length === 0 ? undefined : systemParts
+}
+
+function withoutSystemMessages(value: unknown): unknown {
+ if (!Array.isArray(value)) return value
+ return value.filter((candidate) => object(candidate)?.role !== 'system')
+}
+
+/** Resolve each fact independently, preserving the winning physical key. */
+export function normalizeTrajectoryAttributes(
+ entries: readonly OtlpKeyValue[] | undefined,
+): NormalizedTrajectoryAttributes {
+ const raw = exactAttributeMap(entries)
+ const target: MutableNormalized = { raw, sources: {} }
+ const observationOutput = langfuseOutput(raw)
+
+ assign(target, 'conversationId', resolveString(raw, [
+ STANDARD_ATTRIBUTES.conversationId,
+ OPENJIUWEN_ATTRIBUTES.sessionId,
+ STANDARD_ATTRIBUTES.sessionId,
+ LEGACY.openJiuwenSessionId,
+ LEGACY.agentTeamSessionId,
+ ]))
+ assign(target, 'traceRoot', resolveBoolean(raw, [
+ OPENJIUWEN_ATTRIBUTES.traceRoot,
+ ]))
+ assign(target, 'traceSchemaVersion', resolveString(raw, [
+ OPENJIUWEN_ATTRIBUTES.traceSchemaVersion,
+ DSH_ATTRIBUTES.schemaVersion,
+ ]))
+ assign(target, 'traceComplete', resolveBoolean(raw, [
+ OPENJIUWEN_ATTRIBUTES.traceComplete,
+ ]))
+ assign(target, 'traceForcedClose', resolveBoolean(raw, [
+ OPENJIUWEN_ATTRIBUTES.traceForcedClose,
+ ]))
+ assign(target, 'spanForcedClose', resolveBoolean(raw, [
+ OPENJIUWEN_ATTRIBUTES.spanForcedClose,
+ ]))
+ assign(target, 'spanForcedCloseReason', resolveString(raw, [
+ OPENJIUWEN_ATTRIBUTES.spanForcedCloseReason,
+ ]))
+ assign(target, 'operationName', resolveString(raw, [
+ STANDARD_ATTRIBUTES.operationName,
+ ]))
+ assign(target, 'providerName', resolveString(raw, [
+ STANDARD_ATTRIBUTES.providerName,
+ LEGACY.providerName,
+ ]))
+ assign(target, 'requestId', resolveString(raw, [
+ OPENJIUWEN_ATTRIBUTES.requestId,
+ ]))
+ assign(target, 'runId', resolveString(raw, [
+ OPENJIUWEN_ATTRIBUTES.runId,
+ ]))
+ assign(target, 'turnId', resolveString(raw, [
+ OPENJIUWEN_ATTRIBUTES.turnId,
+ ]))
+ assign(target, 'stepId', resolveString(raw, [
+ OPENJIUWEN_ATTRIBUTES.stepId,
+ ]))
+ assign(target, 'inferenceId', resolveString(raw, [
+ OPENJIUWEN_ATTRIBUTES.inferenceId,
+ ]))
+ assign(target, 'agentMode', resolveString(raw, [
+ OPENJIUWEN_ATTRIBUTES.agentMode,
+ ]))
+ assign(target, 'requestModel', resolveString(raw, [
+ STANDARD_ATTRIBUTES.requestModel,
+ ]))
+ assign(target, 'responseModel', resolveString(raw, [
+ STANDARD_ATTRIBUTES.responseModel,
+ ]))
+ assign(target, 'requestMaxTokens', resolveNonNegativeInt64(raw, [
+ STANDARD_ATTRIBUTES.requestMaxTokens,
+ ]))
+ assign(target, 'requestTemperature', resolveNumber(raw, [
+ STANDARD_ATTRIBUTES.requestTemperature,
+ ]))
+ assign(target, 'requestTopP', resolveNumber(raw, [
+ STANDARD_ATTRIBUTES.requestTopP,
+ ]))
+ assign(target, 'requestStopSequences', resolveStringArray(raw, [
+ STANDARD_ATTRIBUTES.requestStopSequences,
+ ]))
+ assign(target, 'requestStream', resolveBoolean(raw, [
+ STANDARD_ATTRIBUTES.requestStream,
+ ]))
+ assign(target, 'requestReasoningLevel', resolveString(raw, [
+ STANDARD_ATTRIBUTES.requestReasoningLevel,
+ ]))
+ assign(target, 'responseId', resolveString(raw, [
+ STANDARD_ATTRIBUTES.responseId,
+ ]))
+ assign(target, 'responseFinishReasons', resolveStringArray(raw, [
+ STANDARD_ATTRIBUTES.responseFinishReasons,
+ LEGACY.responseFinishReason,
+ ]) ?? langfuseFinishReasons(observationOutput))
+
+ const firstChunk = resolveNonNegativeNumber(raw, [
+ STANDARD_ATTRIBUTES.responseTimeToFirstChunk,
+ ])
+ if (firstChunk !== undefined) {
+ assign(target, 'responseTimeToFirstChunkSeconds', firstChunk)
+ } else {
+ const legacyFirstToken = resolveNonNegativeNumber(raw, [LEGACY.responseTimeToFirstTokenMs])
+ if (legacyFirstToken !== undefined) {
+ assign(target, 'responseTimeToFirstChunkSeconds', {
+ key: legacyFirstToken.key,
+ value: legacyFirstToken.value / 1_000,
+ })
+ }
+ }
+
+ assign(target, 'usageInputTokens', resolveNonNegativeInt64(raw, [
+ STANDARD_ATTRIBUTES.usageInputTokens,
+ LEGACY.usageInputTokens,
+ ]))
+ assign(target, 'usageOutputTokens', resolveNonNegativeInt64(raw, [
+ STANDARD_ATTRIBUTES.usageOutputTokens,
+ LEGACY.usageOutputTokens,
+ ]))
+ assign(target, 'usageReasoningTokens', resolveNonNegativeInt64(raw, [
+ STANDARD_ATTRIBUTES.usageReasoningTokens,
+ LEGACY.usageReasoningTokens,
+ ]))
+ assign(target, 'usageCacheReadTokens', resolveNonNegativeInt64(raw, [
+ STANDARD_ATTRIBUTES.usageCacheReadTokens,
+ LEGACY.usageCacheTokens,
+ ]))
+ assign(target, 'usageCacheCreationTokens', resolveNonNegativeInt64(raw, [
+ STANDARD_ATTRIBUTES.usageCacheCreationTokens,
+ ]))
+ assign(target, 'usageTotalTokens', resolveNonNegativeInt64(raw, [
+ LEGACY.usageTotalTokens,
+ ]))
+
+ if (target.usageInputTokens === undefined) {
+ assign(target, 'usageInputTokens', langfuseUsage(observationOutput, [
+ 'input_tokens',
+ 'prompt_tokens',
+ ]))
+ }
+ if (target.usageOutputTokens === undefined) {
+ assign(target, 'usageOutputTokens', langfuseUsage(observationOutput, [
+ 'output_tokens',
+ 'completion_tokens',
+ ]))
+ }
+ if (target.usageReasoningTokens === undefined) {
+ assign(target, 'usageReasoningTokens', langfuseUsage(observationOutput, [
+ 'reasoning_tokens',
+ ]))
+ }
+ if (target.usageCacheReadTokens === undefined) {
+ assign(target, 'usageCacheReadTokens', langfuseUsage(observationOutput, [
+ 'cache_tokens',
+ 'cache_read_input_tokens',
+ 'cached_tokens',
+ ]))
+ }
+ if (target.usageCacheCreationTokens === undefined) {
+ assign(target, 'usageCacheCreationTokens', langfuseUsage(observationOutput, [
+ 'cache_creation_input_tokens',
+ 'cache_write_input_tokens',
+ ]))
+ }
+ if (target.usageTotalTokens === undefined) {
+ assign(target, 'usageTotalTokens', langfuseUsage(observationOutput, [
+ 'total_tokens',
+ ]))
+ }
+
+ assign(target, 'inputCost', resolveNonNegativeNumber(raw, [
+ OPENJIUWEN_ATTRIBUTES.inputCost,
+ ]))
+ assign(target, 'outputCost', resolveNonNegativeNumber(raw, [
+ OPENJIUWEN_ATTRIBUTES.outputCost,
+ ]))
+ assign(target, 'totalCost', resolveNonNegativeNumber(raw, [
+ OPENJIUWEN_ATTRIBUTES.totalCost,
+ ]))
+ assign(target, 'totalLatencyMs', resolveNonNegativeNumber(raw, [
+ OPENJIUWEN_ATTRIBUTES.totalLatencyMs,
+ ]))
+ assign(target, 'timePerOutputTokenMs', resolveNonNegativeNumber(raw, [
+ OPENJIUWEN_ATTRIBUTES.timePerOutputTokenMs,
+ ]))
+ assign(target, 'promptTokenIds', resolveFlexible(raw, [
+ OPENJIUWEN_ATTRIBUTES.promptTokenIds,
+ ]))
+ assign(target, 'completionTokenIds', resolveFlexible(raw, [
+ OPENJIUWEN_ATTRIBUTES.completionTokenIds,
+ ]))
+ assign(target, 'logprobs', resolveFlexible(raw, [
+ OPENJIUWEN_ATTRIBUTES.logprobs,
+ ]))
+ assign(target, 'parserResult', resolveFlexible(raw, [
+ OPENJIUWEN_ATTRIBUTES.parserResult,
+ ]))
+ assign(target, 'providerMetadata', resolveFlexible(raw, [
+ OPENJIUWEN_ATTRIBUTES.providerMetadata,
+ ]))
+
+ assign(target, 'agentId', resolveString(raw, [
+ STANDARD_ATTRIBUTES.agentId,
+ ]))
+ assign(target, 'agentName', resolveString(raw, [
+ STANDARD_ATTRIBUTES.agentName,
+ LEGACY.deepAgentName,
+ ]))
+ assign(target, 'agentVersion', resolveString(raw, [
+ STANDARD_ATTRIBUTES.agentVersion,
+ ]))
+ assign(target, 'agentDescription', resolveString(raw, [
+ STANDARD_ATTRIBUTES.agentDescription,
+ ]))
+
+ const inputMessages = resolveMessages(
+ raw,
+ [
+ STANDARD_ATTRIBUTES.inputMessages,
+ ],
+ [LEGACY.promptPrefix, LEGACY.langfusePromptPrefix],
+ LEGACY.langfuseInput,
+ [LEGACY.promptScalar],
+ 'user',
+ )
+ if (inputMessages !== undefined) {
+ const explicitSystem = resolveStructuredParts(raw, [
+ STANDARD_ATTRIBUTES.systemInstructions,
+ ])
+ const inferredSystem = systemFromMessages(inputMessages.value)
+ const system = explicitSystem ?? (
+ inferredSystem === undefined
+ ? undefined
+ : { key: inputMessages.key, value: inferredSystem }
+ )
+ assign(target, 'systemInstructions', system)
+ assign(target, 'inputMessages', {
+ key: inputMessages.key,
+ value: withoutSystemMessages(inputMessages.value),
+ })
+ } else {
+ assign(target, 'systemInstructions', resolveStructuredParts(raw, [
+ STANDARD_ATTRIBUTES.systemInstructions,
+ ]))
+ }
+ assign(target, 'inputMessageProvenance', resolveFlexible(raw, [
+ OPENJIUWEN_ATTRIBUTES.inputMessageProvenance,
+ ]))
+
+ const outputMessages = resolveMessages(
+ raw,
+ [
+ STANDARD_ATTRIBUTES.outputMessages,
+ ],
+ [LEGACY.completionPrefix, LEGACY.langfuseCompletionPrefix],
+ LEGACY.langfuseOutput,
+ [LEGACY.completionScalar],
+ 'assistant',
+ )
+ if (outputMessages !== undefined) {
+ const calls = resolveFlexible(raw, [LEGACY.toolCalls])
+ const messages = normalizedMessages(outputMessages.value, 'assistant').map((message, index) => {
+ if (index !== 0 || calls === undefined || !Array.isArray(calls.value)) return message
+ const parts = [...message.parts]
+ for (const call of calls.value) {
+ const normalized = normalizedToolCall(call)
+ if (normalized !== undefined) parts.push(normalized)
+ }
+ return { ...message, parts }
+ })
+ assign(target, 'outputMessages', { key: outputMessages.key, value: messages })
+ }
+
+ assign(target, 'toolDefinitions', resolveStructuredArray(raw, [
+ STANDARD_ATTRIBUTES.toolDefinitions,
+ ]))
+ assign(target, 'toolName', resolveString(raw, [
+ STANDARD_ATTRIBUTES.toolName,
+ ]))
+ assign(target, 'toolCallId', resolveString(raw, [
+ STANDARD_ATTRIBUTES.toolCallId,
+ LEGACY.toolCallId,
+ ]))
+ assign(target, 'toolType', resolveString(raw, [
+ STANDARD_ATTRIBUTES.toolType,
+ ]))
+ assign(target, 'toolDescription', resolveString(raw, [
+ STANDARD_ATTRIBUTES.toolDescription,
+ ]))
+ assign(target, 'toolResourceId', resolveString(raw, [
+ OPENJIUWEN_ATTRIBUTES.toolResourceId,
+ ]))
+ assign(target, 'openJiuwenToolType', resolveString(raw, [
+ OPENJIUWEN_ATTRIBUTES.toolType,
+ ]))
+ assign(target, 'toolAuthoritative', resolveBoolean(raw, [
+ OPENJIUWEN_ATTRIBUTES.toolAuthoritative,
+ ]))
+ assign(target, 'toolCallArguments', resolveFlexible(raw, [
+ STANDARD_ATTRIBUTES.toolCallArguments,
+ LEGACY.toolCallArguments,
+ LEGACY.langfuseInput,
+ ]))
+ assign(target, 'toolCallResult', resolveFlexible(raw, [
+ STANDARD_ATTRIBUTES.toolCallResult,
+ LEGACY.toolCallResult,
+ LEGACY.langfuseOutput,
+ ]))
+
+ assign(target, 'sourceSequence', resolveNonNegativeInt64(raw, [
+ DSH_ATTRIBUTES.sessionSourceSequence,
+ ]))
+ assign(target, 'turnNumber', resolvePositiveInt64(raw, [
+ OPENJIUWEN_ATTRIBUTES.turnNumber,
+ DSH_ATTRIBUTES.turnNumber,
+ ]))
+ assign(target, 'stepNumber', resolvePositiveInt64(raw, [
+ OPENJIUWEN_ATTRIBUTES.stepNumber,
+ DSH_ATTRIBUTES.stepNumber,
+ LEGACY.deepAgentIteration,
+ ]))
+ assign(target, 'trajectoryKind', resolveClosedString(raw, [
+ OPENJIUWEN_ATTRIBUTES.trajectoryKind,
+ DSH_ATTRIBUTES.trajectoryKind,
+ ], TRAJECTORY_KINDS))
+ assign(target, 'requestPurpose', resolveClosedString(raw, [
+ OPENJIUWEN_ATTRIBUTES.requestPurpose,
+ DSH_ATTRIBUTES.requestPurpose,
+ ], REQUEST_PURPOSES))
+ assign(target, 'requestNumber', resolvePositiveInt64(raw, [
+ OPENJIUWEN_ATTRIBUTES.requestNumber,
+ DSH_ATTRIBUTES.requestNumber,
+ ]))
+ assign(target, 'requestRetryCount', resolveNonNegativeInt64(raw, [
+ OPENJIUWEN_ATTRIBUTES.requestRetryCount,
+ DSH_ATTRIBUTES.requestRetryCount,
+ ]))
+ assign(target, 'requestMaxRetries', resolveNonNegativeInt64(raw, [
+ OPENJIUWEN_ATTRIBUTES.requestMaxRetries,
+ DSH_ATTRIBUTES.requestMaxRetries,
+ ]))
+ assign(target, 'messageSourceKind', resolveString(raw, [
+ DSH_ATTRIBUTES.messageSourceKind,
+ ]))
+ assign(target, 'messageSourcePlugin', resolveString(raw, [
+ DSH_ATTRIBUTES.messageSourcePlugin,
+ ]))
+ assign(target, 'compactionInputTokens', resolveNonNegativeInt64(raw, [
+ DSH_ATTRIBUTES.compactionInputTokens,
+ ]))
+ assign(target, 'compactionSummary', resolveString(raw, [
+ DSH_ATTRIBUTES.compactionSummary,
+ ]))
+ assign(target, 'langfuseObservationType', resolveString(raw, [
+ LEGACY.langfuseObservationType,
+ ]))
+ assign(target, 'errorType', resolveString(raw, [
+ STANDARD_ATTRIBUTES.errorType,
+ ]))
+
+ return target
+}
+
+function safeEventSequence(value: bigint | undefined, fallback: number): number {
+ if (value === undefined || value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) return fallback
+ return Number(value)
+}
+
+/** Normalize replayable chunk events without treating ended spans as live revisions. */
+export function normalizeTrajectoryStreamEvents(
+ events: readonly OtlpSpanEvent[] | undefined,
+): readonly NormalizedTrajectoryStreamEvent[] {
+ const normalized: Array<NormalizedTrajectoryStreamEvent & { order: number }> = []
+ for (const [order, event] of (events ?? []).entries()) {
+ if (event.name === OPENJIUWEN_EVENTS.legacyStreamChunk) {
+ normalized.push({
+ sequence: order,
+ kind: 'lifecycle',
+ source: event.name,
+ order,
+ })
+ continue
+ }
+ if (event.name !== OPENJIUWEN_EVENTS.streamChunk && event.name !== DSH_EVENTS.streamChunk) continue
+ const attributes = exactAttributeMap(event.attributes)
+ const sequence = safeEventSequence(
+ resolveNonNegativeInt64(attributes, [
+ OPENJIUWEN_ATTRIBUTES.eventSequence,
+ DSH_ATTRIBUTES.eventSequence,
+ DSH_ATTRIBUTES.streamSequence,
+ ])?.value,
+ order,
+ )
+ const kind = resolveClosedString(attributes, [
+ OPENJIUWEN_ATTRIBUTES.streamKind,
+ DSH_ATTRIBUTES.streamKind,
+ ], STREAM_KINDS)?.value ?? 'lifecycle'
+ const textValue = resolveString(attributes, [
+ OPENJIUWEN_ATTRIBUTES.streamText,
+ DSH_ATTRIBUTES.streamText,
+ ])?.value
+ const toolCallId = resolveString(attributes, [
+ OPENJIUWEN_ATTRIBUTES.streamToolCallId,
+ DSH_ATTRIBUTES.streamToolCallId,
+ ])?.value
+ const toolName = resolveString(attributes, [
+ OPENJIUWEN_ATTRIBUTES.streamToolName,
+ DSH_ATTRIBUTES.streamToolName,
+ ])?.value
+ const argumentsDelta = resolveString(attributes, [
+ OPENJIUWEN_ATTRIBUTES.streamArgumentsDelta,
+ DSH_ATTRIBUTES.streamArgumentsDelta,
+ ])?.value
+ normalized.push({
+ sequence,
+ kind,
+ source: event.name,
+ ...(textValue === undefined ? {} : { text: textValue }),
+ ...(toolCallId === undefined ? {} : { toolCallId }),
+ ...(toolName === undefined ? {} : { toolName }),
+ ...(argumentsDelta === undefined ? {} : { argumentsDelta }),
+ order,
+ })
+ }
+ const ordered = normalized
+ .sort((left, right) => left.sequence - right.sequence || left.order - right.order)
+ const hasReplayableEvent = ordered.some(event => event.kind !== 'lifecycle')
+ const selected = new Map<string, typeof ordered[number]>()
+ const priority = (source: string): number => source === OPENJIUWEN_EVENTS.streamChunk
+ ? 0
+ : source === DSH_EVENTS.streamChunk ? 1 : 2
+ for (const event of ordered) {
+ if (hasReplayableEvent && event.kind === 'lifecycle') continue
+ const identity = [
+ event.sequence,
+ event.kind,
+ event.toolCallId ?? '',
+ event.toolName ?? '',
+ ].join('\u0000')
+ const existing = selected.get(identity)
+ if (existing === undefined || priority(event.source) < priority(existing.source)) {
+ selected.set(identity, event)
+ }
+ }
+ return [...selected.values()]
+ .sort((left, right) => left.sequence - right.sequence || left.order - right.order)
+ .map(event => ({
+ sequence: event.sequence,
+ kind: event.kind,
+ source: event.source,
+ ...(event.text === undefined ? {} : { text: event.text }),
+ ...(event.toolCallId === undefined ? {} : { toolCallId: event.toolCallId }),
+ ...(event.toolName === undefined ? {} : { toolName: event.toolName }),
+ ...(event.argumentsDelta === undefined ? {} : { argumentsDelta: event.argumentsDelta }),
+ }))
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/otel-trajectory-projector.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/otel-trajectory-projector.ts
new file mode 100644
index 0000000000..120b2ab1fd
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/otel-trajectory-projector.ts
@@ -0,0 +1,1272 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Pure OTLP/GenAI to standalone trajectory read-model projection. */
+
+import {
+ exactAttributeMap,
+ readStringAttribute,
+} from '../semconv/attributes.ts'
+import {
+ GEN_AI_OPERATIONS, STANDARD_ATTRIBUTES,
+} from '../semconv/constants.ts'
+import type {
+ NormalizedTrajectoryAttributes, NormalizedTrajectoryStreamEvent,
+} from './attribute-resolver.ts'
+import {
+ normalizeTrajectoryAttributes, normalizeTrajectoryStreamEvents,
+} from './attribute-resolver.ts'
+import type {
+ OtlpExportTraceServiceRequest, OtlpSpan,
+} from '../shared/otlp.ts'
+import type {
+ TrajectoryPromptSnapshot,
+ TrajectoryRecordedFacts,
+ TrajectoryRequest,
+ TrajectoryRequestConfig,
+ TrajectorySnapshot,
+ TrajectoryToolSchema,
+ TrajectoryTurnModel,
+ TrajectoryUsage,
+} from '../trajectory/model.ts'
+import type {
+ TrajectoryCell, TrajectorySourceBlock,
+} from '../trajectory/record.ts'
+
+interface ProjectedSpan {
+ attributes: NormalizedTrajectoryAttributes
+ endTimeUnixNano: bigint | undefined
+ explicitTurn: number | undefined
+ parentSpanId: string | undefined
+ request: OtlpExportTraceServiceRequest
+ sourceSequence: number | undefined
+ requestNumber: number | undefined
+ streamEvents: readonly NormalizedTrajectoryStreamEvent[]
+ span: OtlpSpan
+ startTimeUnixNano: bigint
+ traceId: string
+ turn: number
+ lifecycle: 'running' | 'completed' | 'error'
+}
+
+export interface TrajectoryProjectionOptions {
+ lifecycleByRecordId?: ReadonlyMap<string, 'running' | 'completed' | 'error'>
+}
+
+interface StructuredPart {
+ arguments?: unknown
+ content?: string
+ id?: string
+ name?: string
+ response?: unknown
+ type: string
+}
+
+interface StructuredMessage {
+ inputIndex?: number
+ inputKind?: 'prompt_attachment'
+ parts: readonly StructuredPart[]
+ role: string
+}
+
+interface MutableGroup {
+ title: string
+ description?: string
+ cells: TrajectoryCell[]
+}
+
+interface MutableTurn {
+ turn: number
+ groups: Map<number, MutableGroup>
+}
+
+interface InferenceInputProjection {
+ messages: readonly StructuredMessage[]
+ prompt: TrajectoryPromptSnapshot | undefined
+}
+
+interface ToolResultFact {
+ id?: string
+ name?: string
+ response: unknown
+ traceId: string
+}
+
+interface IndexedMessage {
+ inputIndex: number
+ message: StructuredMessage
+}
+
+const NANOSECONDS_PER_MILLISECOND = 1_000_000n
+const NANOSECONDS_PER_SECOND = 1_000_000_000n
+const HASH_MASK = (1n << 52n) - 1n
+const KNOWN_OPERATIONS = new Set<string>(Object.values(GEN_AI_OPERATIONS))
+
+function object(value: unknown): Record<string, unknown> | undefined {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : undefined
+}
+
+function parsedJson(value: string): unknown {
+ try {
+ return JSON.parse(value) as unknown
+ } catch {
+ return value
+ }
+}
+
+function nonNegativeSafeInteger(value: bigint | undefined): number | undefined {
+ if (value === undefined || value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) return undefined
+ return Number(value)
+}
+
+function positiveSafeInteger(value: bigint | undefined): number | undefined {
+ const safe = nonNegativeSafeInteger(value)
+ return safe === undefined || safe === 0 ? undefined : safe
+}
+
+function spansOf(record: OtlpExportTraceServiceRequest): readonly OtlpSpan[] {
+ return record.resourceSpans.flatMap(resource =>
+ (resource.scopeSpans ?? []).flatMap(scope => scope.spans ?? []))
+}
+
+function soleSpan(record: OtlpExportTraceServiceRequest): OtlpSpan {
+ const spans = spansOf(record)
+ if (spans.length !== 1) {
+ throw new TypeError(`Trajectory records require exactly one Span; received ${spans.length}`)
+ }
+ const span = spans[0]
+ if (span === undefined) throw new TypeError('Trajectory record contains no Span')
+ return span
+}
+
+function compareBigint(left: bigint, right: bigint): number {
+ return left < right ? -1 : left > right ? 1 : 0
+}
+
+function compareSpans(left: ProjectedSpan, right: ProjectedSpan): number {
+ if (left.sourceSequence !== undefined && right.sourceSequence !== undefined) {
+ return left.sourceSequence - right.sourceSequence
+ }
+ return compareBigint(left.startTimeUnixNano, right.startTimeUnixNano)
+ || left.traceId.localeCompare(right.traceId)
+ || left.span.spanId.localeCompare(right.span.spanId)
+}
+
+function stableIndex(identity: string): number {
+ let hash = 0xcbf29ce484222325n
+ for (const character of identity) {
+ hash ^= BigInt(character.codePointAt(0) ?? 0)
+ hash = (hash * 0x100000001b3n) & 0xffffffffffffffffn
+ }
+ return Number(hash & HASH_MASK)
+}
+
+function recordIdentity(span: ProjectedSpan, suffix: string): string {
+ return `${span.traceId}:${span.span.spanId}:${suffix}`
+}
+
+function cellIndex(span: ProjectedSpan, suffix: string): number {
+ return stableIndex(recordIdentity(span, suffix))
+}
+
+function requestRecordIdentity(span: ProjectedSpan): string | undefined {
+ if (span.attributes.inferenceId !== undefined) {
+ return `${span.traceId}:inference:${span.attributes.inferenceId}`
+ }
+ if (span.requestNumber !== undefined) {
+ return `${span.traceId}:request:${span.requestNumber}`
+ }
+ return isInference(span) ? `${span.traceId}:${span.span.spanId}:request` : undefined
+}
+
+function startedAt(span: ProjectedSpan): number {
+ return Number(span.startTimeUnixNano / NANOSECONDS_PER_MILLISECOND)
+}
+
+function durationSeconds(span: ProjectedSpan): number | null {
+ if (span.endTimeUnixNano === undefined) return null
+ return Number(span.endTimeUnixNano - span.startTimeUnixNano) / Number(NANOSECONDS_PER_SECOND)
+}
+
+function formatted(value: unknown): string {
+ if (typeof value === 'string') return value
+ return JSON.stringify(value, null, 2) ?? String(value)
+}
+
+function structuralIdentity(value: unknown): string {
+ if (Array.isArray(value)) return `[${value.map(structuralIdentity).join(',')}]`
+ const valueObject = object(value)
+ if (valueObject === undefined) return JSON.stringify(value) ?? String(value)
+ return `{${Object.keys(valueObject).sort().map(key => (
+ `${JSON.stringify(key)}:${structuralIdentity(valueObject[key])}`
+ )).join(',')}}`
+}
+
+function structuredParts(value: unknown): readonly StructuredPart[] {
+ if (!Array.isArray(value)) return []
+ return value.flatMap((candidate): StructuredPart[] => {
+ const part = object(candidate)
+ if (part === undefined || typeof part.type !== 'string') return []
+ return [{
+ type: part.type,
+ ...(typeof part.content === 'string' ? { content: part.content } : {}),
+ ...(typeof part.id === 'string' ? { id: part.id } : {}),
+ ...(typeof part.name === 'string' ? { name: part.name } : {}),
+ ...(part.arguments === undefined ? {} : { arguments: part.arguments }),
+ ...(part.response === undefined ? {} : { response: part.response }),
+ }]
+ })
+}
+
+function structuredMessages(value: unknown): readonly StructuredMessage[] {
+ if (!Array.isArray(value)) return []
+ return value.flatMap((candidate): StructuredMessage[] => {
+ const message = object(candidate)
+ if (message === undefined || typeof message.role !== 'string') return []
+ return [{ role: message.role, parts: structuredParts(message.parts) }]
+ })
+}
+
+function sourceBlocks(parts: readonly StructuredPart[]): readonly TrajectorySourceBlock[] {
+ return parts.flatMap((part): TrajectorySourceBlock[] => {
+ switch (part.type) {
+ case 'text':
+ case 'reasoning':
+ case 'compaction':
+ return [{ type: part.type, content: part.content ?? '' }]
+ case 'tool_call':
+ return [{
+ type: 'tool-call',
+ content: formatted(part.arguments ?? {}),
+ ...(part.id === undefined ? {} : { callId: part.id }),
+ ...(part.name === undefined ? {} : { toolName: part.name }),
+ }]
+ case 'tool_call_response':
+ return [{
+ type: 'tool-result',
+ content: formatted(part.response),
+ ...(part.id === undefined ? {} : { callId: part.id }),
+ ...(part.name === undefined ? {} : { toolName: part.name }),
+ }]
+ default:
+ return [{ type: part.type, content: part.content ?? formatted(part) }]
+ }
+ })
+}
+
+function streamParts(events: readonly NormalizedTrajectoryStreamEvent[]): readonly StructuredPart[] {
+ const parts: StructuredPart[] = []
+ const indexByIdentity = new Map<string, number>()
+ const append = (identity: string, create: () => StructuredPart, delta: string | undefined) => {
+ const existingIndex = indexByIdentity.get(identity)
+ if (existingIndex === undefined) {
+ const part = create()
+ if (delta !== undefined) part.content = delta
+ indexByIdentity.set(identity, parts.length)
+ parts.push(part)
+ return
+ }
+ if (delta === undefined) return
+ const existing = parts[existingIndex]
+ if (existing !== undefined) existing.content = `${existing.content ?? ''}${delta}`
+ }
+ for (const event of events) {
+ if (event.kind === 'text-delta') {
+ append('text', () => ({ type: 'text' }), event.text)
+ continue
+ }
+ if (event.kind === 'reasoning-delta') {
+ append('reasoning', () => ({ type: 'reasoning' }), event.text)
+ continue
+ }
+ if (event.kind !== 'tool-call-delta') continue
+ const identity = `tool:${event.toolCallId ?? event.toolName ?? 'unknown'}`
+ const existingIndex = indexByIdentity.get(identity)
+ if (existingIndex === undefined) {
+ indexByIdentity.set(identity, parts.length)
+ parts.push({
+ type: 'tool_call',
+ ...(event.toolCallId === undefined ? {} : { id: event.toolCallId }),
+ ...(event.toolName === undefined ? {} : { name: event.toolName }),
+ ...(event.argumentsDelta === undefined ? {} : { arguments: event.argumentsDelta }),
+ })
+ continue
+ }
+ if (event.argumentsDelta === undefined) continue
+ const existing = parts[existingIndex]
+ if (existing !== undefined) {
+ existing.arguments = `${typeof existing.arguments === 'string' ? existing.arguments : ''}${event.argumentsDelta}`
+ }
+ }
+ return parts
+}
+
+function partText(parts: readonly StructuredPart[], type: string): string | undefined {
+ const text = parts.flatMap(part => part.type === type && part.content !== undefined
+ ? [part.content]
+ : []).join('\n\n')
+ return text === '' ? undefined : text
+}
+
+function requestConfig(attributes: NormalizedTrajectoryAttributes): TrajectoryRequestConfig {
+ const provider = attributes.providerName ?? 'unknown'
+ const model = attributes.requestModel ?? attributes.responseModel ?? 'unknown'
+ const stop = attributes.requestStopSequences
+ const purpose = attributes.requestPurpose
+ const reasoningEffort = attributes.requestReasoningLevel
+ const temperature = attributes.requestTemperature
+ const topP = attributes.requestTopP
+ const stream = attributes.requestStream
+ const maxTokens = nonNegativeSafeInteger(attributes.requestMaxTokens)
+ return {
+ provider,
+ model,
+ ...(purpose === undefined ? {} : { purpose }),
+ ...(reasoningEffort === undefined ? {} : { reasoningEffort }),
+ ...(temperature === undefined ? {} : { temperature }),
+ ...(topP === undefined ? {} : { topP }),
+ ...(maxTokens === undefined ? {} : { maxTokens }),
+ ...(stop === undefined ? {} : { stop }),
+ ...(stream === undefined ? {} : { stream }),
+ }
+}
+
+function nonEmpty<T extends object>(value: T): T | undefined {
+ return Object.keys(value).length === 0 ? undefined : value
+}
+
+function recordedFacts(
+ attributes: NormalizedTrajectoryAttributes,
+ rootAttributes: NormalizedTrajectoryAttributes | undefined,
+): TrajectoryRecordedFacts | undefined {
+ const root = rootAttributes ?? attributes
+ const correlation = nonEmpty({
+ ...(attributes.conversationId === undefined && root.conversationId === undefined
+ ? {}
+ : { sessionId: attributes.conversationId ?? root.conversationId }),
+ ...(attributes.requestId === undefined && root.requestId === undefined
+ ? {}
+ : { requestId: attributes.requestId ?? root.requestId }),
+ ...(attributes.runId === undefined && root.runId === undefined
+ ? {}
+ : { runId: attributes.runId ?? root.runId }),
+ ...(attributes.turnId === undefined && root.turnId === undefined
+ ? {}
+ : { turnId: attributes.turnId ?? root.turnId }),
+ })
+ const agent = nonEmpty({
+ ...(attributes.agentId === undefined ? {} : { id: attributes.agentId }),
+ ...(attributes.agentName === undefined ? {} : { name: attributes.agentName }),
+ ...(attributes.agentVersion === undefined ? {} : { version: attributes.agentVersion }),
+ ...(attributes.agentDescription === undefined ? {} : { description: attributes.agentDescription }),
+ ...(attributes.agentMode === undefined && root.agentMode === undefined
+ ? {}
+ : { mode: attributes.agentMode ?? root.agentMode }),
+ })
+ const response = nonEmpty({
+ ...(attributes.responseId === undefined ? {} : { id: attributes.responseId }),
+ ...(attributes.responseModel === undefined ? {} : { model: attributes.responseModel }),
+ ...(attributes.responseFinishReasons === undefined
+ ? {}
+ : { finishReasons: attributes.responseFinishReasons }),
+ ...(attributes.totalLatencyMs === undefined ? {} : { totalLatencyMs: attributes.totalLatencyMs }),
+ ...(attributes.timePerOutputTokenMs === undefined
+ ? {}
+ : { timePerOutputTokenMs: attributes.timePerOutputTokenMs }),
+ ...(attributes.promptTokenIds === undefined ? {} : { promptTokenIds: attributes.promptTokenIds }),
+ ...(attributes.completionTokenIds === undefined
+ ? {}
+ : { completionTokenIds: attributes.completionTokenIds }),
+ ...(attributes.logprobs === undefined ? {} : { logprobs: attributes.logprobs }),
+ ...(attributes.parserResult === undefined ? {} : { parserResult: attributes.parserResult }),
+ ...(attributes.providerMetadata === undefined
+ ? {}
+ : { providerMetadata: attributes.providerMetadata }),
+ })
+ const cost = nonEmpty({
+ ...(attributes.inputCost === undefined ? {} : { input: attributes.inputCost }),
+ ...(attributes.outputCost === undefined ? {} : { output: attributes.outputCost }),
+ ...(attributes.totalCost === undefined ? {} : { total: attributes.totalCost }),
+ })
+ const trace = nonEmpty({
+ ...(root.traceRoot === undefined ? {} : { root: root.traceRoot }),
+ ...(root.traceSchemaVersion === undefined
+ ? attributes.traceSchemaVersion === undefined ? {} : { schemaVersion: attributes.traceSchemaVersion }
+ : { schemaVersion: root.traceSchemaVersion }),
+ ...(root.traceComplete === undefined ? {} : { complete: root.traceComplete }),
+ ...(root.traceForcedClose === undefined ? {} : { forcedClose: root.traceForcedClose }),
+ })
+ return nonEmpty({
+ ...(correlation === undefined ? {} : { correlation }),
+ ...(agent === undefined ? {} : { agent }),
+ ...(response === undefined ? {} : { response }),
+ ...(cost === undefined ? {} : { cost }),
+ ...(trace === undefined ? {} : { trace }),
+ })
+}
+
+function toolSchemas(value: unknown): readonly TrajectoryToolSchema[] {
+ if (!Array.isArray(value)) return []
+ return value.flatMap((candidate): TrajectoryToolSchema[] => {
+ const tool = object(candidate)
+ if (tool === undefined) return []
+ const functionDefinition = object(tool.function)
+ const definition = functionDefinition ?? tool
+ if (typeof definition.name !== 'string') return []
+ const parameters = definition.parameters
+ return [{
+ name: definition.name,
+ description: typeof definition.description === 'string' ? definition.description : '',
+ parameters: (typeof parameters === 'object' && parameters !== null)
+ ? parameters as object | unknown[]
+ : {},
+ }]
+ })
+}
+
+function promptSnapshot(attributes: NormalizedTrajectoryAttributes): TrajectoryPromptSnapshot | undefined {
+ const instructions = structuredParts(attributes.systemInstructions)
+ const tools = toolSchemas(attributes.toolDefinitions)
+ if (instructions.length === 0 && tools.length === 0) return undefined
+ return {
+ config: requestConfig(attributes),
+ system: instructions.flatMap(part => part.content === undefined ? [] : [part.content]).join('\n\n'),
+ tools,
+ }
+}
+
+function usage(attributes: NormalizedTrajectoryAttributes): TrajectoryUsage {
+ const input = nonNegativeSafeInteger(attributes.usageInputTokens)
+ const cacheRead = nonNegativeSafeInteger(attributes.usageCacheReadTokens)
+ const cacheWrite = nonNegativeSafeInteger(attributes.usageCacheCreationTokens)
+ const output = nonNegativeSafeInteger(attributes.usageOutputTokens)
+ const reasoning = nonNegativeSafeInteger(attributes.usageReasoningTokens)
+ const total = nonNegativeSafeInteger(attributes.usageTotalTokens)
+ return {
+ ...(input === undefined ? {} : { input }),
+ ...(cacheRead === undefined ? {} : { cacheRead }),
+ ...(cacheWrite === undefined ? {} : { cacheWrite }),
+ ...(output === undefined ? {} : { output }),
+ ...(reasoning === undefined ? {} : { reasoning }),
+ ...(total === undefined ? {} : { total }),
+ }
+}
+
+function addUsage(total: TrajectoryUsage, next: TrajectoryUsage): TrajectoryUsage {
+ const sum = (left: number | undefined, right: number | undefined): number | undefined =>
+ left === undefined && right === undefined ? undefined : (left ?? 0) + (right ?? 0)
+ const input = sum(total.input, next.input)
+ const cacheRead = sum(total.cacheRead, next.cacheRead)
+ const cacheWrite = sum(total.cacheWrite, next.cacheWrite)
+ const output = sum(total.output, next.output)
+ const reasoning = sum(total.reasoning, next.reasoning)
+ const grandTotal = sum(total.total, next.total)
+ return {
+ ...(input === undefined ? {} : { input }),
+ ...(cacheRead === undefined ? {} : { cacheRead }),
+ ...(cacheWrite === undefined ? {} : { cacheWrite }),
+ ...(output === undefined ? {} : { output }),
+ ...(reasoning === undefined ? {} : { reasoning }),
+ ...(grandTotal === undefined ? {} : { total: grandTotal }),
+ }
+}
+
+function status(projected: ProjectedSpan): 'complete' | 'running' | 'error' {
+ if (projected.lifecycle === 'running') return 'running'
+ if (projected.lifecycle === 'error') return 'error'
+ return projected.span.status?.code === 2 || projected.attributes.spanForcedClose === true
+ ? 'error'
+ : 'complete'
+}
+
+function statusError(projected: ProjectedSpan): string | undefined {
+ const statusIsError = projected.span.status?.code === 2
+ const forcedClose = projected.attributes.spanForcedClose === true
+ if (!statusIsError && !forcedClose && projected.lifecycle !== 'error') return undefined
+ if (statusIsError
+ && projected.span.status?.message !== undefined
+ && projected.span.status.message !== '') {
+ return projected.span.status.message
+ }
+ if (statusIsError && projected.attributes.errorMessage !== undefined) {
+ return projected.attributes.errorMessage
+ }
+ const exception = projected.span.events?.find(event => event.name === 'exception')
+ if (exception !== undefined) {
+ const attributes = exactAttributeMap(exception.attributes)
+ const message = readStringAttribute(attributes, STANDARD_ATTRIBUTES.exceptionMessage)
+ if (message !== undefined) return message
+ const type = readStringAttribute(attributes, STANDARD_ATTRIBUTES.exceptionType)
+ if (type !== undefined) return type
+ }
+ if (statusIsError && projected.attributes.errorType !== undefined) {
+ return projected.attributes.errorType
+ }
+ if (forcedClose) {
+ return projected.attributes.spanForcedCloseReason ?? 'Span was force-closed during trace finalization'
+ }
+ if (projected.lifecycle === 'error') return 'Trajectory operation reported an error'
+ return 'OpenTelemetry Span reported an error'
+}
+
+function operation(span: ProjectedSpan): string | undefined {
+ return span.attributes.operationName
+}
+
+function knownOperation(span: ProjectedSpan): string | undefined {
+ const name = operation(span)
+ return name !== undefined && KNOWN_OPERATIONS.has(name) ? name : undefined
+}
+
+function recordKind(span: ProjectedSpan): string | undefined {
+ return span.attributes.trajectoryKind
+}
+
+function isInference(span: ProjectedSpan): boolean {
+ const kind = recordKind(span)
+ if (kind !== undefined) return kind === 'inference'
+ const name = knownOperation(span)
+ if (name !== undefined) return name === GEN_AI_OPERATIONS.chat
+ || name === GEN_AI_OPERATIONS.generateContent
+ || name === GEN_AI_OPERATIONS.textCompletion
+ return span.attributes.langfuseObservationType === 'generation'
+}
+
+function isTool(span: ProjectedSpan): boolean {
+ const kind = recordKind(span)
+ if (kind !== undefined) return kind === 'tool'
+ const name = knownOperation(span)
+ if (name !== undefined) return name === GEN_AI_OPERATIONS.executeTool
+ if (span.attributes.langfuseObservationType === 'tool') return true
+ return span.span.name.startsWith('tool.') || span.span.name.startsWith('execute_tool')
+}
+
+function isCompaction(span: ProjectedSpan): boolean {
+ return recordKind(span) === 'compaction'
+}
+
+function spanCellBase(span: ProjectedSpan, suffix: string): Pick<
+ TrajectoryCell,
+ 'index' | 'recordId' | 'sourceSeq' | 'startedAt' | 'status' | 'timeSeconds' | 'traceDetail'
+> & Pick<TrajectoryCell, 'requestRecordId'> {
+ return {
+ index: cellIndex(span, suffix),
+ recordId: recordIdentity(span, suffix),
+ ...(span.sourceSequence === undefined ? {} : { sourceSeq: span.sourceSequence }),
+ startedAt: startedAt(span),
+ timeSeconds: durationSeconds(span),
+ status: status(span),
+ traceDetail: span.request,
+ ...(requestRecordIdentity(span) === undefined
+ ? {}
+ : { requestRecordId: requestRecordIdentity(span) }),
+ }
+}
+
+function inputCells(
+ span: ProjectedSpan,
+ projection: InferenceInputProjection,
+): TrajectoryCell[] {
+ const cells: TrajectoryCell[] = []
+ const prompt = projection.prompt
+ if (prompt !== undefined) {
+ const text = prompt.system !== ''
+ ? prompt.system
+ : `${prompt.tools.length} tool definition${prompt.tools.length === 1 ? '' : 's'}`
+ cells.push({
+ ...spanCellBase(span, 'system'),
+ timeSeconds: null,
+ kind: 'system',
+ text,
+ promptDetail: prompt,
+ })
+ }
+ projection.messages.forEach((message, index) => {
+ const blocks = sourceBlocks(message.parts)
+ const text = partText(message.parts, 'text')
+ ?? partText(message.parts, 'compaction')
+ ?? blocks.map(block => block.content).filter(Boolean).join('\n')
+ const attachment = message.inputKind === 'prompt_attachment'
+ const user = message.role === 'user' && !attachment
+ cells.push({
+ ...spanCellBase(span, `input:${message.inputIndex ?? index}`),
+ timeSeconds: null,
+ kind: user ? 'user' : 'context',
+ text,
+ inputDetail: text,
+ sourceBlocks: blocks,
+ messageSource: {
+ role: message.role,
+ kind: attachment
+ ? 'prompt_attachment'
+ : span.attributes.messageSourceKind ?? message.role,
+ plugin: span.attributes.messageSourcePlugin,
+ inputIndex: message.inputIndex ?? index,
+ ...(attachment ? { scope: 'request' } : {}),
+ },
+ })
+ })
+ return cells
+}
+
+function assistantCell(span: ProjectedSpan): TrajectoryCell {
+ const messages = structuredMessages(span.attributes.outputMessages)
+ const completedParts = messages.flatMap(message => message.parts)
+ const replayParts = streamParts(span.streamEvents)
+ const completedTypes = new Set(completedParts.map(part => part.type))
+ const parts = [
+ ...completedParts,
+ ...replayParts.filter(part => !completedTypes.has(part.type)),
+ ]
+ const blocks = sourceBlocks(parts)
+ const output = partText(parts, 'text')
+ const thinking = partText(parts, 'reasoning')
+ const toolCalls = blocks.filter(block => block.type === 'tool-call')
+ const text = output
+ ?? thinking
+ ?? (toolCalls.length > 0
+ ? 'Tool call only'
+ : span.lifecycle === 'running' ? 'Waiting for model response…' : 'No output content')
+ const usageValue = usage(span.attributes)
+ const firstChunkSeconds = span.attributes.responseTimeToFirstChunkSeconds
+ const start = startedAt(span)
+ const error = statusError(span)
+ return {
+ ...spanCellBase(span, 'assistant'),
+ kind: 'message',
+ text,
+ ...(output === undefined ? {} : { outputDetail: output, previewMarkdown: output }),
+ ...(thinking === undefined ? {} : { thinkingDetail: thinking }),
+ sourceBlocks: blocks,
+ outputBlocks: blocks.filter(block => block.type === 'text' || block.type === 'reasoning'),
+ assistantMetrics: {
+ timingRecorded: true,
+ stepStartTime: start,
+ firstTokenTime: firstChunkSeconds === undefined ? null : start + firstChunkSeconds * 1_000,
+ completedTime: span.endTimeUnixNano === undefined
+ ? null
+ : Number(span.endTimeUnixNano / NANOSECONDS_PER_MILLISECOND),
+ usageProvided: Object.keys(usageValue).length > 0,
+ outputTokens: usageValue.output ?? null,
+ },
+ ...(error === undefined ? {} : { isError: true, result: error }),
+ ...(usageValue.input === undefined ? {} : { input: usageValue.input }),
+ ...(usageValue.cacheRead === undefined ? {} : { cacheRead: usageValue.cacheRead }),
+ ...(usageValue.cacheWrite === undefined ? {} : { cacheWrite: usageValue.cacheWrite }),
+ ...(usageValue.output === undefined ? {} : { output: usageValue.output }),
+ ...(usageValue.reasoning === undefined ? {} : { think: usageValue.reasoning }),
+ ...(usageValue.total === undefined ? {} : { total: usageValue.total }),
+ }
+}
+
+function toolCell(
+ span: ProjectedSpan,
+ toolSpanIds: ReadonlySet<string>,
+ schemaDetail: string | undefined,
+ correlatedResult: ToolResultFact | undefined,
+): TrajectoryCell {
+ const name = span.attributes.toolName ?? span.span.name
+ const callId = span.attributes.toolCallId ?? `${span.traceId}:${span.span.spanId}`
+ const input = span.attributes.toolCallArguments
+ const result = span.attributes.toolCallResult === undefined
+ ? correlatedResult?.response
+ : span.attributes.toolCallResult
+ const inputText = input === undefined ? undefined : formatted(input)
+ const resultText = result === undefined ? undefined : formatted(result)
+ const nested = span.parentSpanId !== undefined && toolSpanIds.has(span.parentSpanId)
+ const error = statusError(span)
+ const description = span.attributes.toolDescription
+ const toolMetadata = nonEmpty({
+ ...(description === undefined ? {} : { description }),
+ ...(span.attributes.toolType === undefined && span.attributes.openJiuwenToolType === undefined
+ ? {}
+ : { type: span.attributes.toolType ?? span.attributes.openJiuwenToolType }),
+ ...(span.attributes.toolResourceId === undefined
+ ? {}
+ : { resourceId: span.attributes.toolResourceId }),
+ ...(span.attributes.toolAuthoritative === undefined
+ ? {}
+ : { authoritative: span.attributes.toolAuthoritative }),
+ })
+ const detail = schemaDetail === undefined && toolMetadata === undefined
+ ? undefined
+ : JSON.stringify({
+ ...(schemaDetail === undefined ? {} : { definition: parsedJson(schemaDetail) }),
+ ...(toolMetadata === undefined ? {} : { metadata: toolMetadata }),
+ }, null, 2)
+ return {
+ ...spanCellBase(span, 'tool'),
+ kind: nested ? 'subtool' : 'tool',
+ text: inputText === undefined ? name : `${name} · ${inputText.replace(/\s+/g, ' ').slice(0, 160)}`,
+ callId,
+ ...(inputText === undefined ? {} : { inputDetail: inputText }),
+ ...(resultText === undefined ? {} : { outputDetail: resultText, result: resultText }),
+ ...(error === undefined ? {} : { isError: true, result: error }),
+ ...(detail === undefined ? {} : { schemaDetail: detail }),
+ }
+}
+
+function occurrenceTokens(messages: readonly IndexedMessage[]): readonly string[] {
+ const occurrences = new Map<string, number>()
+ return messages.map(({ message }) => {
+ const identity = structuralIdentity(message)
+ const occurrence = (occurrences.get(identity) ?? 0) + 1
+ occurrences.set(identity, occurrence)
+ return `${identity}\u0000${occurrence}`
+ })
+}
+
+function lcsInsertedInputIndexes(
+ previous: readonly IndexedMessage[],
+ current: readonly IndexedMessage[],
+): ReadonlySet<number> {
+ const previousTokens = occurrenceTokens(previous)
+ const currentTokens = occurrenceTokens(current)
+ let prefix = 0
+ while (
+ prefix < Math.min(previousTokens.length, currentTokens.length)
+ && previousTokens[prefix] === currentTokens[prefix]
+ ) prefix += 1
+ let suffix = 0
+ const suffixLimit = Math.min(previousTokens.length, currentTokens.length) - prefix
+ while (
+ suffix < suffixLimit
+ && previousTokens[previousTokens.length - suffix - 1]
+ === currentTokens[currentTokens.length - suffix - 1]
+ ) suffix += 1
+
+ const previousEnd = previousTokens.length - suffix
+ const currentEnd = currentTokens.length - suffix
+ const previousLength = previousEnd - prefix
+ const currentLength = currentEnd - prefix
+ const lengths = Array.from(
+ { length: previousLength + 1 },
+ () => new Uint32Array(currentLength + 1),
+ )
+ for (let left = previousLength - 1; left >= 0; left -= 1) {
+ for (let right = currentLength - 1; right >= 0; right -= 1) {
+ lengths[left][right] = previousTokens[prefix + left] === currentTokens[prefix + right]
+ ? 1 + lengths[left + 1][right + 1]
+ : Math.max(lengths[left + 1][right], lengths[left][right + 1])
+ }
+ }
+
+ const inserted = new Set<number>()
+ let left = 0
+ let right = 0
+ while (left < previousLength && right < currentLength) {
+ if (previousTokens[prefix + left] === currentTokens[prefix + right]) {
+ left += 1
+ right += 1
+ continue
+ }
+ if (lengths[left + 1][right] >= lengths[left][right + 1]) {
+ left += 1
+ continue
+ }
+ const entry = current[prefix + right]
+ if (entry !== undefined) inserted.add(entry.inputIndex)
+ right += 1
+ }
+ while (right < currentLength) {
+ const entry = current[prefix + right]
+ if (entry !== undefined) inserted.add(entry.inputIndex)
+ right += 1
+ }
+ return inserted
+}
+
+function legacyRequestScopedAttachment(message: StructuredMessage): boolean {
+ return message.parts.some(part => (
+ part.type === 'prompt_attachment'
+ || (
+ part.type === 'text'
+ && part.content?.includes('<system-reminder>') === true
+ && part.content.includes('<prompt-attachment')
+ )
+ ))
+}
+
+function provenanceAttachmentIndexes(
+ value: unknown,
+): ReadonlySet<number> | undefined {
+ if (value === undefined) return undefined
+ if (!Array.isArray(value)) return new Set<number>()
+ const indexes = value.flatMap((candidate): number[] => {
+ const provenance = object(candidate)
+ if (
+ provenance?.kind !== 'prompt_attachment'
+ || provenance.scope !== 'request'
+ ) return []
+ const index = provenance.input_message_index
+ if (typeof index === 'number' && Number.isSafeInteger(index) && index >= 0) return [index]
+ if (typeof index !== 'string' || !/^\d+$/.test(index)) return []
+ const parsed = Number(index)
+ return Number.isSafeInteger(parsed) ? [parsed] : []
+ })
+ return new Set(indexes)
+}
+
+function behaviorSessionKey(span: ProjectedSpan): string {
+ return span.attributes.conversationId ?? `trace:${span.traceId}`
+}
+
+function compareInferenceBehavior(left: ProjectedSpan, right: ProjectedSpan): number {
+ return compareBigint(left.startTimeUnixNano, right.startTimeUnixNano)
+ || (left.requestNumber ?? 0) - (right.requestNumber ?? 0)
+ || (left.sourceSequence ?? 0) - (right.sourceSequence ?? 0)
+ || left.traceId.localeCompare(right.traceId)
+ || left.span.spanId.localeCompare(right.span.spanId)
+}
+
+function consumePriorOutput(
+ pending: StructuredMessage[],
+ message: StructuredMessage,
+): boolean {
+ if (message.role !== 'assistant') return false
+ const index = pending.findIndex(candidate => outputReplayMatches(candidate, message))
+ if (index < 0) return false
+ pending.splice(index, 1)
+ return true
+}
+
+function partContents(message: StructuredMessage, type: string): readonly string[] {
+ return message.parts.flatMap(part => (
+ part.type === type && part.content !== undefined && part.content !== ''
+ ? [part.content]
+ : []
+ ))
+}
+
+function sameSequence(left: readonly string[], right: readonly string[]): boolean {
+ return left.length === right.length && left.every((value, index) => value === right[index])
+}
+
+function stableToolArguments(value: unknown): string | undefined {
+ if (value === undefined) return undefined
+ if (typeof value === 'string' && value.trim() === '') return undefined
+ if (typeof value !== 'string') return structuralIdentity(value)
+ const parsed = parsedJson(value)
+ return structuralIdentity(parsed)
+}
+
+function toolCallsMatch(output: StructuredPart, input: StructuredPart): boolean {
+ if (output.id !== undefined && input.id !== undefined) {
+ if (output.id !== input.id) return false
+ if (output.name !== undefined && input.name !== undefined && output.name !== input.name) return false
+ const outputArguments = stableToolArguments(output.arguments)
+ const inputArguments = stableToolArguments(input.arguments)
+ return outputArguments === undefined
+ || inputArguments === undefined
+ || outputArguments === inputArguments
+ }
+ if (output.name === undefined || input.name === undefined || output.name !== input.name) return false
+ const outputArguments = stableToolArguments(output.arguments)
+ const inputArguments = stableToolArguments(input.arguments)
+ return outputArguments !== undefined
+ && inputArguments !== undefined
+ && outputArguments === inputArguments
+}
+
+function replayToolCalls(message: StructuredMessage): readonly StructuredPart[] {
+ const ids = new Set<string>()
+ return message.parts.flatMap((part): StructuredPart[] => {
+ if (part.type !== 'tool_call') return []
+ if (part.id === undefined) return [part]
+ if (ids.has(part.id)) return []
+ ids.add(part.id)
+ return [part]
+ })
+}
+
+function outputReplayMatches(
+ output: StructuredMessage,
+ input: StructuredMessage,
+): boolean {
+ if (output.role !== 'assistant' || input.role !== 'assistant') return false
+ const outputText = partContents(output, 'text')
+ const inputText = partContents(input, 'text')
+ const hasText = outputText.length > 0 || inputText.length > 0
+ if (hasText && !sameSequence(outputText, inputText)) return false
+
+ const outputReasoning = partContents(output, 'reasoning')
+ const inputReasoning = partContents(input, 'reasoning')
+ if (
+ outputReasoning.length > 0
+ && inputReasoning.length > 0
+ && !sameSequence(outputReasoning, inputReasoning)
+ ) return false
+
+ const outputCalls = replayToolCalls(output)
+ const inputCalls = replayToolCalls(input)
+ if (outputCalls.length > 0 && inputCalls.length > 0) {
+ if (outputCalls.length !== inputCalls.length) return false
+ if (!outputCalls.every((part, index) => {
+ const inputPart = inputCalls[index]
+ return inputPart !== undefined && toolCallsMatch(part, inputPart)
+ })) return false
+ }
+ if (hasText) return true
+
+ if (outputCalls.length === 0 || inputCalls.length === 0) return false
+ return outputCalls.every((part, index) => (
+ part.id !== undefined && part.id === inputCalls[index]?.id
+ ))
+}
+
+function promptBehaviorIdentity(prompt: TrajectoryPromptSnapshot): string {
+ return structuralIdentity({ system: prompt.system, tools: prompt.tools })
+}
+
+function projectInferenceInputs(spans: readonly ProjectedSpan[]): {
+ inputsBySpanId: ReadonlyMap<string, InferenceInputProjection>
+ toolResultById: ReadonlyMap<string, ToolResultFact>
+ toolResultBySpanId: ReadonlyMap<string, ToolResultFact>
+} {
+ const inputsBySpanId = new Map<string, InferenceInputProjection>()
+ const previousInputsBySession = new Map<string, readonly IndexedMessage[]>()
+ const previousPromptBySession = new Map<string, string>()
+ const previousOutputsBySession = new Map<string, readonly StructuredMessage[]>()
+ const toolResults: ToolResultFact[] = []
+
+ for (const span of spans.filter(isInference).sort(compareInferenceBehavior)) {
+ const sessionKey = behaviorSessionKey(span)
+ const currentInputs = structuredMessages(span.attributes.inputMessages)
+ const previousInputs = previousInputsBySession.get(sessionKey) ?? []
+ const attachmentIndexes = provenanceAttachmentIndexes(span.attributes.inputMessageProvenance)
+ const attachmentIndexSet = new Set(currentInputs.flatMap((message, index): number[] => {
+ const attachment = attachmentIndexes === undefined
+ ? legacyRequestScopedAttachment(message)
+ : attachmentIndexes.has(index)
+ return attachment ? [index] : []
+ }))
+ const currentOrdinary = currentInputs.flatMap((message, inputIndex): IndexedMessage[] => (
+ attachmentIndexSet.has(inputIndex) ? [] : [{ inputIndex, message }]
+ ))
+ const insertedIndexes = lcsInsertedInputIndexes(previousInputs, currentOrdinary)
+ const replayableOutputs = [...(previousOutputsBySession.get(sessionKey) ?? [])]
+ const messages = currentInputs.flatMap((message, index): StructuredMessage[] => {
+ const attachment = attachmentIndexSet.has(index)
+ if (!insertedIndexes.has(index) && !attachment) return []
+ for (const part of message.parts) {
+ if (part.type !== 'tool_call_response') continue
+ toolResults.push({
+ traceId: span.traceId,
+ response: part.response,
+ ...(part.id === undefined ? {} : { id: part.id }),
+ ...(part.name === undefined ? {} : { name: part.name }),
+ })
+ }
+ if (!attachment && consumePriorOutput(replayableOutputs, message)) return []
+ const parts = message.parts.filter(part => (
+ part.type !== 'tool_call' && part.type !== 'tool_call_response'
+ ))
+ if (parts.length === 0) return []
+ return [{
+ ...message,
+ parts,
+ inputIndex: index,
+ ...(attachment ? { inputKind: 'prompt_attachment' as const } : {}),
+ }]
+ })
+ const prompt = promptSnapshot(span.attributes)
+ const promptIdentity = prompt === undefined ? undefined : promptBehaviorIdentity(prompt)
+ const previousPrompt = previousPromptBySession.get(sessionKey)
+ inputsBySpanId.set(span.span.spanId, {
+ messages,
+ prompt: promptIdentity === undefined || promptIdentity === previousPrompt ? undefined : prompt,
+ })
+ if (promptIdentity !== undefined) previousPromptBySession.set(sessionKey, promptIdentity)
+ previousInputsBySession.set(sessionKey, currentOrdinary)
+ const outputs = structuredMessages(span.attributes.outputMessages)
+ previousOutputsBySession.set(sessionKey, outputs)
+ }
+
+ const toolResultById = new Map<string, ToolResultFact>()
+ const fallbackByTrace = new Map<string, ToolResultFact[]>()
+ for (const result of toolResults) {
+ if (result.id !== undefined) {
+ toolResultById.set(`${result.traceId}\u0000${result.id}`, result)
+ }
+ const facts = fallbackByTrace.get(result.traceId) ?? []
+ facts.push(result)
+ fallbackByTrace.set(result.traceId, facts)
+ }
+
+ const toolResultBySpanId = new Map<string, ToolResultFact>()
+ const consumedByTrace = new Map<string, Set<number>>()
+ for (const span of spans.filter(isTool)) {
+ if (span.attributes.toolCallId !== undefined) continue
+ const candidates = fallbackByTrace.get(span.traceId) ?? []
+ const consumed = consumedByTrace.get(span.traceId) ?? new Set<number>()
+ const name = span.attributes.toolName ?? span.span.name
+ let resultIndex = candidates.findIndex((candidate, index) => (
+ !consumed.has(index) && candidate.name !== undefined && candidate.name === name
+ ))
+ if (resultIndex < 0) resultIndex = candidates.findIndex((_, index) => !consumed.has(index))
+ const result = candidates[resultIndex]
+ if (result !== undefined) {
+ consumed.add(resultIndex)
+ toolResultBySpanId.set(span.span.spanId, result)
+ consumedByTrace.set(span.traceId, consumed)
+ }
+ }
+ return { inputsBySpanId, toolResultById, toolResultBySpanId }
+}
+
+function compactionCell(span: ProjectedSpan, inference: ProjectedSpan | undefined): TrajectoryCell {
+ const summary = span.attributes.compactionSummary
+ ?? (inference === undefined
+ ? undefined
+ : structuredMessages(inference.attributes.outputMessages).flatMap(message => message.parts)
+ .flatMap(part => part.type === 'compaction' && part.content !== undefined ? [part.content] : [])
+ .join('\n\n'))
+ ?? ''
+ const inputTokens = nonNegativeSafeInteger(span.attributes.compactionInputTokens)
+ const error = statusError(span)
+ return {
+ ...spanCellBase(span, 'compaction'),
+ kind: 'compacted',
+ text: summary === '' ? 'Context compaction' : summary,
+ outputDetail: summary,
+ ...(inputTokens === undefined ? {} : { input: inputTokens }),
+ ...(error === undefined ? {} : { isError: true, result: error }),
+ }
+}
+
+function requestFor(
+ span: ProjectedSpan,
+ purpose: 'assistant' | 'compaction',
+ rootAttributes: NormalizedTrajectoryAttributes | undefined,
+): TrajectoryRequest {
+ const requestNumber = span.requestNumber ?? 1
+ const step = positiveSafeInteger(span.attributes.stepNumber) ?? 1
+ const usageValue = usage(span.attributes)
+ const facts = recordedFacts(span.attributes, rootAttributes)
+ const base = {
+ recordId: requestRecordIdentity(span),
+ seq: span.sourceSequence,
+ group: purpose === 'compaction' ? 'Compaction' : `Step ${step}`,
+ number: requestNumber,
+ status: status(span),
+ startedAt: startedAt(span),
+ completedAt: span.endTimeUnixNano === undefined
+ ? null
+ : Number(span.endTimeUnixNano / NANOSECONDS_PER_MILLISECOND),
+ ...(statusError(span) === undefined ? {} : { error: statusError(span) }),
+ retry: nonNegativeSafeInteger(span.attributes.requestRetryCount),
+ maxRetries: nonNegativeSafeInteger(span.attributes.requestMaxRetries),
+ provider: span.attributes.providerName,
+ model: span.attributes.requestModel ?? span.attributes.responseModel,
+ requestConfig: requestConfig(span.attributes),
+ recordedFacts: facts,
+ usage: usageValue,
+ }
+ const defined = Object.fromEntries(Object.entries(base).filter(([, value]) => value !== undefined))
+ return purpose === 'compaction'
+ ? { ...defined, purpose, turn: null, step: 0 } as TrajectoryRequest
+ : { ...defined, purpose, turn: span.turn, step } as TrajectoryRequest
+}
+
+function assignTurns(spans: readonly Omit<ProjectedSpan, 'turn'>[]): ProjectedSpan[] {
+ const traceStarts = new Map<string, bigint>()
+ const explicitByTrace = new Map<string, number>()
+ for (const span of spans) {
+ const prior = traceStarts.get(span.traceId)
+ if (prior === undefined || span.startTimeUnixNano < prior) {
+ traceStarts.set(span.traceId, span.startTimeUnixNano)
+ }
+ if (span.explicitTurn !== undefined) explicitByTrace.set(span.traceId, span.explicitTurn)
+ }
+ let nextTurn = Math.max(0, ...explicitByTrace.values()) + 1
+ const turnByTrace = new Map(explicitByTrace)
+ for (const [traceId] of [...traceStarts].sort((left, right) =>
+ compareBigint(left[1], right[1]) || left[0].localeCompare(right[0]))) {
+ if (!turnByTrace.has(traceId)) turnByTrace.set(traceId, nextTurn++)
+ }
+ return spans.map(span => ({ ...span, turn: turnByTrace.get(span.traceId) ?? 1 }))
+}
+
+function normalize(
+ records: readonly OtlpExportTraceServiceRequest[],
+ options: TrajectoryProjectionOptions,
+): ProjectedSpan[] {
+ const spans = assignTurns(records.map((record): Omit<ProjectedSpan, 'turn'> => {
+ const span = soleSpan(record)
+ const attributes = normalizeTrajectoryAttributes(span.attributes)
+ const lifecycle = options.lifecycleByRecordId?.get(`${span.traceId}:${span.spanId}`)
+ ?? (span.endTimeUnixNano === undefined ? 'running' : 'completed')
+ return {
+ attributes,
+ request: record,
+ span,
+ traceId: span.traceId,
+ parentSpanId: span.parentSpanId,
+ startTimeUnixNano: BigInt(span.startTimeUnixNano),
+ endTimeUnixNano: lifecycle === 'running' || span.endTimeUnixNano === undefined
+ ? undefined
+ : BigInt(span.endTimeUnixNano),
+ explicitTurn: positiveSafeInteger(attributes.turnNumber),
+ sourceSequence: nonNegativeSafeInteger(attributes.sourceSequence),
+ requestNumber: positiveSafeInteger(attributes.requestNumber),
+ streamEvents: normalizeTrajectoryStreamEvents(span.events),
+ lifecycle,
+ }
+ })).sort(compareSpans)
+ const currentByTrace = new Map<string, number>()
+ return spans.map((span) => {
+ if (!isInference(span)) return span
+ const current = currentByTrace.get(span.traceId) ?? 0
+ const requestNumber = span.requestNumber ?? current + 1
+ currentByTrace.set(span.traceId, Math.max(current, requestNumber))
+ return { ...span, requestNumber }
+ })
+}
+
+function group(turn: MutableTurn, step: number): MutableGroup {
+ const existing = turn.groups.get(step)
+ if (existing !== undefined) return existing
+ const created: MutableGroup = { title: `Step ${step}`, cells: [] }
+ turn.groups.set(step, created)
+ return created
+}
+
+function finalizeRequests(requests: readonly TrajectoryRequest[]): TrajectoryRequest[] {
+ let cumulative: TrajectoryUsage = {}
+ return [...requests]
+ .sort((left, right) => (left.startedAt ?? 0) - (right.startedAt ?? 0) || left.number - right.number)
+ .map((request) => {
+ cumulative = addUsage(cumulative, request.usage ?? {})
+ return { ...request, cumulativeUsage: cumulative }
+ })
+}
+
+/** Fold one bounded OTLP record window into the trajectory UI's closed read model. */
+export function projectOtelTrajectory(
+ records: readonly OtlpExportTraceServiceRequest[],
+ options: TrajectoryProjectionOptions = {},
+): TrajectorySnapshot {
+ const spans = normalize(records, options)
+ const mutableTurns = new Map<number, MutableTurn>()
+ const requests: TrajectoryRequest[] = []
+ const inputProjection = projectInferenceInputs(spans)
+ const toolSpanIds = new Set(spans.filter(isTool).map(span => span.span.spanId))
+ const authoritativeToolCallIds = new Set(spans
+ .filter(span => isTool(span) && span.attributes.toolAuthoritative === true)
+ .flatMap(span => span.attributes.toolCallId === undefined
+ ? []
+ : [`${span.traceId}\u0000${span.attributes.toolCallId}`]))
+ const rootByTrace = new Map<string, ProjectedSpan>()
+ for (const span of spans) {
+ if (span.attributes.traceRoot !== true && span.parentSpanId !== undefined) continue
+ const existing = rootByTrace.get(span.traceId)
+ if (
+ existing === undefined
+ || (span.attributes.traceRoot === true && existing.attributes.traceRoot !== true)
+ || (
+ span.attributes.traceRoot === existing.attributes.traceRoot
+ && span.startTimeUnixNano < existing.startTimeUnixNano
+ )
+ ) rootByTrace.set(span.traceId, span)
+ }
+ const compactionInferences = new Map<number, ProjectedSpan>()
+ const compactions = new Map<number, ProjectedSpan>()
+ const toolSchemaByTurnAndName = new Map<string, string>()
+
+ for (const span of spans.filter(isInference)) {
+ for (const schema of toolSchemas(span.attributes.toolDefinitions)) {
+ toolSchemaByTurnAndName.set(`${span.turn}\u0000${schema.name}`, JSON.stringify(schema))
+ }
+ }
+
+ for (const span of spans) {
+ const turn = mutableTurns.get(span.turn) ?? { turn: span.turn, groups: new Map() }
+ mutableTurns.set(span.turn, turn)
+ const step = positiveSafeInteger(span.attributes.stepNumber) ?? 1
+ if (isInference(span)) {
+ const purpose = span.attributes.requestPurpose
+ if (purpose === 'compaction') {
+ compactionInferences.set(span.turn, span)
+ requests.push(requestFor(span, 'compaction', rootByTrace.get(span.traceId)?.attributes))
+ continue
+ }
+ const target = group(turn, step)
+ const inputs = inputProjection.inputsBySpanId.get(span.span.spanId)
+ ?? { messages: [], prompt: undefined }
+ target.cells.push(...inputCells(span, inputs), assistantCell(span))
+ requests.push(requestFor(span, 'assistant', rootByTrace.get(span.traceId)?.attributes))
+ continue
+ }
+ if (isTool(span)) {
+ if (
+ span.attributes.toolAuthoritative !== true
+ && span.attributes.toolCallId !== undefined
+ && authoritativeToolCallIds.has(`${span.traceId}\u0000${span.attributes.toolCallId}`)
+ ) continue
+ const name = span.attributes.toolName ?? span.span.name
+ const correlatedResult = span.attributes.toolCallId === undefined
+ ? inputProjection.toolResultBySpanId.get(span.span.spanId)
+ : inputProjection.toolResultById.get(`${span.traceId}\u0000${span.attributes.toolCallId}`)
+ group(turn, step).cells.push(toolCell(
+ span,
+ toolSpanIds,
+ toolSchemaByTurnAndName.get(`${span.turn}\u0000${name}`),
+ correlatedResult,
+ ))
+ continue
+ }
+ if (isCompaction(span)) compactions.set(span.turn, span)
+ }
+
+ const turns: TrajectoryTurnModel[] = []
+ for (const turn of [...mutableTurns.values()].sort((left, right) => left.turn - right.turn)) {
+ const groups = [...turn.groups.entries()]
+ .sort((left, right) => left[0] - right[0])
+ .map(([, value]) => ({
+ ...value,
+ cells: [...value.cells].sort((left, right) => {
+ const leftStart = left.startedAt ?? 0
+ const rightStart = right.startedAt ?? 0
+ const kindOrder = (cell: TrajectoryCell): number => {
+ if (cell.kind === 'system') return 0
+ if (cell.kind === 'user' || cell.kind === 'context') return 1
+ if (cell.kind === 'message') return 2
+ if (cell.kind === 'tool') return 3
+ return 4
+ }
+ return leftStart - rightStart || kindOrder(left) - kindOrder(right)
+ }),
+ }))
+ .filter(value => value.cells.length > 0)
+ if (groups.length > 0) turns.push({ turn: turn.turn, groups })
+ const compaction = compactions.get(turn.turn)
+ if (compaction !== undefined) {
+ turns.push({
+ turn: null,
+ groups: [{
+ title: 'Compaction',
+ cells: [compactionCell(compaction, compactionInferences.get(turn.turn))],
+ }],
+ })
+ }
+ }
+
+ return {
+ turns,
+ requests: finalizeRequests(requests),
+ }
+}
+
+/** Reusable projector boundary independent from any concrete transport. */
+export interface TrajectoryProjector {
+ project(records: readonly OtlpExportTraceServiceRequest[]): TrajectorySnapshot
+}
+
+/** Stateless projector suitable for an HTTP polling or incremental trace store. */
+export class OtelGenAiTrajectoryProjector implements TrajectoryProjector {
+ /** Project the current bounded record window. */
+ project(records: readonly OtlpExportTraceServiceRequest[]): TrajectorySnapshot {
+ return projectOtelTrajectory(records)
+ }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/semconv/attributes.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/semconv/attributes.ts
new file mode 100644
index 0000000000..b3841a110e
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/semconv/attributes.ts
@@ -0,0 +1,146 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Exact OTLP attribute readers and builders for semantic validation. */
+
+import type { OtlpAnyValue, OtlpKeyValue } from '../shared/otlp.ts'
+
+/** An attribute lookup that preserves the original OTLP AnyValue arm. */
+export type OtlpAttributeMap = ReadonlyMap<string, OtlpAnyValue>
+
+/** Convert already duplicate-checked attributes into an exact-value map. */
+export function exactAttributeMap(attributes: readonly OtlpKeyValue[] | undefined): OtlpAttributeMap {
+ return new Map((attributes ?? []).map(attribute => [attribute.key, attribute.value]))
+}
+
+/** Read an exact string attribute without coercion. */
+export function readStringAttribute(attributes: OtlpAttributeMap, key: string): string | undefined {
+ const value = attributes.get(key)
+ return value !== undefined && 'stringValue' in value ? value.stringValue : undefined
+}
+
+/** Read an exact boolean attribute without coercion. */
+export function readBooleanAttribute(attributes: OtlpAttributeMap, key: string): boolean | undefined {
+ const value = attributes.get(key)
+ return value !== undefined && 'boolValue' in value ? value.boolValue : undefined
+}
+
+/** Read an OTLP int64 attribute as a lossless bigint. */
+export function readInt64Attribute(attributes: OtlpAttributeMap, key: string): bigint | undefined {
+ const value = attributes.get(key)
+ if (value === undefined || !('intValue' in value)) return undefined
+ try {
+ return BigInt(value.intValue)
+ } catch {
+ return undefined
+ }
+}
+
+/** Read an OTLP integer only when it can be represented exactly by JavaScript. */
+export function readSafeIntegerAttribute(attributes: OtlpAttributeMap, key: string): number | undefined {
+ const value = readInt64Attribute(attributes, key)
+ if (value === undefined || value < BigInt(Number.MIN_SAFE_INTEGER) || value > BigInt(Number.MAX_SAFE_INTEGER)) return undefined
+ return Number(value)
+}
+
+/** Read a finite numeric attribute from its double or int64 arm. */
+export function readNumberAttribute(attributes: OtlpAttributeMap, key: string): number | undefined {
+ const value = attributes.get(key)
+ if (value === undefined) return undefined
+ if ('doubleValue' in value) return value.doubleValue
+ if (!('intValue' in value)) return undefined
+ let integer: bigint
+ try {
+ integer = BigInt(value.intValue)
+ } catch {
+ return undefined
+ }
+ if (integer < BigInt(Number.MIN_SAFE_INTEGER) || integer > BigInt(Number.MAX_SAFE_INTEGER)) return undefined
+ return Number(integer)
+}
+
+/** Read a homogeneous OTLP string-array attribute. */
+export function readStringArrayAttribute(attributes: OtlpAttributeMap, key: string): readonly string[] | undefined {
+ const value = attributes.get(key)
+ if (value === undefined || !('arrayValue' in value)) return undefined
+ const result: string[] = []
+ for (const item of value.arrayValue.values ?? []) {
+ if (!('stringValue' in item)) return undefined
+ result.push(item.stringValue)
+ }
+ return result
+}
+
+/** Convert an OTLP AnyValue into a structured JSON-compatible value without numeric coercion. */
+export function structuredOtlpValue(value: OtlpAnyValue): unknown {
+ if ('stringValue' in value) return value.stringValue
+ if ('boolValue' in value) return value.boolValue
+ if ('intValue' in value) return value.intValue
+ if ('doubleValue' in value) return value.doubleValue
+ if ('bytesValue' in value) return value.bytesValue
+ if ('arrayValue' in value) return (value.arrayValue.values ?? []).map(structuredOtlpValue)
+ return Object.fromEntries((value.kvlistValue.values ?? []).map(item => [item.key, structuredOtlpValue(item.value)]))
+}
+
+/** Read a structured GenAI attribute, accepting the specified JSON-string fallback on spans. */
+export function readStructuredAttribute(attributes: OtlpAttributeMap, key: string): unknown {
+ const value = attributes.get(key)
+ if (value === undefined) return undefined
+ if ('stringValue' in value) {
+ try {
+ return JSON.parse(value.stringValue) as unknown
+ } catch {
+ return undefined
+ }
+ }
+ return structuredOtlpValue(value)
+}
+
+/** Build a string OTLP AnyValue. */
+export function stringValue(value: string): OtlpAnyValue {
+ return { stringValue: value }
+}
+
+/** Build a boolean OTLP AnyValue. */
+export function boolValue(value: boolean): OtlpAnyValue {
+ return { boolValue: value }
+}
+
+/** Build an int64 OTLP AnyValue from an exact integer. */
+export function intValue(value: bigint | number): OtlpAnyValue {
+ return { intValue: String(value) }
+}
+
+/** Build a double OTLP AnyValue. */
+export function doubleValue(value: number): OtlpAnyValue {
+ return { doubleValue: value }
+}
+
+/** Build an OTLP array AnyValue. */
+export function arrayValue(values: readonly OtlpAnyValue[]): OtlpAnyValue {
+ return { arrayValue: { values: [...values] } }
+}
+
+/** Build an OTLP key/value-list AnyValue. */
+export function kvlistValue(values: readonly OtlpKeyValue[]): OtlpAnyValue {
+ return { kvlistValue: { values: [...values] } }
+}
+
+/** Build one OTLP key/value attribute. */
+export function attribute(key: string, value: OtlpAnyValue): OtlpKeyValue {
+ return { key, value }
+}
+
+/** Encode a JSON-compatible structured value as OTLP AnyValue. */
+export function structuredValue(value: unknown): OtlpAnyValue {
+ if (typeof value === 'string') return stringValue(value)
+ if (typeof value === 'boolean') return boolValue(value)
+ if (typeof value === 'number') {
+ if (!Number.isFinite(value)) throw new TypeError('structured OTLP numbers must be finite')
+ return Number.isInteger(value) ? intValue(value) : doubleValue(value)
+ }
+ if (Array.isArray(value)) return arrayValue(value.map(structuredValue))
+ if (typeof value === 'object' && value !== null) {
+ return kvlistValue(Object.entries(value).map(([key, item]) => attribute(key, structuredValue(item))))
+ }
+ throw new TypeError('OTLP AnyValue cannot represent null or undefined inside this profile')
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/semconv/constants.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/semconv/constants.ts
new file mode 100644
index 0000000000..2b6b5f89ff
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/semconv/constants.ts
@@ -0,0 +1,200 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Version pins and semantic names accepted by the observability profile. */
+
+/** OpenTelemetry specification revision used to define the trace model. */
+export const OTEL_SPEC_VERSION = '1.60.0' as const
+
+/** OTLP protocol revision used to define the protobuf JSON mapping. */
+export const OTLP_PROTO_VERSION = '1.11.0' as const
+
+/** Stable core semantic-conventions revision used by resource schema URLs. */
+export const OTEL_SEMCONV_VERSION = '1.44.0' as const
+
+/** Exact development revision of the standalone GenAI semantic conventions. */
+export const GEN_AI_SEMCONV_REVISION = 'a685613a207a580163353b8e48a7ad88967e7b42' as const
+
+/** Current pre-release DSH extension schema accepted by the viewer. */
+export const DSH_SCHEMA_VERSION = '1' as const
+
+/** Standard OTel and GenAI attribute keys used by the profile. */
+export const STANDARD_ATTRIBUTES = {
+ serviceName: 'service.name',
+ sessionId: 'session.id',
+ errorType: 'error.type',
+ exceptionType: 'exception.type',
+ exceptionMessage: 'exception.message',
+ exceptionStacktrace: 'exception.stacktrace',
+ operationName: 'gen_ai.operation.name',
+ providerName: 'gen_ai.provider.name',
+ conversationId: 'gen_ai.conversation.id',
+ conversationCompacted: 'gen_ai.conversation.compacted',
+ requestModel: 'gen_ai.request.model',
+ requestMaxTokens: 'gen_ai.request.max_tokens',
+ requestTemperature: 'gen_ai.request.temperature',
+ requestTopP: 'gen_ai.request.top_p',
+ requestStopSequences: 'gen_ai.request.stop_sequences',
+ requestStream: 'gen_ai.request.stream',
+ requestReasoningLevel: 'gen_ai.request.reasoning.level',
+ responseId: 'gen_ai.response.id',
+ responseModel: 'gen_ai.response.model',
+ responseFinishReasons: 'gen_ai.response.finish_reasons',
+ responseTimeToFirstChunk: 'gen_ai.response.time_to_first_chunk',
+ usageInputTokens: 'gen_ai.usage.input_tokens',
+ usageOutputTokens: 'gen_ai.usage.output_tokens',
+ usageReasoningTokens: 'gen_ai.usage.reasoning.output_tokens',
+ usageCacheReadTokens: 'gen_ai.usage.cache_read.input_tokens',
+ usageCacheCreationTokens: 'gen_ai.usage.cache_creation.input_tokens',
+ agentId: 'gen_ai.agent.id',
+ agentName: 'gen_ai.agent.name',
+ agentVersion: 'gen_ai.agent.version',
+ agentDescription: 'gen_ai.agent.description',
+ toolName: 'gen_ai.tool.name',
+ toolCallId: 'gen_ai.tool.call.id',
+ toolType: 'gen_ai.tool.type',
+ toolDescription: 'gen_ai.tool.description',
+ toolCallArguments: 'gen_ai.tool.call.arguments',
+ toolCallResult: 'gen_ai.tool.call.result',
+ systemInstructions: 'gen_ai.system_instructions',
+ inputMessages: 'gen_ai.input.messages',
+ outputMessages: 'gen_ai.output.messages',
+ toolDefinitions: 'gen_ai.tool.definitions',
+} as const
+
+/** OpenJiuwen trajectory extensions and compatibility attributes. */
+export const OPENJIUWEN_ATTRIBUTES = {
+ traceRoot: 'openjiuwen.trace.root',
+ traceSchemaVersion: 'openjiuwen.trace.schema_version',
+ traceComplete: 'openjiuwen.trace.complete',
+ traceForcedClose: 'openjiuwen.trace.forced_close',
+ spanForcedClose: 'openjiuwen.span.forced_close',
+ spanForcedCloseReason: 'openjiuwen.span.forced_close.reason',
+ sessionId: 'openjiuwen.session.id',
+ requestId: 'openjiuwen.request.id',
+ runId: 'openjiuwen.run.id',
+ turnId: 'openjiuwen.turn.id',
+ turnNumber: 'openjiuwen.turn.number',
+ stepId: 'openjiuwen.step.id',
+ stepNumber: 'openjiuwen.step.number',
+ inferenceId: 'openjiuwen.inference.id',
+ trajectoryKind: 'openjiuwen.trajectory.record.kind',
+ requestPurpose: 'openjiuwen.request.purpose',
+ requestNumber: 'openjiuwen.request.number',
+ requestRetryCount: 'openjiuwen.request.retry_count',
+ requestMaxRetries: 'openjiuwen.request.max_retries',
+ agentMode: 'openjiuwen.agent.mode',
+ inputCost: 'openjiuwen.gen_ai.usage.input_cost',
+ outputCost: 'openjiuwen.gen_ai.usage.output_cost',
+ totalCost: 'openjiuwen.gen_ai.usage.total_cost',
+ totalLatencyMs: 'openjiuwen.gen_ai.response.total_latency_ms',
+ timePerOutputTokenMs: 'openjiuwen.gen_ai.response.tpot_ms',
+ promptTokenIds: 'openjiuwen.gen_ai.response.prompt_token_ids',
+ completionTokenIds: 'openjiuwen.gen_ai.response.completion_token_ids',
+ logprobs: 'openjiuwen.gen_ai.response.logprobs',
+ parserResult: 'openjiuwen.gen_ai.response.parser_result',
+ providerMetadata: 'openjiuwen.gen_ai.response.provider_metadata',
+ inputMessageProvenance: 'openjiuwen.gen_ai.input.message_provenance',
+ toolResourceId: 'openjiuwen.tool.resource_id',
+ toolType: 'openjiuwen.tool.type',
+ toolAuthoritative: 'openjiuwen.tool.authoritative',
+ eventSequence: 'openjiuwen.event.sequence',
+ streamKind: 'openjiuwen.stream.kind',
+ streamText: 'openjiuwen.stream.text',
+ streamToolCallId: 'openjiuwen.stream.tool_call.id',
+ streamToolName: 'openjiuwen.stream.tool_call.name',
+ streamArgumentsDelta: 'openjiuwen.stream.tool_call.arguments_delta',
+} as const
+
+/** OpenJiuwen event names added alongside existing DSH and llm.chunk events. */
+export const OPENJIUWEN_EVENTS = {
+ streamChunk: 'openjiuwen.stream.chunk',
+ retryScheduled: 'openjiuwen.retry.scheduled',
+ retryStarted: 'openjiuwen.retry.started',
+ legacyStreamChunk: 'llm.chunk',
+} as const
+
+/** DSH-specific attribute keys whose meaning is defined by the data-format reference. */
+export const DSH_ATTRIBUTES = {
+ schemaVersion: 'dsh.schema.version',
+ genAiSemconvRevision: 'dsh.semconv.gen_ai.revision',
+ sessionParentId: 'dsh.session.parent_id',
+ sessionSourceSequence: 'dsh.session.source_sequence',
+ turnNumber: 'dsh.turn.number',
+ turnEndReason: 'dsh.turn.end_reason',
+ stepNumber: 'dsh.step.number',
+ trajectoryKind: 'dsh.trajectory.record.kind',
+ requestPurpose: 'dsh.request.purpose',
+ requestNumber: 'dsh.request.number',
+ requestRetryCount: 'dsh.request.retry_count',
+ requestMaxRetries: 'dsh.request.max_retries',
+ messageSourceKind: 'dsh.message.source.kind',
+ messageSourcePlugin: 'dsh.message.source.plugin',
+ eventSequence: 'dsh.event.sequence',
+ retryAttempt: 'dsh.retry.attempt',
+ retryMaximumAttempts: 'dsh.retry.maximum_attempts',
+ retryDelayMilliseconds: 'dsh.retry.delay_ms',
+ streamSequence: 'dsh.stream.sequence',
+ streamKind: 'dsh.stream.kind',
+ streamBlockIndex: 'dsh.stream.block.index',
+ streamText: 'dsh.stream.text',
+ streamArgumentsDelta: 'dsh.stream.arguments_delta',
+ streamToolCallId: 'dsh.stream.tool_call.id',
+ streamToolName: 'dsh.stream.tool.name',
+ compactionId: 'dsh.compaction.id',
+ compactionShadowedSequenceStart: 'dsh.compaction.shadowed_sequence.start',
+ compactionShadowedSequenceEnd: 'dsh.compaction.shadowed_sequence.end',
+ compactionInputTokens: 'dsh.compaction.input_tokens',
+ compactionSourceCommand: 'dsh.compaction.source_command',
+ compactionSummary: 'dsh.compaction.summary',
+} as const
+
+/** DSH-specific span-event names used for replay and lifecycle detail. */
+export const DSH_EVENTS = {
+ streamChunk: 'dsh.stream.chunk',
+ retryScheduled: 'dsh.retry.scheduled',
+ retryStarted: 'dsh.retry.started',
+} as const
+
+/** Well-known GenAI operation names used by the projector. */
+export const GEN_AI_OPERATIONS = {
+ chat: 'chat',
+ generateContent: 'generate_content',
+ textCompletion: 'text_completion',
+ invokeAgent: 'invoke_agent',
+ executeTool: 'execute_tool',
+ invokeWorkflow: 'invoke_workflow',
+ plan: 'plan',
+} as const
+
+/** Closed DSH record-kind hints understood by the trajectory projector. */
+export const DSH_TRAJECTORY_KINDS = [
+ 'turn',
+ 'step',
+ 'inference',
+ 'reasoning',
+ 'tool',
+ 'compaction',
+] as const
+
+/** Replayable DSH stream-chunk discriminants. */
+export const DSH_STREAM_KINDS = [
+ 'block-start',
+ 'text-delta',
+ 'reasoning-delta',
+ 'tool-call-delta',
+ 'block-end',
+ 'usage',
+] as const
+
+/** DSH turn outcomes rendered independently from OTel status. */
+export const DSH_TURN_END_REASONS = [
+ 'completed',
+ 'max-tokens',
+ 'error',
+ 'aborted',
+ 'blocked',
+ 'interrupted',
+] as const
+
+/** Request purposes that select the trajectory request inspector. */
+export const DSH_REQUEST_PURPOSES = ['assistant', 'compaction'] as const
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/shared/otlp.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/shared/otlp.ts
new file mode 100644
index 0000000000..4e405ad3f3
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/shared/otlp.ts
@@ -0,0 +1,142 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** OTLP/JSON trace types and normalized accessors used on both sides of the transport. */
+
+export type OtlpAnyValue =
+ | { stringValue: string }
+ | { boolValue: boolean }
+ | { intValue: string }
+ | { doubleValue: number }
+ | { bytesValue: string }
+ | { arrayValue: { values?: OtlpAnyValue[] } }
+ | { kvlistValue: { values?: OtlpKeyValue[] } }
+
+export interface OtlpKeyValue {
+ key: string
+ value: OtlpAnyValue
+}
+
+export interface OtlpResource {
+ attributes?: OtlpKeyValue[]
+ droppedAttributesCount?: number
+}
+
+export interface OtlpInstrumentationScope {
+ name?: string
+ version?: string
+ attributes?: OtlpKeyValue[]
+ droppedAttributesCount?: number
+}
+
+export interface OtlpSpanEvent {
+ timeUnixNano: string
+ name: string
+ attributes?: OtlpKeyValue[]
+ droppedAttributesCount?: number
+}
+
+export interface OtlpSpanLink {
+ traceId: string
+ spanId: string
+ traceState?: string
+ attributes?: OtlpKeyValue[]
+ droppedAttributesCount?: number
+ flags?: number
+}
+
+export interface OtlpStatus {
+ message?: string
+ code?: number
+}
+
+export interface OtlpSpan {
+ traceId: string
+ spanId: string
+ traceState?: string
+ parentSpanId?: string
+ flags?: number
+ name: string
+ kind?: number
+ startTimeUnixNano: string
+ /** Absent on an additive provisional snapshot; required on authoritative OTLP final records. */
+ endTimeUnixNano?: string
+ attributes?: OtlpKeyValue[]
+ droppedAttributesCount?: number
+ events?: OtlpSpanEvent[]
+ droppedEventsCount?: number
+ links?: OtlpSpanLink[]
+ droppedLinksCount?: number
+ status?: OtlpStatus
+}
+
+export interface OtlpScopeSpans {
+ scope?: OtlpInstrumentationScope
+ spans?: OtlpSpan[]
+ schemaUrl?: string
+}
+
+export interface OtlpResourceSpans {
+ resource?: OtlpResource
+ scopeSpans?: OtlpScopeSpans[]
+ schemaUrl?: string
+}
+
+/** One physical observability JSONL record. */
+export interface OtlpExportTraceServiceRequest {
+ resourceSpans: OtlpResourceSpans[]
+}
+
+/** One-span profile extracted from an accepted JSONL line. */
+export interface NormalizedTraceRecord {
+ request: OtlpExportTraceServiceRequest
+ resourceSpans: OtlpResourceSpans
+ scopeSpans: OtlpScopeSpans
+ span: OtlpSpan
+ traceId: string
+ spanId: string
+ parentSpanId: string | null
+ startTimeUnixNano: bigint
+ endTimeUnixNano: bigint
+}
+
+/** Convert an OTLP AnyValue into its JSON-compatible value. */
+export function otlpValue(value: OtlpAnyValue): unknown {
+ if ('stringValue' in value) return value.stringValue
+ if ('boolValue' in value) return value.boolValue
+ if ('intValue' in value) return value.intValue
+ if ('doubleValue' in value) return value.doubleValue
+ if ('bytesValue' in value) return value.bytesValue
+ if ('arrayValue' in value) return (value.arrayValue.values ?? []).map(otlpValue)
+ if ('kvlistValue' in value) return Object.fromEntries(
+ (value.kvlistValue.values ?? []).map(item => [item.key, otlpValue(item.value)]),
+ )
+ return undefined
+}
+
+/** Build a last-value-wins attribute map from OTLP key/value entries. */
+export function attributeMap(attributes: readonly OtlpKeyValue[] | undefined): ReadonlyMap<string, unknown> {
+ const result = new Map<string, unknown>()
+ for (const attribute of attributes ?? []) result.set(attribute.key, otlpValue(attribute.value))
+ return result
+}
+
+/** Read a string attribute without coercing another OTLP value type. */
+export function stringAttribute(
+ attributes: readonly OtlpKeyValue[] | undefined,
+ key: string,
+): string | undefined {
+ const value = attributeMap(attributes).get(key)
+ return typeof value === 'string' ? value : undefined
+}
+
+/** Read a finite numeric attribute, including the OTLP int64 decimal-string representation. */
+export function numberAttribute(
+ attributes: readonly OtlpKeyValue[] | undefined,
+ key: string,
+): number | undefined {
+ const value = attributeMap(attributes).get(key)
+ if (typeof value === 'number' && Number.isFinite(value)) return value
+ if (typeof value !== 'string' || value.trim() === '') return undefined
+ const parsed = Number(value)
+ return Number.isFinite(parsed) ? parsed : undefined
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/PROVENANCE.md b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/PROVENANCE.md
new file mode 100644
index 0000000000..47f83fdda0
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/PROVENANCE.md
@@ -0,0 +1,5 @@
+# Theme source provenance
+
+English | [中文](PROVENANCE.zh.md)
+
+The five CSS files in this directory originate from `packages/client/ui-theme/src/styles/{base,design-platform,scrollbar,gradient-shadow-text,shiki}.css` at DeepSeek Harness commit `99f6f02fecdb7dff40c3fbc9470f5907c29f74ca`. They are used under the MIT license. This copy replaces global `:root`/`body`/scrollbar selectors with `.jiuwenTrajectoryTheme` and `.jiuwenTrajectoryPortal`, and adds the trajectory-only tokens needed by migrated primitives. The original DSH theme files remain unchanged.
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/PROVENANCE.zh.md b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/PROVENANCE.zh.md
new file mode 100644
index 0000000000..bcec856682
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/PROVENANCE.zh.md
@@ -0,0 +1,5 @@
+# 主题来源
+
+[English](PROVENANCE.md) | 中文
+
+本目录中的五个 CSS 文件来源于 DeepSeek Harness commit `99f6f02fecdb7dff40c3fbc9470f5907c29f74ca` 的 `packages/client/ui-theme/src/styles/{base,design-platform,scrollbar,gradient-shadow-text,shiki}.css`,并依据 MIT 许可证使用。本副本把全局 `:root`、`body` 和 scrollbar selector 改为 `.jiuwenTrajectoryTheme` / `.jiuwenTrajectoryPortal` 作用域,并增加迁入基础组件所需的轨迹局部 token。原始 DSH 主题文件保持不变。
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/base.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/base.css
new file mode 100644
index 0000000000..87bc8ab9f1
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/base.css
@@ -0,0 +1,18 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+/* Base variables referenced by the token sheets and component CSS but defined
+ * upstream (deepsuite theme/global.css) — supplied here so the composite
+ * --dsw-font-* variables resolve and motion rides the upstream curve. Code
+ * font stack deliberately omits a bare `monospace` tail (Windows CJK falls
+ * back to SimSun otherwise). */
+.jiuwenTrajectoryTheme,
+.jiuwenTrajectoryPortal {
+ --dsw-font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC',
+ 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ --ds-font-family-code: 'SF Mono', 'JetBrains Mono', 'Fira Code', Consolas,
+ 'Liberation Mono', Menlo, Courier, 'PingFang SC', 'Microsoft YaHei';
+ --ds-ease-in-out: cubic-bezier(0.4, 0, 0.2, 1);
+ --ds-transition-duration: 0.2s;
+ --ds-transition-duration-fast: 0.1s;
+ --ds-transition-duration-slow: 0.3s;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/context.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/context.tsx
new file mode 100644
index 0000000000..050f1ccefc
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/context.tsx
@@ -0,0 +1,28 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+import { createContext, type ReactNode, useContext } from 'react'
+
+/** Theme variants retained by the migrated trajectory presentation layer. */
+export type TrajectoryColorMode = 'light' | 'dark'
+
+const TrajectoryColorModeContext = createContext<TrajectoryColorMode>('light')
+
+/** Keep theme metadata available to content rendered through a React portal. */
+export function TrajectoryThemeProvider({
+ children,
+ colorMode,
+}: {
+ children: ReactNode
+ colorMode: TrajectoryColorMode
+}) {
+ return (
+ <TrajectoryColorModeContext.Provider value={colorMode}>
+ {children}
+ </TrajectoryColorModeContext.Provider>
+ )
+}
+
+/** Read the trajectory-local color mode without coupling to the host theme store. */
+export function useTrajectoryColorMode(): TrajectoryColorMode {
+ return useContext(TrajectoryColorModeContext)
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/design-platform.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/design-platform.css
new file mode 100644
index 0000000000..52229011f6
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/design-platform.css
@@ -0,0 +1,344 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+/* Figma font-weight 510 (an SF Pro variable-font weight) always renders as
+ font-weight: 500 in this UI — non-variable webfonts snap intermediate
+ weights unpredictably across platforms. */
+.jiuwenTrajectoryTheme,
+.jiuwenTrajectoryPortal {
+ --dsw-static-amber-100: rgb(254, 245, 231);
+ --dsw-static-amber-400: rgb(247, 173, 49);
+ --dsw-static-amber-500: rgb(245, 158, 11);
+ --dsw-static-amber-600: rgb(221, 134, 41);
+ --dsw-static-amber-900: rgb(39, 36, 31);
+ --dsw-static-blue-100: rgb(219, 234, 254);
+ --dsw-static-blue-300: rgb(147, 197, 253);
+ --dsw-static-blue-400: rgb(96, 165, 250);
+ --dsw-static-blue-450: rgb(77, 147, 248);
+ --dsw-static-blue-500: rgb(59, 130, 246);
+ --dsw-static-blue-50: rgb(239, 246, 255);
+ --dsw-static-blue-50p: rgb(234, 243, 255);
+ --dsw-static-blue-600: rgb(37, 99, 235);
+ --dsw-static-blue-75: rgb(229, 240, 255);
+ --dsw-static-blue-800: rgb(30, 64, 175);
+ --dsw-static-blue-900: rgb(14, 48, 116);
+ --dsw-static-blue-950: rgb(23, 37, 84);
+ --dsw-static-deepseek-100: rgb(228, 237, 253);
+ --dsw-static-deepseek-200: rgb(211, 226, 255);
+ --dsw-static-deepseek-300: rgb(183, 200, 254);
+ --dsw-static-deepseek-400: rgb(103, 158, 254);
+ --dsw-static-deepseek-450: rgb(86, 134, 254);
+ --dsw-static-deepseek-500: rgb(65, 118, 230);
+ --dsw-static-deepseek-50: rgb(237, 243, 254);
+ --dsw-static-deepseek-600: rgb(72, 104, 178);
+ --dsw-static-deepseek-700-delete: rgb(47, 76, 143);
+ --dsw-static-deepseek-800: rgb(52, 65, 91);
+ --dsw-static-deepseek-900: rgb(40, 49, 66);
+ --dsw-static-green-100: rgb(230, 250, 237);
+ --dsw-static-green-400: rgb(78, 209, 126);
+ --dsw-static-green-500: rgb(34, 197, 94);
+ --dsw-static-green-900: rgb(35, 60, 44);
+ --dsw-static-neutral-00: rgb(255, 255, 255);
+ --dsw-static-neutral-1000: rgb(0, 0, 0);
+ --dsw-static-neutral-100: rgb(245, 245, 245);
+ --dsw-static-neutral-150: rgb(237, 237, 237);
+ --dsw-static-neutral-200: rgb(229, 229, 229);
+ --dsw-static-neutral-250: rgb(220, 220, 220);
+ --dsw-static-neutral-300: rgb(212, 212, 212);
+ --dsw-static-neutral-400: rgb(162, 164, 166);
+ --dsw-static-neutral-500: rgb(127, 130, 135);
+ --dsw-static-neutral-50: rgb(250, 250, 250);
+ --dsw-static-neutral-550: rgb(101, 103, 107);
+ --dsw-static-neutral-600: rgb(84, 85, 87);
+ --dsw-static-neutral-700: rgb(60, 60, 61);
+ --dsw-static-neutral-800: rgb(41, 41, 41);
+ --dsw-static-neutral-850: rgb(33, 33, 35);
+ --dsw-static-neutral-900: rgb(15, 15, 15);
+ --dsw-static-neutral-bluish-00: rgb(255, 255, 255);
+ --dsw-static-neutral-bluish-1000: rgb(15, 17, 21);
+ --dsw-static-neutral-bluish-100: rgb(235, 238, 242);
+ --dsw-static-neutral-bluish-150: rgb(233, 236, 242);
+ --dsw-static-neutral-bluish-200: rgb(225, 229, 238);
+ --dsw-static-neutral-bluish-300: rgb(207, 211, 214);
+ --dsw-static-neutral-bluish-400: rgb(173, 178, 184);
+ --dsw-static-neutral-bluish-500: rgb(151, 157, 166);
+ --dsw-static-neutral-bluish-50: rgb(249, 250, 251);
+ --dsw-static-neutral-bluish-600: rgb(129, 133, 140);
+ --dsw-static-neutral-bluish-60: rgb(245, 246, 247);
+ --dsw-static-neutral-bluish-700: rgb(97, 102, 107);
+ --dsw-static-neutral-bluish-750: rgb(67, 69, 74);
+ --dsw-static-neutral-bluish-75: rgb(241, 243, 245);
+ --dsw-static-neutral-bluish-800: rgb(53, 54, 56);
+ --dsw-static-neutral-bluish-850: rgb(44, 44, 46);
+ --dsw-static-neutral-bluish-875: rgb(35, 35, 36);
+ --dsw-static-neutral-bluish-900: rgb(27, 27, 28);
+ --dsw-static-neutral-bluish-950: rgb(21, 21, 23);
+ --dsw-static-red-100: rgb(254, 226, 226);
+ --dsw-static-red-400: rgb(242, 90, 90);
+ --dsw-static-red-500: rgb(239, 68, 68);
+ --dsw-static-red-50: rgb(254, 242, 242);
+ --dsw-static-red-600: rgb(236, 19, 19);
+ --dsw-static-red-900: rgb(87, 12, 12);
+}
+
+.jiuwenTrajectoryTheme[data-trajectory-theme='dark'],
+.jiuwenTrajectoryPortal[data-trajectory-theme='dark'] {
+ --dsw-static-amber-100: rgb(254, 245, 231);
+ --dsw-static-amber-400: rgb(247, 173, 49);
+ --dsw-static-amber-500: rgb(245, 158, 11);
+ --dsw-static-amber-600: rgb(221, 134, 41);
+ --dsw-static-amber-900: rgb(39, 36, 31);
+ --dsw-static-blue-100: rgb(219, 234, 254);
+ --dsw-static-blue-300: rgb(147, 197, 253);
+ --dsw-static-blue-400: rgb(96, 165, 250);
+ --dsw-static-blue-450: rgb(77, 147, 248);
+ --dsw-static-blue-500: rgb(59, 130, 246);
+ --dsw-static-blue-50: rgb(239, 246, 255);
+ --dsw-static-blue-50p: rgb(234, 243, 255);
+ --dsw-static-blue-600: rgb(37, 99, 235);
+ --dsw-static-blue-75: rgb(229, 240, 255);
+ --dsw-static-blue-800: rgb(30, 64, 175);
+ --dsw-static-blue-900: rgb(14, 48, 116);
+ --dsw-static-blue-950: rgb(23, 37, 84);
+ --dsw-static-deepseek-100: rgb(228, 237, 253);
+ --dsw-static-deepseek-200: rgb(211, 226, 255);
+ --dsw-static-deepseek-300: rgb(183, 200, 254);
+ --dsw-static-deepseek-400: rgb(103, 158, 254);
+ --dsw-static-deepseek-450: rgb(86, 134, 254);
+ --dsw-static-deepseek-500: rgb(65, 118, 230);
+ --dsw-static-deepseek-50: rgb(237, 243, 254);
+ --dsw-static-deepseek-600: rgb(72, 104, 178);
+ --dsw-static-deepseek-700-delete: rgb(47, 76, 143);
+ --dsw-static-deepseek-800: rgb(52, 65, 91);
+ --dsw-static-deepseek-900: rgb(40, 49, 66);
+ --dsw-static-green-100: rgb(230, 250, 237);
+ --dsw-static-green-400: rgb(78, 209, 126);
+ --dsw-static-green-500: rgb(34, 197, 94);
+ --dsw-static-green-900: rgb(35, 60, 44);
+ --dsw-static-neutral-00: rgb(255, 255, 255);
+ --dsw-static-neutral-1000: rgb(0, 0, 0);
+ --dsw-static-neutral-100: rgb(245, 245, 245);
+ --dsw-static-neutral-150: rgb(237, 237, 237);
+ --dsw-static-neutral-200: rgb(229, 229, 229);
+ --dsw-static-neutral-250: rgb(220, 220, 220);
+ --dsw-static-neutral-300: rgb(212, 212, 212);
+ --dsw-static-neutral-400: rgb(162, 164, 166);
+ --dsw-static-neutral-500: rgb(127, 130, 135);
+ --dsw-static-neutral-50: rgb(250, 250, 250);
+ --dsw-static-neutral-550: rgb(101, 103, 107);
+ --dsw-static-neutral-600: rgb(84, 85, 87);
+ --dsw-static-neutral-700: rgb(60, 60, 61);
+ --dsw-static-neutral-800: rgb(41, 41, 41);
+ --dsw-static-neutral-850: rgb(33, 33, 35);
+ --dsw-static-neutral-900: rgb(15, 15, 15);
+ --dsw-static-neutral-bluish-00: rgb(255, 255, 255);
+ --dsw-static-neutral-bluish-1000: rgb(15, 17, 21);
+ --dsw-static-neutral-bluish-100: rgb(235, 238, 242);
+ --dsw-static-neutral-bluish-150: rgb(233, 236, 242);
+ --dsw-static-neutral-bluish-200: rgb(225, 229, 238);
+ --dsw-static-neutral-bluish-300: rgb(207, 211, 214);
+ --dsw-static-neutral-bluish-400: rgb(173, 178, 184);
+ --dsw-static-neutral-bluish-500: rgb(151, 157, 166);
+ --dsw-static-neutral-bluish-50: rgb(249, 250, 251);
+ --dsw-static-neutral-bluish-600: rgb(129, 133, 140);
+ --dsw-static-neutral-bluish-60: rgb(249, 250, 251);
+ --dsw-static-neutral-bluish-700: rgb(97, 102, 107);
+ --dsw-static-neutral-bluish-750: rgb(67, 69, 74);
+ --dsw-static-neutral-bluish-75: rgb(241, 243, 245);
+ --dsw-static-neutral-bluish-800: rgb(53, 54, 56);
+ --dsw-static-neutral-bluish-850: rgb(44, 44, 46);
+ --dsw-static-neutral-bluish-875: rgb(35, 35, 36);
+ --dsw-static-neutral-bluish-900: rgb(27, 27, 28);
+ --dsw-static-neutral-bluish-950: rgb(21, 21, 23);
+ --dsw-static-red-100: rgb(254, 226, 226);
+ --dsw-static-red-400: rgb(242, 90, 90);
+ --dsw-static-red-500: rgb(239, 68, 68);
+ --dsw-static-red-50: rgb(254, 242, 242);
+ --dsw-static-red-600: rgb(236, 19, 19);
+ --dsw-static-red-900: rgb(87, 12, 12);
+}
+
+.jiuwenTrajectoryTheme,
+.jiuwenTrajectoryPortal {
+ --dsw-alias-bg-base: var(--dsw-static-neutral-bluish-00);
+ --dsw-alias-bg-layer-1: var(--dsw-static-neutral-bluish-00);
+ --dsw-alias-bg-layer-2: var(--dsw-static-neutral-bluish-00);
+ --dsw-alias-bg-layer-3: var(--dsw-static-neutral-bluish-00);
+ --dsw-alias-bg-mask-1: rgba(0, 0, 0, 0.24);
+ --dsw-alias-bg-mask-2: rgba(0, 0, 0, 0.12);
+ --dsw-alias-bg-mask-3: rgba(0, 0, 0, 0.48);
+ --dsw-alias-bg-mask-photo: rgba(0, 0, 0, 0.88);
+ --dsw-alias-bg-mask-drop: rgba(255, 255, 255, 0.7);
+ --dsw-alias-bg-module-platform: var(--dsw-static-neutral-bluish-60);
+ --dsw-alias-bg-multi-select: var(--dsw-static-neutral-bluish-60);
+ --dsw-alias-bg-overlay: var(--dsw-static-neutral-bluish-150);
+ --dsw-alias-bg-skeleton: rgba(0, 0, 0, 0.04);
+ --dsw-alias-border-inverted2: rgba(0, 0, 0, 0);
+ --dsw-alias-border-inverted: rgba(0, 0, 0, 0);
+ --dsw-alias-border-l1: rgba(0, 0, 0, 0.04);
+ --dsw-alias-border-l2-darkmode-thin: rgba(0, 0, 0, 0.1);
+ --dsw-alias-border-l2: rgba(0, 0, 0, 0.1);
+ --dsw-alias-border-l3: rgba(0, 0, 0, 0.12);
+ --dsw-alias-border-l4: rgba(0, 0, 0, 0.16);
+ --dsw-alias-brand-primary-invert: var(--dsw-static-neutral-bluish-1000);
+ --dsw-alias-brand-primary-new-colorprimary-new-color: rgb(65, 118, 230);
+ --dsw-alias-brand-primary: var(--dsw-static-neutral-bluish-1000);
+ --dsw-alias-brand-text: var(--dsw-static-neutral-bluish-1000);
+ --dsw-alias-button-contrast-fill: var(--dsw-static-neutral-bluish-700);
+ --dsw-alias-button-elevated-fill: var(--dsw-static-neutral-bluish-00);
+ --dsw-alias-button-floating-fill: var(--dsw-static-neutral-bluish-00);
+ --dsw-alias-button-floating-hover: var(--dsw-static-neutral-bluish-75);
+ --dsw-alias-button-ghost-active-border: var(--dsw-static-neutral-bluish-500);
+ --dsw-alias-button-ghost-active-fill: var(--dsw-static-neutral-bluish-100);
+ --dsw-alias-button-ghost-active-hover: var(--dsw-static-neutral-bluish-150);
+ --dsw-alias-button-info-fill: var(--dsw-static-deepseek-500);
+ --dsw-alias-button-info-hover: var(--dsw-static-deepseek-400);
+ --dsw-alias-button-primary-dimmed: var(--dsw-static-neutral-bluish-100);
+ --dsw-alias-button-primary-fill: var(--dsw-alias-brand-primary);
+ --dsw-alias-button-primary-hover: var(--dsw-static-neutral-bluish-750);
+ --dsw-alias-button-tool-bar-fill-invisible: rgba(31, 31, 31, 0.36);
+ --dsw-alias-button-tool-bar-fill: rgba(84, 85, 87, 0.5);
+ --dsw-alias-button-tool-bar-hover: rgba(84, 85, 87, 0.6);
+ --dsw-alias-interactive-bg-active: rgba(38, 49, 72, 0.1);
+ --dsw-alias-interactive-bg-hover-accent: rgba(38, 49, 72, 0.14);
+ --dsw-alias-interactive-bg-hover-danger: rgba(236, 19, 19, 0.05);
+ --dsw-alias-interactive-bg-hover-solid: var(--dsw-static-neutral-bluish-75);
+ --dsw-alias-interactive-bg-hover: rgba(38, 49, 72, 0.06);
+ --dsw-alias-label-caption: var(--dsw-static-neutral-bluish-400);
+ --dsw-alias-label-dimmed: var(--dsw-static-neutral-bluish-200);
+ --dsw-alias-label-primary-bluish: var(--dsw-static-blue-900);
+ --dsw-alias-label-primary-dimmed: var(--dsw-static-neutral-bluish-950);
+ --dsw-alias-label-primary-foreground: var(--dsw-static-neutral-bluish-00);
+ --dsw-alias-label-primary-inverted: var(--dsw-static-neutral-bluish-00);
+ --dsw-alias-label-primary: var(--dsw-static-neutral-bluish-1000);
+ --dsw-alias-label-secondary: var(--dsw-static-neutral-bluish-700);
+ --dsw-alias-label-tertiary: var(--dsw-static-neutral-bluish-600);
+ --dsw-alias-markdown-citation: var(--dsw-static-neutral-bluish-100);
+ --dsw-alias-markdown-code-block-banner: var(--dsw-static-neutral-bluish-50);
+ --dsw-alias-markdown-code-block: var(--dsw-static-neutral-bluish-50);
+ --dsw-alias-markdown-code-segment-selected: var(--dsw-static-neutral-bluish-00);
+ --dsw-alias-markdown-code-segment-unselected: var(--dsw-static-neutral-bluish-75);
+ --dsw-alias-markdown-inline-code: var(--dsw-static-neutral-bluish-100);
+ --dsw-alias-markdown-placeholder: var(--dsw-static-neutral-bluish-60);
+ --dsw-alias-markdown-tag: var(--dsw-static-neutral-bluish-75);
+ --dsw-alias-scrollbar-bg-l1: var(--dsw-static-neutral-200);
+ --dsw-alias-scrollbar-bg-l2: var(--dsw-static-neutral-200);
+ --dsw-alias-scrollbar-hover-l1: var(--dsw-static-neutral-300);
+ --dsw-alias-scrollbar-hover-l2: var(--dsw-static-neutral-300);
+ --dsw-alias-state-business-primary: var(--dsw-static-deepseek-500);
+ --dsw-alias-state-business-tertiary: var(--dsw-static-deepseek-100);
+ --dsw-alias-state-error-primary: var(--dsw-static-red-600);
+ --dsw-alias-state-error-secondary: var(--dsw-static-red-400);
+ --dsw-alias-state-success-primary: var(--dsw-static-green-500);
+ --dsw-alias-state-success-secondary: var(--dsw-static-green-400);
+ --dsw-alias-state-success-tertiary: var(--dsw-static-green-100);
+ --dsw-alias-state-warn-label: var(--dsw-static-amber-600);
+ --dsw-alias-state-warn-primary: var(--dsw-static-amber-500);
+ --dsw-alias-state-warn-secondary: var(--dsw-static-amber-400);
+ --dsw-alias-state-warn-tertiary: var(--dsw-static-amber-100);
+ --dsw-alias-toast-bg: var(--dsw-static-neutral-bluish-800);
+ --dsw-alias-tooltip-bg: var(--dsw-static-neutral-bluish-850);
+ --dsw-specific-bubble-highlight: var(--dsw-static-deepseek-200);
+ --dsw-specific-bubble: var(--dsw-static-deepseek-50);
+ --dsw-specific-input-major: var(--dsw-static-neutral-bluish-00);
+ --dsw-specific-login-input: var(--dsw-static-neutral-bluish-50);
+ --dsw-specific-menu: var(--dsw-alias-bg-layer-3);
+ --dsw-specific-selector: var(--dsw-static-neutral-bluish-60);
+ --dsw-specific-sidebar-fill: var(--dsw-static-neutral-bluish-50);
+ --dsw-specific-sidebar-nav-item-active-accent: var(--dsw-static-deepseek-100);
+ --dsw-specific-sidebar-nav-item-active: var(--dsw-static-neutral-bluish-100);
+ --dsw-specific-sidebar-nav-item-hover: var(--dsw-static-neutral-bluish-75);
+ --dsw-specific-tip: var(--dsw-static-neutral-bluish-60);
+}
+
+.jiuwenTrajectoryTheme[data-trajectory-theme='dark'],
+.jiuwenTrajectoryPortal[data-trajectory-theme='dark'] {
+ --dsw-alias-bg-base: var(--dsw-static-neutral-bluish-950);
+ --dsw-alias-bg-layer-1: var(--dsw-static-neutral-bluish-875);
+ --dsw-alias-bg-layer-2: var(--dsw-static-neutral-bluish-850);
+ --dsw-alias-bg-layer-3: var(--dsw-static-neutral-bluish-800);
+ --dsw-alias-bg-mask-1: rgba(0, 0, 0, 0.5);
+ --dsw-alias-bg-mask-2: rgba(0, 0, 0, 0.2);
+ --dsw-alias-bg-mask-3: rgba(0, 0, 0, 0.48);
+ --dsw-alias-bg-mask-photo: rgba(0, 0, 0, 0.88);
+ --dsw-alias-bg-mask-drop: rgba(39, 39, 48, 0.7);
+ --dsw-alias-bg-module-platform: var(--dsw-static-neutral-bluish-800);
+ --dsw-alias-bg-multi-select: var(--dsw-static-neutral-850);
+ --dsw-alias-bg-overlay: var(--dsw-static-neutral-bluish-700);
+ --dsw-alias-bg-skeleton: rgba(255, 255, 255, 0.08);
+ --dsw-alias-border-inverted2: rgba(255, 255, 255, 0.08);
+ --dsw-alias-border-inverted: rgba(255, 255, 255, 0.06);
+ --dsw-alias-border-l1: rgba(255, 255, 255, 0.06);
+ --dsw-alias-border-l2-darkmode-thin: rgba(255, 255, 255, 0.06);
+ --dsw-alias-border-l2: rgba(255, 255, 255, 0.12);
+ --dsw-alias-border-l3: rgba(255, 255, 255, 0.16);
+ --dsw-alias-border-l4: rgba(255, 255, 255, 0.2);
+ --dsw-alias-brand-primary-invert: var(--dsw-static-neutral-bluish-50);
+ --dsw-alias-brand-primary-new-colorprimary-new-color: var(--dsw-static-deepseek-450);
+ --dsw-alias-brand-primary: var(--dsw-static-neutral-bluish-50);
+ --dsw-alias-brand-text: var(--dsw-static-neutral-bluish-50);
+ --dsw-alias-button-contrast-fill: var(--dsw-static-neutral-bluish-50);
+ --dsw-alias-button-elevated-fill: var(--dsw-static-neutral-bluish-750);
+ --dsw-alias-button-floating-fill: var(--dsw-static-neutral-bluish-850);
+ --dsw-alias-button-floating-hover: var(--dsw-static-neutral-bluish-800);
+ --dsw-alias-button-ghost-active-border: var(--dsw-static-neutral-bluish-600);
+ --dsw-alias-button-ghost-active-fill: var(--dsw-static-neutral-bluish-750);
+ --dsw-alias-button-ghost-active-hover: var(--dsw-static-neutral-bluish-700);
+ --dsw-alias-button-info-fill: var(--dsw-static-deepseek-400);
+ --dsw-alias-button-info-hover: var(--dsw-static-deepseek-500);
+ --dsw-alias-button-primary-dimmed: var(--dsw-static-neutral-bluish-750);
+ --dsw-alias-button-primary-fill: var(--dsw-alias-brand-primary);
+ --dsw-alias-button-primary-hover: var(--dsw-static-neutral-bluish-100);
+ --dsw-alias-button-tool-bar-fill-invisible: rgba(31, 31, 31, 0.36);
+ --dsw-alias-button-tool-bar-fill: rgba(84, 85, 87, 0.5);
+ --dsw-alias-button-tool-bar-hover: rgba(84, 85, 87, 0.6);
+ --dsw-alias-interactive-bg-active: rgba(255, 255, 255, 0.14);
+ --dsw-alias-interactive-bg-hover-accent: rgba(255, 255, 255, 0.24);
+ --dsw-alias-interactive-bg-hover-danger: rgba(242, 90, 90, 0.15);
+ --dsw-alias-interactive-bg-hover-solid: var(--dsw-static-neutral-bluish-800);
+ --dsw-alias-interactive-bg-hover: rgba(255, 255, 255, 0.08);
+ --dsw-alias-label-caption: var(--dsw-static-neutral-bluish-600);
+ --dsw-alias-label-dimmed: var(--dsw-static-neutral-bluish-750);
+ --dsw-alias-label-primary-bluish: var(--dsw-static-neutral-bluish-50);
+ --dsw-alias-label-primary-dimmed: var(--dsw-static-neutral-bluish-100);
+ --dsw-alias-label-primary-foreground: var(--dsw-static-neutral-bluish-1000);
+ --dsw-alias-label-primary-inverted: var(--dsw-static-neutral-bluish-800);
+ --dsw-alias-label-primary: var(--dsw-static-neutral-bluish-50);
+ --dsw-alias-label-secondary: var(--dsw-static-neutral-bluish-300);
+ --dsw-alias-label-tertiary: var(--dsw-static-neutral-bluish-400);
+ --dsw-alias-markdown-citation: var(--dsw-static-neutral-bluish-800);
+ --dsw-alias-markdown-code-block-banner: var(--dsw-static-neutral-bluish-850);
+ --dsw-alias-markdown-code-block: var(--dsw-static-neutral-bluish-900);
+ --dsw-alias-markdown-code-segment-selected: var(--dsw-static-neutral-bluish-800);
+ --dsw-alias-markdown-code-segment-unselected: var(--dsw-static-neutral-bluish-900);
+ --dsw-alias-markdown-inline-code: var(--dsw-static-neutral-bluish-850);
+ --dsw-alias-markdown-placeholder: var(--dsw-static-neutral-bluish-850);
+ --dsw-alias-markdown-tag: var(--dsw-static-neutral-bluish-850);
+ --dsw-alias-scrollbar-bg-l1: var(--dsw-static-neutral-700);
+ --dsw-alias-scrollbar-bg-l2: var(--dsw-static-neutral-600);
+ --dsw-alias-scrollbar-hover-l1: var(--dsw-static-neutral-600);
+ --dsw-alias-scrollbar-hover-l2: var(--dsw-static-neutral-550);
+ --dsw-alias-state-business-primary: var(--dsw-static-deepseek-400);
+ --dsw-alias-state-business-tertiary: var(--dsw-static-deepseek-800);
+ --dsw-alias-state-error-primary: var(--dsw-static-red-400);
+ --dsw-alias-state-error-secondary: var(--dsw-static-red-400);
+ --dsw-alias-state-success-primary: var(--dsw-static-green-500);
+ --dsw-alias-state-success-secondary: var(--dsw-static-green-400);
+ --dsw-alias-state-success-tertiary: var(--dsw-static-green-900);
+ --dsw-alias-state-warn-label: var(--dsw-static-amber-600);
+ --dsw-alias-state-warn-primary: var(--dsw-static-amber-500);
+ --dsw-alias-state-warn-secondary: var(--dsw-static-amber-400);
+ --dsw-alias-state-warn-tertiary: var(--dsw-static-amber-900);
+ --dsw-alias-toast-bg: var(--dsw-static-neutral-bluish-750);
+ --dsw-alias-tooltip-bg: var(--dsw-static-neutral-bluish-750);
+ --dsw-specific-bubble-highlight: var(--dsw-static-neutral-bluish-750);
+ --dsw-specific-bubble: var(--dsw-static-neutral-bluish-850);
+ --dsw-specific-input-major: var(--dsw-static-neutral-bluish-850);
+ --dsw-specific-login-input: var(--dsw-static-neutral-bluish-900);
+ --dsw-specific-menu: var(--dsw-alias-bg-layer-3);
+ --dsw-specific-selector: var(--dsw-static-neutral-bluish-800);
+ --dsw-specific-sidebar-fill: var(--dsw-static-neutral-bluish-900);
+ --dsw-specific-sidebar-nav-item-active-accent: var(--dsw-static-neutral-bluish-800);
+ --dsw-specific-sidebar-nav-item-active: var(--dsw-static-neutral-bluish-750);
+ --dsw-specific-sidebar-nav-item-hover: var(--dsw-static-neutral-bluish-850);
+ --dsw-specific-tip: var(--dsw-static-neutral-bluish-800);
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/gradient-shadow-text.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/gradient-shadow-text.css
new file mode 100644
index 0000000000..c54159ea46
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/gradient-shadow-text.css
@@ -0,0 +1,254 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+.jiuwenTrajectoryTheme,
+.jiuwenTrajectoryPortal {
+ --dsw-linear-gradient-think: linear-gradient(180deg, #fff 20.19%, rgba(255, 255, 255, 0) 100%);
+ --dsw-linear-think-select: linear-gradient(180deg, #f5f6f7 20.19%, rgba(245, 246, 247, 0) 100%);
+ /* Shadows */
+ --dsw-shadow-lv1: 0 2px 4px 0 rgba(0, 0, 0, 0.05);
+ --dsw-shadow-lv1-blur: 0 4px 12px 0 rgba(0, 0, 0, 0.02);
+ --dsw-shadow-lv2: 0 4px 12px 0 rgba(0, 0, 0, 0.02), 0 2px 8px 0 rgba(0, 0, 0, 0.04);
+ --dsw-shadow-lv3:
+ 0 0 1px 0 rgba(0, 0, 0, 0.2), 0 0 4px 0 rgba(0, 0, 0, 0.02), 0 12px 32px 0 rgba(0, 0, 0, 0.08);
+ /* blur filter */
+ --dsw-mask-blur: blur(2px);
+ --trajectory-shadow-request-boundary: 0 2px 6px rgba(0, 0, 0, 0.12);
+ --trajectory-shadow-mobile-details: -12px 0 32px rgba(0, 0, 0, 0.14);
+ --trajectory-math-error: var(--dsw-alias-state-error-primary);
+ --json-tree-property: #881391;
+ --json-tree-string: #c41a16;
+ --json-tree-number: #1c00cf;
+ --json-tree-keyword: #1c00cf;
+ --json-tree-punctuation: #202124;
+ --json-tree-icon: #5f6368;
+ --json-tree-hover: rgb(60 64 67 / 4%);
+}
+
+.jiuwenTrajectoryTheme[data-trajectory-theme='dark'],
+.jiuwenTrajectoryPortal[data-trajectory-theme='dark'] {
+ --dsw-linear-gradient-think: linear-gradient(180deg, #151517 20.19%, rgba(21, 21, 23, 0) 100%);
+ --dsw-linear-think-select: linear-gradient(180deg, #232325 20.19%, rgba(35, 35, 37, 0) 100%);
+ --json-tree-property: #5db0d7;
+ --json-tree-string: #f28b82;
+ --json-tree-number: #99c8ff;
+ --json-tree-keyword: #99c8ff;
+ --json-tree-punctuation: #e8eaed;
+ --json-tree-icon: #9aa0a6;
+ --json-tree-hover: rgb(232 234 237 / 5%);
+}
+
+/* ---------- Typography ---------- */
+/* Exported by the @deepseek-figma-plugin/custom-variable-name plugin. */
+.jiuwenTrajectoryTheme,
+.jiuwenTrajectoryPortal {
+ --dsw-font-markdown-h1: 700 24px/34px var(--dsw-font-family);
+ --dsw-font-markdown-h1-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-h1-font-weight: 700;
+ --dsw-font-markdown-h1-line-height: 34px;
+ --dsw-font-markdown-h1-font-size: 24px;
+ --dsw-font-markdown-h1-font-style: normal;
+
+ --dsw-font-markdown-h2: 700 22px/32px var(--dsw-font-family);
+ --dsw-font-markdown-h2-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-h2-font-weight: 700;
+ --dsw-font-markdown-h2-line-height: 32px;
+ --dsw-font-markdown-h2-font-size: 22px;
+ --dsw-font-markdown-h2-font-style: normal;
+
+ --dsw-font-markdown-h3: 700 20px/30px var(--dsw-font-family);
+ --dsw-font-markdown-h3-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-h3-font-weight: 700;
+ --dsw-font-markdown-h3-line-height: 30px;
+ --dsw-font-markdown-h3-font-size: 20px;
+ --dsw-font-markdown-h3-font-style: normal;
+
+ --dsw-font-markdown-h4: 600 16px/28px var(--dsw-font-family);
+ --dsw-font-markdown-h4-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-h4-font-weight: 600;
+ --dsw-font-markdown-h4-line-height: 28px;
+ --dsw-font-markdown-h4-font-size: 16px;
+ --dsw-font-markdown-h4-font-style: normal;
+
+ --dsw-font-markdown-base: 16px/28px var(--dsw-font-family);
+ --dsw-font-markdown-base-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-base-font-weight: 400;
+ --dsw-font-markdown-base-line-height: 28px;
+ --dsw-font-markdown-base-font-size: 16px;
+ --dsw-font-markdown-base-font-style: normal;
+
+ --dsw-font-markdown-base-strong: 600 16px/28px var(--dsw-font-family);
+ --dsw-font-markdown-base-strong-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-base-strong-font-weight: 600;
+ --dsw-font-markdown-base-strong-line-height: 28px;
+ --dsw-font-markdown-base-strong-font-size: 16px;
+ --dsw-font-markdown-base-strong-font-style: normal;
+
+ --dsw-font-markdown-base-italic: italic 16px/28px var(--dsw-font-family);
+ --dsw-font-markdown-base-italic-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-base-italic-font-weight: 400;
+ --dsw-font-markdown-base-italic-line-height: 28px;
+ --dsw-font-markdown-base-italic-font-size: 16px;
+ --dsw-font-markdown-base-italic-font-style: italic;
+
+ --dsw-font-markdown-base-strong-italic: italic 600 16px/28px var(--dsw-font-family);
+ --dsw-font-markdown-base-strong-italic-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-base-strong-italic-font-weight: 600;
+ --dsw-font-markdown-base-strong-italic-line-height: 28px;
+ --dsw-font-markdown-base-strong-italic-font-size: 16px;
+ --dsw-font-markdown-base-strong-italic-font-style: italic;
+
+ --dsw-font-markdown-table: 15px/25px var(--dsw-font-family);
+ --dsw-font-markdown-table-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-table-font-weight: 400;
+ --dsw-font-markdown-table-line-height: 25px;
+ --dsw-font-markdown-table-font-size: 15px;
+ --dsw-font-markdown-table-font-style: normal;
+
+ --dsw-font-markdown-table-head: 500 15px/25px var(--dsw-font-family);
+ --dsw-font-markdown-table-head-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-table-head-font-weight: 500;
+ --dsw-font-markdown-table-head-line-height: 25px;
+ --dsw-font-markdown-table-head-font-size: 15px;
+ --dsw-font-markdown-table-head-font-style: normal;
+
+ --dsw-font-markdown-small: 14px/24px var(--dsw-font-family);
+ --dsw-font-markdown-small-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-small-font-weight: 400;
+ --dsw-font-markdown-small-line-height: 24px;
+ --dsw-font-markdown-small-font-size: 14px;
+ --dsw-font-markdown-small-font-style: normal;
+
+ --dsw-font-markdown-small-strong: 600 14px/24px var(--dsw-font-family);
+ --dsw-font-markdown-small-strong-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-small-strong-font-weight: 600;
+ --dsw-font-markdown-small-strong-line-height: 24px;
+ --dsw-font-markdown-small-strong-font-size: 14px;
+ --dsw-font-markdown-small-strong-font-style: normal;
+
+ --dsw-font-markdown-small-italic: italic 14px/24px var(--dsw-font-family);
+ --dsw-font-markdown-small-italic-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-small-italic-font-weight: 400;
+ --dsw-font-markdown-small-italic-line-height: 24px;
+ --dsw-font-markdown-small-italic-font-size: 14px;
+ --dsw-font-markdown-small-italic-font-style: italic;
+
+ --dsw-font-markdown-small-strong-italic: italic 600 14px/24px var(--dsw-font-family);
+ --dsw-font-markdown-small-strong-italic-font-family: var(--dsw-font-family);
+ --dsw-font-markdown-small-strong-italic-font-weight: 600;
+ --dsw-font-markdown-small-strong-italic-line-height: 24px;
+ --dsw-font-markdown-small-strong-italic-font-size: 14px;
+ --dsw-font-markdown-small-strong-italic-font-style: italic;
+
+ --dsw-font-markdown-code: 14px/22px var(--ds-font-family-code);
+ --dsw-font-markdown-code-font-family: var(--ds-font-family-code);
+ --dsw-font-markdown-code-font-weight: 400;
+ --dsw-font-markdown-code-line-height: 22px;
+ --dsw-font-markdown-code-font-size: 14px;
+ --dsw-font-markdown-code-font-style: normal;
+
+ --dsw-font-markdown-code-block: 13px/22px var(--ds-font-family-code);
+ --dsw-font-markdown-code-block-font-family: var(--ds-font-family-code);
+ --dsw-font-markdown-code-block-font-weight: 400;
+ --dsw-font-markdown-code-block-line-height: 22px;
+ --dsw-font-markdown-code-block-font-size: 13px;
+ --dsw-font-markdown-code-block-font-style: normal;
+
+ /* Local addition: compact code type inside expanded tool-row cards. */
+ --dsw-font-markdown-code-block-small: 12px/18px var(--ds-font-family-code);
+ --dsw-font-markdown-code-block-small-font-family: var(--ds-font-family-code);
+ --dsw-font-markdown-code-block-small-font-weight: 400;
+ --dsw-font-markdown-code-block-small-line-height: 18px;
+ --dsw-font-markdown-code-block-small-font-size: 12px;
+ --dsw-font-markdown-code-block-small-font-style: normal;
+
+ --dsw-font-xl-24: 600 24px/32px var(--dsw-font-family);
+ --dsw-font-xl-24-font-family: var(--dsw-font-family);
+ --dsw-font-xl-24-font-weight: 600;
+ --dsw-font-xl-24-line-height: 32px;
+ --dsw-font-xl-24-font-size: 24px;
+ --dsw-font-xl-24-font-style: normal;
+
+ --dsw-font-l-20: 500 20px/28px var(--dsw-font-family);
+ --dsw-font-l-20-font-family: var(--dsw-font-family);
+ --dsw-font-l-20-font-weight: 500;
+ --dsw-font-l-20-line-height: 28px;
+ --dsw-font-l-20-font-size: 20px;
+ --dsw-font-l-20-font-style: normal;
+
+ --dsw-font-m-18: 500 16px/28px var(--dsw-font-family);
+ --dsw-font-m-18-font-family: var(--dsw-font-family);
+ --dsw-font-m-18-font-weight: 500;
+ --dsw-font-m-18-line-height: 28px;
+ --dsw-font-m-18-font-size: 16px;
+ --dsw-font-m-18-font-style: normal;
+
+ --dsw-font-base-16: 16px/24px var(--dsw-font-family);
+ --dsw-font-base-16-font-family: var(--dsw-font-family);
+ --dsw-font-base-16-font-weight: 400;
+ --dsw-font-base-16-line-height: 24px;
+ --dsw-font-base-16-font-size: 16px;
+ --dsw-font-base-16-font-style: normal;
+
+ --dsw-font-base-strong-16: 500 16px/24px var(--dsw-font-family);
+ --dsw-font-base-strong-16-font-family: var(--dsw-font-family);
+ --dsw-font-base-strong-16-font-weight: 500;
+ --dsw-font-base-strong-16-line-height: 24px;
+ --dsw-font-base-strong-16-font-size: 16px;
+ --dsw-font-base-strong-16-font-style: normal;
+
+ --dsw-font-s-14: 14px/22px var(--dsw-font-family);
+ --dsw-font-s-14-font-family: var(--dsw-font-family);
+ --dsw-font-s-14-font-weight: 400;
+ --dsw-font-s-14-line-height: 22px;
+ --dsw-font-s-14-font-size: 14px;
+ --dsw-font-s-14-font-style: normal;
+
+ --dsw-font-s-strong-14: 500 14px/22px var(--dsw-font-family);
+ --dsw-font-s-strong-14-font-family: var(--dsw-font-family);
+ --dsw-font-s-strong-14-font-weight: 500;
+ --dsw-font-s-strong-14-line-height: 22px;
+ --dsw-font-s-strong-14-font-size: 14px;
+ --dsw-font-s-strong-14-font-style: normal;
+
+ --dsw-font-xs-13: 13px/20px var(--dsw-font-family);
+ --dsw-font-xs-13-font-family: var(--dsw-font-family);
+ --dsw-font-xs-13-font-weight: 400;
+ --dsw-font-xs-13-line-height: 20px;
+ --dsw-font-xs-13-font-size: 13px;
+ --dsw-font-xs-13-font-style: normal;
+
+ --dsw-font-xs-strong-13: 500 13px/20px var(--dsw-font-family);
+ --dsw-font-xs-strong-13-font-family: var(--dsw-font-family);
+ --dsw-font-xs-strong-13-font-weight: 500;
+ --dsw-font-xs-strong-13-line-height: 20px;
+ --dsw-font-xs-strong-13-font-size: 13px;
+ --dsw-font-xs-strong-13-font-style: normal;
+
+ --dsw-font-xxs-12: 12px/18px var(--dsw-font-family);
+ --dsw-font-xxs-12-font-family: var(--dsw-font-family);
+ --dsw-font-xxs-12-font-weight: 400;
+ --dsw-font-xxs-12-line-height: 18px;
+ --dsw-font-xxs-12-font-size: 12px;
+ --dsw-font-xxs-12-font-style: normal;
+
+ --dsw-font-xxs-strong-12: 500 12px/18px var(--dsw-font-family);
+ --dsw-font-xxs-strong-12-font-family: var(--dsw-font-family);
+ --dsw-font-xxs-strong-12-font-weight: 500;
+ --dsw-font-xxs-strong-12-line-height: 18px;
+ --dsw-font-xxs-strong-12-font-size: 12px;
+ --dsw-font-xxs-strong-12-font-style: normal;
+
+ --dsw-font-xxxs-11: 11px/14px var(--dsw-font-family);
+ --dsw-font-xxxs-11-font-family: var(--dsw-font-family);
+ --dsw-font-xxxs-11-font-weight: 400;
+ --dsw-font-xxxs-11-line-height: 14px;
+ --dsw-font-xxxs-11-font-size: 11px;
+ --dsw-font-xxxs-11-font-style: normal;
+
+ --dsw-font-xxxs-strong-11: 500 11px/14px var(--dsw-font-family);
+ --dsw-font-xxxs-strong-11-font-family: var(--dsw-font-family);
+ --dsw-font-xxxs-strong-11-font-weight: 500;
+ --dsw-font-xxxs-strong-11-line-height: 14px;
+ --dsw-font-xxxs-strong-11-font-size: 11px;
+ --dsw-font-xxxs-strong-11-font-style: normal;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/scrollbar.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/scrollbar.css
new file mode 100644
index 0000000000..b985d73115
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/scrollbar.css
@@ -0,0 +1,107 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+/* Scrollbar skin: the sole consumer of the four --dsw-alias-scrollbar-*
+ * tokens. Without it every scrolling region renders the UA scrollbar, which
+ * ignores the theme — a light native bar over the dark palette.
+ *
+ * The migrated rules sit on the trajectory host and its portal surface.
+ * design-platform.css declares the --dsw-alias-* tokens on those same scoped
+ * roots, so custom properties never alter unrelated JiuwenSwarm surfaces.
+ *
+ * Surfaces pick their elevation by rebinding --dsh-scrollbar-thumb{,-hover}:
+ * the l1 pair here is the base-surface default, and an elevated surface
+ * (menu, popover, dialog) rebinds to the l2 pair on its own container. Both
+ * rendering paths below read the indirection, so one rebind reaches whichever
+ * path the engine took. */
+
+.jiuwenTrajectoryTheme,
+.jiuwenTrajectoryPortal {
+ --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l1);
+ --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l1);
+ /* The WebKit bar's layout width, mirrored by the ::-webkit-scrollbar rule
+ below. A surface that must align itself beside a space-consuming bar
+ (ConversationRoot's overlay composer seat) reads this instead of
+ hardcoding the number. */
+ --dsh-scrollbar-width: 8px;
+}
+
+/* The two paths are mutually exclusive, and the gate is load-bearing rather
+ than defensive. A non-`auto` `scrollbar-width` or `scrollbar-color` makes
+ Chromium and Safari drop every `::-webkit-scrollbar*` rule for that
+ element, including `::-webkit-scrollbar-thumb:hover` — measured in chromium
+ as an 8px `::-webkit-scrollbar` width taking effect on its own and being
+ ignored as soon as `scrollbar-width: thin` is added. Declaring both
+ unconditionally therefore leaves the hover tokens with no rendering at all,
+ because the engines that implement the hover pseudo-element are exactly the
+ ones the standard properties silence, and Firefox has no hover
+ pseudo-element to fall back on.
+
+ `not selector(::-webkit-scrollbar)` is true only where the pseudo-element
+ is unimplemented, so Firefox takes the standard path and WebKit-based
+ engines take the pseudo-element path. An engine too old for the
+ `selector()` function makes the condition invalid, which evaluates false
+ and selects the pseudo-element path — the correct side for the pre-16.4
+ Safari that is the realistic case. */
+@supports not selector(::-webkit-scrollbar) {
+ /* Declared on every element rather than inherited from the host. Inheriting
+ would pass down the COLOUR already substituted at the host, so a descendant
+ rebinding --dsh-scrollbar-thumb could not change it; re-declaring makes
+ each element substitute the variable as it sees it, which is what gives
+ an elevated surface a working rebind. `scrollbar-width` is not an
+ inherited property at all, so it needs the per-element declaration
+ regardless.
+
+ No hover counterpart exists on this path: `scrollbar-color` states one
+ thumb colour and the engine derives its own hover treatment. */
+ .jiuwenTrajectoryTheme,
+ .jiuwenTrajectoryTheme *,
+ .jiuwenTrajectoryPortal,
+ .jiuwenTrajectoryPortal * {
+ scrollbar-width: thin;
+ scrollbar-color: var(--dsh-scrollbar-thumb) transparent;
+ }
+}
+
+/* Not gated in turn: an engine that does not implement these pseudo-elements
+ drops the rules as unknown selectors, so the gate would only restate what
+ selector matching already does. The selectors remain explicitly scoped. */
+.jiuwenTrajectoryTheme::-webkit-scrollbar,
+.jiuwenTrajectoryTheme *::-webkit-scrollbar,
+.jiuwenTrajectoryPortal::-webkit-scrollbar,
+.jiuwenTrajectoryPortal *::-webkit-scrollbar {
+ width: 8px;
+ height: 8px;
+}
+
+/* Track stays transparent so the thumb reads against whatever surface scrolls
+ under it; only the thumb carries a token colour. */
+.jiuwenTrajectoryTheme::-webkit-scrollbar-track,
+.jiuwenTrajectoryTheme *::-webkit-scrollbar-track,
+.jiuwenTrajectoryPortal::-webkit-scrollbar-track,
+.jiuwenTrajectoryPortal *::-webkit-scrollbar-track {
+ background: transparent;
+}
+
+.jiuwenTrajectoryTheme::-webkit-scrollbar-thumb,
+.jiuwenTrajectoryTheme *::-webkit-scrollbar-thumb,
+.jiuwenTrajectoryPortal::-webkit-scrollbar-thumb,
+.jiuwenTrajectoryPortal *::-webkit-scrollbar-thumb {
+ border-radius: 4px;
+ background: var(--dsh-scrollbar-thumb);
+}
+
+.jiuwenTrajectoryTheme::-webkit-scrollbar-thumb:hover,
+.jiuwenTrajectoryTheme *::-webkit-scrollbar-thumb:hover,
+.jiuwenTrajectoryPortal::-webkit-scrollbar-thumb:hover,
+.jiuwenTrajectoryPortal *::-webkit-scrollbar-thumb:hover {
+ background: var(--dsh-scrollbar-thumb-hover);
+}
+
+/* Both scrollbars meeting in a corner: no separate token, so the corner
+ matches the transparent track rather than the UA's opaque default. */
+.jiuwenTrajectoryTheme::-webkit-scrollbar-corner,
+.jiuwenTrajectoryTheme *::-webkit-scrollbar-corner,
+.jiuwenTrajectoryPortal::-webkit-scrollbar-corner,
+.jiuwenTrajectoryPortal *::-webkit-scrollbar-corner {
+ background: transparent;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/shiki.css b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/shiki.css
new file mode 100644
index 0000000000..8025b9935d
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/theme/shiki.css
@@ -0,0 +1,35 @@
+/* Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. */
+
+/* Syntax-highlight token palette: the values behind shiki's css-variables
+ theme (--shiki-* custom properties emitted by the ui-primitives CodeBlock).
+ Light values live on the trajectory roots, with local dark overrides — the
+ same cascade as every other token sheet. Background/foreground deliberately
+ alias the markdown code-block tokens so highlighted and plain blocks agree. */
+
+.jiuwenTrajectoryTheme,
+.jiuwenTrajectoryPortal {
+ --shiki-foreground: var(--dsw-alias-label-primary);
+ --shiki-background: var(--dsw-alias-markdown-code-block);
+ --shiki-token-constant: #1c7ed6;
+ --shiki-token-string: #2f9e44;
+ --shiki-token-comment: #868e96;
+ --shiki-token-keyword: #d6336c;
+ --shiki-token-parameter: #e8590c;
+ --shiki-token-function: #6741d9;
+ --shiki-token-string-expression: #2b8a3e;
+ --shiki-token-punctuation: #495057;
+ --shiki-token-link: #1971c2;
+}
+
+.jiuwenTrajectoryTheme[data-trajectory-theme='dark'],
+.jiuwenTrajectoryPortal[data-trajectory-theme='dark'] {
+ --shiki-token-constant: #4dabf7;
+ --shiki-token-string: #69db7c;
+ --shiki-token-comment: #adb5bd;
+ --shiki-token-keyword: #faa2c1;
+ --shiki-token-parameter: #ffa94d;
+ --shiki-token-function: #b197fc;
+ --shiki-token-string-expression: #8ce99a;
+ --shiki-token-punctuation: #ced4da;
+ --shiki-token-link: #74c0fc;
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/PROVENANCE.md b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/PROVENANCE.md
new file mode 100644
index 0000000000..456c86d484
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/PROVENANCE.md
@@ -0,0 +1,19 @@
+# Trajectory source provenance
+
+English | [中文](PROVENANCE.zh.md)
+
+JiuwenSwarm copies selected DSH Trajectory sources under the MIT license and adapts only the copies in this feature directory. The original `packages/client` files remain unchanged and continue to own the DSH Web feature.
+
+| JiuwenSwarm copy | DSH source |
+|---|---|
+| `../client/TrajectoryTable.tsx` and `.module.css` | `packages/client/ui-trajectory/src/client/TrajectoryTable.*` |
+| `../client/TrajectoryTimeline.tsx` and `.module.css` | `packages/client/ui-trajectory/src/client/TrajectoryTimeline.*` |
+| `../client/TrajectoryToolbar.tsx` and `.module.css` | `packages/client/ui-trajectory/src/client/TrajectoryToolbar.*` |
+| `../client/TrajectoryExplorer.module.css` | `packages/client/ui-trajectory/src/client/views.module.css` |
+| `timeline.ts` | `packages/client/ui-trajectory/src/client/timeline.ts` |
+| `search-index.ts` | `packages/client/ui-trajectory/src/client/trajectory-search-index.ts` |
+| `virtual-rows.ts` | `packages/client/ui-trajectory/src/client/trajectory-virtual-rows.ts` |
+| `preview.ts` | `packages/client/ui-trajectory/src/client/trajectory-preview.ts` |
+| `record.ts` | `packages/client/ui-trajectory/src/client/trajectory-record.ts` |
+
+`../theme/` starts from the five token sheets in `packages/client/ui-theme/src/styles` and scopes them to the trajectory host; [`../theme/PROVENANCE.md`](../theme/PROVENANCE.md) records the source revision and adaptation. [`../primitives/PROVENANCE.md`](../primitives/PROVENANCE.md) records the locally copied React primitives. JiuwenSwarm does not resolve an upstream workspace package at build or runtime.
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/PROVENANCE.zh.md b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/PROVENANCE.zh.md
new file mode 100644
index 0000000000..d2d6962960
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/PROVENANCE.zh.md
@@ -0,0 +1,19 @@
+# 轨迹源码来源
+
+[English](PROVENANCE.md) | 中文
+
+JiuwenSwarm 依据 MIT 许可证复制部分 DSH Trajectory 源码,并且仅调整本 feature 目录中的副本。原始 `packages/client` 文件保持不变,并继续负责 DSH Web 功能。
+
+| JiuwenSwarm 副本 | DSH 源文件 |
+|---|---|
+| `../client/TrajectoryTable.tsx` 和 `.module.css` | `packages/client/ui-trajectory/src/client/TrajectoryTable.*` |
+| `../client/TrajectoryTimeline.tsx` 和 `.module.css` | `packages/client/ui-trajectory/src/client/TrajectoryTimeline.*` |
+| `../client/TrajectoryToolbar.tsx` 和 `.module.css` | `packages/client/ui-trajectory/src/client/TrajectoryToolbar.*` |
+| `../client/TrajectoryExplorer.module.css` | `packages/client/ui-trajectory/src/client/views.module.css` |
+| `timeline.ts` | `packages/client/ui-trajectory/src/client/timeline.ts` |
+| `search-index.ts` | `packages/client/ui-trajectory/src/client/trajectory-search-index.ts` |
+| `virtual-rows.ts` | `packages/client/ui-trajectory/src/client/trajectory-virtual-rows.ts` |
+| `preview.ts` | `packages/client/ui-trajectory/src/client/trajectory-preview.ts` |
+| `record.ts` | `packages/client/ui-trajectory/src/client/trajectory-record.ts` |
+
+`../theme/` 以 `packages/client/ui-theme/src/styles` 的五个 token 样式表为来源,并将作用域限制到轨迹宿主;[`../theme/PROVENANCE.zh.md`](../theme/PROVENANCE.zh.md) 记录源版本和调整。[`../primitives/PROVENANCE.zh.md`](../primitives/PROVENANCE.zh.md) 记录本地复制的 React 基础组件。JiuwenSwarm 在构建或运行时不会解析上游 workspace 包。
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/model.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/model.ts
new file mode 100644
index 0000000000..e3b418afe5
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/model.ts
@@ -0,0 +1,138 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Standalone trajectory read model.
+ *
+ * Adapted from `packages/client/ui-trajectory/src/client/layout.ts` under the
+ * repository MIT license. This file deliberately contains no DSH runtime or
+ * React types; OTel projectors publish this closed model to the UI.
+ */
+
+import type { TrajectoryCell } from './record.ts'
+
+/** Provider request settings displayed by the request inspector. */
+export interface TrajectoryRequestConfig {
+ provider: string
+ model: string
+ purpose?: string
+ thinking?: string
+ reasoningEffort?: string
+ temperature?: number
+ topP?: number
+ maxTokens?: number
+ stop?: readonly string[]
+ stream?: boolean
+}
+
+/** Correlation, response, cost, and trace facts shown outside request options. */
+export interface TrajectoryRecordedFacts {
+ correlation?: {
+ sessionId?: string
+ requestId?: string
+ runId?: string
+ turnId?: string
+ }
+ agent?: {
+ id?: string
+ name?: string
+ version?: string
+ description?: string
+ mode?: string
+ }
+ response?: {
+ id?: string
+ model?: string
+ finishReasons?: readonly string[]
+ totalLatencyMs?: number
+ timePerOutputTokenMs?: number
+ promptTokenIds?: unknown
+ completionTokenIds?: unknown
+ logprobs?: unknown
+ parserResult?: unknown
+ providerMetadata?: unknown
+ }
+ cost?: {
+ input?: number
+ output?: number
+ total?: number
+ }
+ trace?: {
+ root?: boolean
+ schemaVersion?: string
+ complete?: boolean
+ forcedClose?: boolean
+ }
+}
+
+/** One tool definition in the effective model-visible tool catalog. */
+export interface TrajectoryToolSchema {
+ name: string
+ description: string
+ parameters: object | unknown[]
+}
+
+/** Effective prompt state displayed by SYSTEM records. */
+export interface TrajectoryPromptSnapshot {
+ config: TrajectoryRequestConfig
+ system: string
+ tools: readonly TrajectoryToolSchema[]
+}
+
+/** One Message or Step group inside a turn. */
+export interface TrajectoryGroupModel {
+ title: string
+ description?: string
+ cells: readonly TrajectoryCell[]
+}
+
+/** One sticky turn, or a standalone compaction section between turns. */
+export interface TrajectoryTurnModel {
+ turn: number | null
+ groups: readonly TrajectoryGroupModel[]
+}
+
+/** Token buckets displayed for one request or a loaded-window prefix. */
+export interface TrajectoryUsage {
+ input?: number
+ cacheRead?: number
+ cacheWrite?: number
+ output?: number
+ reasoning?: number
+ total?: number
+}
+
+/** Request-inspector fields shared by generation and compaction. */
+interface TrajectoryRequestBase {
+ /** Stable identity of one physical model request, independent from its Step group. */
+ recordId?: string
+ seq?: number
+ group: string
+ number: number
+ status?: 'complete' | 'running' | 'error'
+ startedAt?: number
+ completedAt?: number | null
+ error?: string
+ retry?: number
+ maxRetries?: number
+ retryDelayMs?: number
+ resultSeq?: number
+ provider?: string
+ model?: string
+ requestConfig?: TrajectoryRequestConfig
+ recordedFacts?: TrajectoryRecordedFacts
+ usage?: TrajectoryUsage
+ cumulativeUsage?: TrajectoryUsage
+}
+
+/** One purpose-discriminated request paired with its display number. */
+export type TrajectoryRequest = TrajectoryRequestBase & (
+ | { purpose?: 'assistant'; turn: number; step: number }
+ | { purpose: 'compaction'; turn: number | null; step: 0 }
+)
+
+/** Snapshot consumed atomically by `TrajectoryExplorer`. */
+export interface TrajectorySnapshot {
+ turns: readonly TrajectoryTurnModel[]
+ requests?: readonly TrajectoryRequest[]
+ streamingCells?: readonly TrajectoryCell[]
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/preview.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/preview.ts
new file mode 100644
index 0000000000..c39489c120
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/preview.ts
@@ -0,0 +1,26 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Bounded Markdown-to-text projection shared by trajectory consumers.
+ * Adapted mechanically from `packages/client/ui-trajectory/src/client/trajectory-preview.ts`
+ * under the repository MIT license.
+ */
+
+import { extractMarkdownPlainText } from '../primitives/index.ts'
+
+const PREVIEW_SOURCE_CHARACTERS = 2_048
+const PREVIEW_OUTPUT_CHARACTERS = 512
+
+/**
+ * Build a bounded one-line preview without parsing the complete Markdown document.
+ * @param text - Untrusted message, reasoning, payload, or result text.
+ * @returns A compact preview capped independently from the retained source.
+ */
+export function trajectoryPreviewText(text: string): string {
+ const source = text.slice(0, PREVIEW_SOURCE_CHARACTERS)
+ const compact = extractMarkdownPlainText(source).replace(/\s+/g, ' ').trim()
+ const preview = compact.slice(0, PREVIEW_OUTPUT_CHARACTERS).trimEnd()
+ return source.length < text.length || preview.length < compact.length
+ ? `${preview}…`
+ : preview
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/record.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/record.ts
new file mode 100644
index 0000000000..bc29411bc8
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/record.ts
@@ -0,0 +1,117 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Standalone trajectory record model and formatters.
+ *
+ * Adapted from `packages/client/ui-trajectory/src/client/trajectory-record.ts`
+ * under the repository MIT license.
+ */
+
+import type { TrajectoryPromptSnapshot } from './model.ts'
+
+/** Closed set of record kinds rendered by the trajectory UI. */
+export type TrajectoryCellKind =
+ | 'system'
+ | 'user'
+ | 'context'
+ | 'compacted'
+ | 'message'
+ | 'tool'
+ | 'subtool'
+
+/** Recorded inputs needed to derive assistant TTFT and decode throughput. */
+export interface AssistantMetricDetail {
+ timingRecorded: boolean
+ stepStartTime: number | null
+ firstTokenTime: number | null
+ completedTime: number | null
+ usageProvided: boolean
+ outputTokens: number | null
+}
+
+/** One source content block preserved in model order for the inspector. */
+export interface TrajectorySourceBlock {
+ type: string
+ content: string
+ imageSrc?: string
+ imageAlt?: string
+ callId?: string
+ toolName?: string
+}
+
+/** Data for one projected trajectory record. */
+export interface TrajectoryCell {
+ index: number
+ recordId?: string
+ /** Physical model request owning this row; several requests may share one Step. */
+ requestRecordId?: string
+ kind: TrajectoryCellKind
+ /** Explicit lifecycle; payload capture policy never determines completion. */
+ status?: 'complete' | 'running' | 'error'
+ text: string
+ previewMarkdown?: string
+ opensTurn?: boolean
+ sourceSeq?: number
+ messageSource?: unknown
+ /** Original one-Span OTLP export request for the generic OTel inspector. */
+ traceDetail?: unknown
+ requestOnly?: boolean
+ inputDetail?: string
+ promptDetail?: TrajectoryPromptSnapshot
+ previousPromptDetail?: TrajectoryPromptSnapshot
+ outputDetail?: string
+ thinkingDetail?: string
+ sourceBlocks?: readonly TrajectorySourceBlock[]
+ outputBlocks?: readonly TrajectorySourceBlock[]
+ schemaDetail?: string
+ assistantMetrics?: AssistantMetricDetail
+ result?: string
+ resultPreviewMarkdown?: string
+ callId?: string
+ isError?: boolean
+ timeSeconds: number | null
+ startedAt?: number | null
+ input?: number
+ cacheRead?: number
+ cacheWrite?: number
+ output?: number
+ think?: number
+ total?: number
+}
+
+/** Compatibility name retained by the mechanically adapted DSH components. */
+export type TrajectoryCellProps = TrajectoryCell
+
+/** Resolve the identity that survives prepending older projected records. */
+export function trajectoryRecordId(cell: TrajectoryCell): string {
+ if (cell.recordId !== undefined) return cell.recordId
+ if (cell.callId !== undefined) return `${cell.kind}\u0000call\u0000${cell.callId}`
+ if (cell.sourceSeq !== undefined) return `${cell.kind}\u0000seq\u0000${cell.sourceSeq}`
+ return `${cell.kind}\u0000index\u0000${cell.index}`
+}
+
+/** Format a duration in milliseconds, or an em dash when unknown. */
+export function formatDurationMillis(milliseconds: number | null): string {
+ if (milliseconds === null || !Number.isFinite(milliseconds)) return '—'
+ const integer = String(Math.round(milliseconds))
+ return `${integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',')} ms`
+}
+
+/** Format elapsed seconds as an integer-millisecond label. */
+export function formatElapsedSeconds(seconds: number | null): string {
+ return formatDurationMillis(seconds === null ? null : seconds * 1_000)
+}
+
+/** Resolve a running record's open interval without mutating its recorded facts. */
+export function liveElapsedSeconds(
+ cell: TrajectoryCell,
+ nowMilliseconds: number,
+): number | null {
+ if (cell.timeSeconds !== null) return cell.timeSeconds
+ if (cell.status !== 'running'
+ || cell.startedAt === null
+ || cell.startedAt === undefined
+ || !Number.isFinite(cell.startedAt)
+ || !Number.isFinite(nowMilliseconds)) return null
+ return Math.max(0, nowMilliseconds - cell.startedAt) / 1_000
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/search-index.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/search-index.ts
new file mode 100644
index 0000000000..48dcd73043
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/search-index.ts
@@ -0,0 +1,139 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Incremental full-text index for the trajectory ledger.
+ * Adapted mechanically from `packages/client/ui-trajectory/src/client/trajectory-search-index.ts`
+ * under the repository MIT license.
+ */
+
+import type { TrajectoryTurnModel } from './model.ts'
+import type { TrajectoryCellProps } from './record.ts'
+import { trajectoryRecordId } from './record.ts'
+import { trajectoryPreviewText } from './preview.ts'
+
+interface SearchEntry {
+ readonly sources: readonly string[]
+ readonly text: string
+}
+
+function searchableJson(value: unknown): string {
+ if (value === undefined) return ''
+ try {
+ return JSON.stringify(value)
+ } catch {
+ return ''
+ }
+}
+
+function sameSources(left: readonly string[], right: readonly string[]): boolean {
+ return left.length === right.length && left.every((value, index) => value === right[index])
+}
+
+function markdownPreview(cell: TrajectoryCellProps): string {
+ if (cell.previewMarkdown === undefined) return ''
+ const preview = trajectoryPreviewText(cell.previewMarkdown)
+ if (cell.text === '') return preview
+ return preview === '' ? cell.text : `${cell.text} · ${preview}`
+}
+
+function resultPreview(cell: TrajectoryCellProps): string {
+ return cell.resultPreviewMarkdown === undefined
+ ? cell.result ?? ''
+ : trajectoryPreviewText(cell.resultPreviewMarkdown)
+}
+
+function recordSources(
+ turn: number | null,
+ group: string,
+ cell: TrajectoryCellProps,
+): readonly string[] {
+ const blocks = [
+ ...(cell.sourceBlocks ?? []),
+ ...(cell.outputBlocks ?? []),
+ ]
+ return [
+ turn === null ? 'between turns' : `turn ${turn}`,
+ group,
+ cell.kind,
+ cell.kind === 'message' ? 'assistant' : '',
+ cell.text,
+ cell.previewMarkdown ?? '',
+ cell.inputDetail ?? '',
+ cell.outputDetail ?? '',
+ cell.thinkingDetail ?? '',
+ cell.schemaDetail ?? '',
+ cell.result ?? '',
+ cell.resultPreviewMarkdown ?? '',
+ cell.callId ?? '',
+ ...blocks.flatMap(block => [
+ block.type,
+ block.content,
+ block.callId ?? '',
+ block.toolName ?? '',
+ block.imageAlt ?? '',
+ ]),
+ searchableJson(cell.messageSource),
+ searchableJson(cell.promptDetail),
+ searchableJson(cell.previousPromptDetail),
+ ]
+}
+
+/** View-local index that reparses Markdown only when one record's source changes. */
+export class TrajectorySearchIndex {
+ private readonly entries = new Map<string, SearchEntry>()
+ private layouts: readonly (readonly TrajectoryTurnModel[])[] | undefined
+
+ /**
+ * Incrementally synchronize one or more current trajectory layout slices.
+ * @param layouts - Finalized and optional streaming layouts from the same view.
+ * @returns Whether the indexed layout version changed.
+ */
+ update(layouts: readonly (readonly TrajectoryTurnModel[])[]): boolean {
+ if (this.layouts === layouts) return false
+ this.layouts = layouts
+ const seen = new Set<string>()
+ for (const turns of layouts) {
+ for (const turn of turns) {
+ for (const group of turn.groups) {
+ for (const cell of group.cells) {
+ if (cell.requestOnly === true) continue
+ const id = trajectoryRecordId(cell)
+ const sources = recordSources(turn.turn, group.title, cell)
+ const previous = this.entries.get(id)
+ const entry = previous !== undefined && sameSources(previous.sources, sources)
+ ? previous
+ : {
+ sources,
+ text: [
+ ...sources,
+ markdownPreview(cell),
+ resultPreview(cell),
+ ].join('\n').toLocaleLowerCase(),
+ }
+ this.entries.set(id, entry)
+ seen.add(id)
+ }
+ }
+ }
+ }
+ for (const id of this.entries.keys()) {
+ if (!seen.has(id)) this.entries.delete(id)
+ }
+ return true
+ }
+
+ /**
+ * Match a query against the latest committed index version.
+ * @param query - Space-separated case-insensitive search terms.
+ * @returns Matching stable record identities, or `null` without a query.
+ */
+ search(query: string): ReadonlySet<string> | null {
+ const terms = query.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)
+ if (terms.length === 0) return null
+ const matches = new Set<string>()
+ for (const [id, entry] of this.entries) {
+ if (terms.every(term => entry.text.includes(term))) matches.add(id)
+ }
+ return matches
+ }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/timeline.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/timeline.ts
new file mode 100644
index 0000000000..5967842d7d
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/timeline.ts
@@ -0,0 +1,216 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Operation-sequence and recorded-time projections for the trajectory overview.
+ * Adapted mechanically from `packages/client/ui-trajectory/src/client/timeline.ts`
+ * under the repository MIT license.
+ */
+
+import type { TrajectoryTurnModel } from './model.ts'
+import { formatDurationMillis, liveElapsedSeconds } from './record.ts'
+import type { TrajectoryCellKind, TrajectoryCellProps } from './record.ts'
+
+/** Horizontal projection used by the trajectory timeline. */
+export type TrajectoryTimelineMode = 'sequence' | 'duration' | 'time' | 'actual'
+
+/** Inclusive selection in the active timeline projection's domain. */
+export interface TrajectoryTimeRange {
+ start: number
+ end: number
+}
+
+/** One ledger record projected into the active timeline domain. */
+export interface TrajectoryTimelineSpan extends TrajectoryTimeRange {
+ index: number
+ isError: boolean
+ kind: TrajectoryCellKind
+ label: string
+ lane: number
+}
+
+/** One turn boundary in the active timeline domain. */
+export interface TrajectoryTimelineTurnBoundary {
+ turn: number
+ time: number
+}
+
+/** Full-domain model used by the overview. */
+export interface TrajectoryTimelineModel extends TrajectoryTimeRange {
+ spans: readonly TrajectoryTimelineSpan[]
+ turnBoundaries: readonly TrajectoryTimelineTurnBoundary[]
+}
+
+/**
+ * Format a timeline duration as an integer-millisecond label.
+ * @param milliseconds - Non-negative duration in milliseconds.
+ * @returns Millisecond label with thousands separators.
+ */
+export function formatTimelineOffset(milliseconds: number): string {
+ return formatDurationMillis(milliseconds)
+}
+
+function laneFor(kind: TrajectoryCellKind): number {
+ if (kind === 'tool' || kind === 'subtool') return 2
+ if (kind === 'message' || kind === 'compacted') return 1
+ return 0
+}
+
+function finite(value: number | null | undefined): value is number {
+ return value !== null && value !== undefined && Number.isFinite(value)
+}
+
+function cellRange(
+ cell: TrajectoryCellProps,
+ nowMilliseconds: number | undefined,
+): TrajectoryTimeRange | null {
+ if (!finite(cell.startedAt)) return null
+ const elapsed = nowMilliseconds === undefined
+ ? cell.timeSeconds
+ : liveElapsedSeconds(cell, nowMilliseconds)
+ const durationMs = finite(elapsed)
+ ? Math.max(0, elapsed * 1_000)
+ : 0
+ return { start: cell.startedAt, end: cell.startedAt + durationMs }
+}
+
+/**
+ * Project every visible record into a stable three-lane timeline.
+ * @param turns - Unfiltered trajectory layout.
+ * @param mode - Independent equal/recorded duration and compressed/complete time projection.
+ * @returns Timeline model, or `null` when no record is visible.
+ */
+export function deriveTrajectoryTimeline(
+ turns: readonly TrajectoryTurnModel[],
+ mode: TrajectoryTimelineMode = 'sequence',
+ nowMilliseconds?: number,
+): TrajectoryTimelineModel | null {
+ if (mode !== 'sequence') {
+ return deriveTimedTimeline(
+ turns,
+ mode === 'duration' || mode === 'actual',
+ mode === 'duration',
+ nowMilliseconds,
+ )
+ }
+ const spans: TrajectoryTimelineSpan[] = []
+ const turnBoundaries: TrajectoryTimelineTurnBoundary[] = []
+
+ for (const turn of turns) {
+ const cells = turn.groups.flatMap(group =>
+ group.cells.filter(cell => cell.requestOnly !== true),
+ )
+ if (cells.length === 0) continue
+ if (turn.turn !== null) {
+ turnBoundaries.push({
+ turn: turn.turn,
+ time: spans.length,
+ })
+ }
+ spans.push(...cells.map((cell, offset): TrajectoryTimelineSpan => ({
+ start: spans.length + offset,
+ end: spans.length + offset + 1,
+ index: cell.index,
+ isError: cell.isError === true,
+ kind: cell.kind,
+ label: cell.text,
+ lane: laneFor(cell.kind),
+ })))
+ }
+
+ if (spans.length === 0) return null
+ return {
+ start: 0,
+ end: spans.length,
+ spans,
+ turnBoundaries,
+ }
+}
+
+function deriveTimedTimeline(
+ turns: readonly TrajectoryTurnModel[],
+ actualDuration: boolean,
+ compressIdle: boolean,
+ nowMilliseconds: number | undefined,
+): TrajectoryTimelineModel | null {
+ const timedTurns = turns.flatMap((turn) => {
+ const rawSpans = turn.groups.flatMap(group =>
+ group.cells.flatMap((cell): TrajectoryTimelineSpan[] => {
+ if (cell.requestOnly === true) return []
+ const range = cellRange(cell, nowMilliseconds)
+ return range === null
+ ? []
+ : [{
+ ...range,
+ index: cell.index,
+ isError: cell.isError === true,
+ kind: cell.kind,
+ label: cell.text,
+ lane: laneFor(cell.kind),
+ }]
+ }),
+ )
+ return rawSpans.length === 0 ? [] : [{ turn: turn.turn, rawSpans }]
+ })
+ const rawSpans = timedTurns.flatMap(turn => turn.rawSpans)
+ if (rawSpans.length === 0) return null
+
+ const removedIdleBySpan = new Map<TrajectoryTimelineSpan, number>()
+ let removedIdle = 0
+ let coveredUntil: number | null = null
+ for (const span of [...rawSpans].sort((left, right) =>
+ left.start - right.start || left.end - right.end)) {
+ if (compressIdle && coveredUntil !== null && span.start > coveredUntil) {
+ removedIdle += span.start - coveredUntil
+ }
+ removedIdleBySpan.set(span, removedIdle)
+ coveredUntil = coveredUntil === null ? span.end : Math.max(coveredUntil, span.end)
+ }
+
+ const spans: TrajectoryTimelineSpan[] = []
+ const turnBoundaries: TrajectoryTimelineTurnBoundary[] = []
+ for (const turn of timedTurns) {
+ const projected = turn.rawSpans.map((span): TrajectoryTimelineSpan => {
+ const offset = removedIdleBySpan.get(span) ?? 0
+ return {
+ ...span,
+ start: span.start - offset,
+ end: (actualDuration ? span.end : span.start) - offset,
+ }
+ })
+ spans.push(...projected)
+ if (turn.turn !== null) {
+ turnBoundaries.push({
+ turn: turn.turn,
+ time: Math.min(...projected.map(span => span.start)),
+ })
+ }
+ }
+
+ return {
+ start: Math.min(...spans.map(span => span.start)),
+ end: Math.max(...spans.map(span => span.end)),
+ spans,
+ turnBoundaries,
+ }
+}
+
+/**
+ * Identify records active at any point inside an inclusive selected interval.
+ * @param turns - Unfiltered trajectory layout.
+ * @param range - Selected interval in the active projection.
+ * @param mode - Independent equal/recorded duration and compressed/complete time projection.
+ * @returns Record indexes inside the focus interval.
+ */
+export function trajectoryTimelineFocusIndexes(
+ turns: readonly TrajectoryTurnModel[],
+ range: TrajectoryTimeRange,
+ mode: TrajectoryTimelineMode = 'sequence',
+ nowMilliseconds?: number,
+): ReadonlySet<number> {
+ const model = deriveTrajectoryTimeline(turns, mode, nowMilliseconds)
+ return new Set(
+ model?.spans
+ .filter(span => span.start <= range.end && span.end >= range.start)
+ .map(span => span.index),
+ )
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/virtual-rows.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/virtual-rows.ts
new file mode 100644
index 0000000000..ea12d255a0
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/virtual-rows.ts
@@ -0,0 +1,89 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/**
+ * Pure projection from trajectory records to measurable virtual ledger rows.
+ * Adapted mechanically from `packages/client/ui-trajectory/src/client/trajectory-virtual-rows.ts`
+ * under the repository MIT license.
+ */
+
+import type { TrajectoryCellProps } from './record.ts'
+import { trajectoryRecordId } from './record.ts'
+
+const CONTENT_ROW_HEIGHT = 30
+const COLLAPSED_SUMMARY_HEIGHT = 20
+const TERMINAL_BOUNDARY_HEIGHT = 9
+
+/** Minimal record shape required by the trajectory virtual-row projection. */
+export interface VirtualizableTrajectoryRecord {
+ cell: TrajectoryCellProps
+ collapsedSummaryKind?: 'turn' | 'assistant'
+}
+
+/** One logical record retained inside a measurable virtual row. */
+export interface TrajectoryVirtualRowEntry<T extends VirtualizableTrajectoryRecord> {
+ logicalIndex: number
+ record: T
+}
+
+/** One virtualizer item, which may carry zero-height request boundaries. */
+export interface TrajectoryVirtualRow<T extends VirtualizableTrajectoryRecord> {
+ entries: readonly TrajectoryVirtualRowEntry<T>[]
+ height: number
+ key: string
+}
+
+/**
+ * Derive the DOM-safe row identity shared by React, the virtualizer, and
+ * browser scroll contracts.
+ * @param record - Display record whose identity is required.
+ * @returns Stable record identity with a suffix for synthetic fold summaries.
+ */
+export function trajectoryVirtualRecordKey(
+ record: VirtualizableTrajectoryRecord,
+): string {
+ const identity = encodeURIComponent(trajectoryRecordId(record.cell))
+ return record.collapsedSummaryKind === undefined
+ ? identity
+ : `${identity}\u0000summary\u0000${record.collapsedSummaryKind}`
+}
+
+/**
+ * Attach separator-only records to the next content row so the virtualizer
+ * never owns a zero-height item. A terminal separator retains its CSS-owned
+ * lower-marker clearance as a standalone item.
+ * @param records - Final search/fold projection in ledger order.
+ * @returns Measurable virtual rows with original logical positions retained.
+ */
+export function groupTrajectoryVirtualRows<T extends VirtualizableTrajectoryRecord>(
+ records: readonly T[],
+): readonly TrajectoryVirtualRow<T>[] {
+ const rows: TrajectoryVirtualRow<T>[] = []
+ let pending: TrajectoryVirtualRowEntry<T>[] = []
+
+ for (const [logicalIndex, record] of records.entries()) {
+ const entry = { logicalIndex, record }
+ if (record.cell.requestOnly === true) {
+ pending.push(entry)
+ continue
+ }
+ const entries = [...pending, entry]
+ pending = []
+ rows.push({
+ entries,
+ height: record.collapsedSummaryKind === undefined
+ ? CONTENT_ROW_HEIGHT
+ : COLLAPSED_SUMMARY_HEIGHT,
+ key: trajectoryVirtualRecordKey(record),
+ })
+ }
+
+ if (pending.length > 0) {
+ rows.push({
+ entries: pending,
+ height: TERMINAL_BOUNDARY_HEIGHT,
+ key: pending.map(candidate => trajectoryVirtualRecordKey(candidate.record)).join('|'),
+ })
+ }
+
+ return rows
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryArchive.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryArchive.ts
new file mode 100644
index 0000000000..9b244e3bb0
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryArchive.ts
@@ -0,0 +1,200 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Versioned browser-side archive contract for offline trajectory replay. */
+
+import type { WebConnectionState } from '../../types';
+import type { OtlpExportTraceServiceRequest } from './shared/otlp';
+import type { TrajectoryDetailRecord } from './trajectoryClient';
+import {
+ applyTrajectoryDetailRecords,
+ recordIdentity,
+ type TrajectoryRecordVersion,
+ type TrajectoryTraceBucket,
+} from './trajectoryWindow';
+
+export const TRAJECTORY_ARCHIVE_FORMAT = 'openjiuwen.trajectory.archive';
+export const TRAJECTORY_ARCHIVE_VERSION = 1;
+export const MAX_TRAJECTORY_ARCHIVE_RECORDS = 200_000;
+
+export type TrajectoryArchiveRecord = Omit<TrajectoryDetailRecord, 'ingest_seq' | 'change_seq'> & {
+ record_id: string;
+ record_revision: number;
+ lifecycle: 'running' | 'final' | 'abandoned';
+ operation: 'upsert';
+ change_seq: string;
+ observed_time_unix_nano: string;
+ trace_id: string;
+ span_id: string;
+ raw_json_base64: string;
+};
+
+export interface TrajectoryArchive {
+ format: typeof TRAJECTORY_ARCHIVE_FORMAT;
+ archive_version: typeof TRAJECTORY_ARCHIVE_VERSION;
+ session_id: string;
+ store_epoch: string;
+ revision: string;
+ exported_at: string;
+ records: TrajectoryArchiveRecord[];
+}
+
+export interface TrajectoryArchiveView {
+ records: OtlpExportTraceServiceRequest[];
+ rawRecords: TrajectoryDetailRecord[];
+ lifecycleByRecordId: Map<string, TrajectoryRecordVersion['lifecycle']>;
+ traceCount: number;
+ invalidRecordSeen: boolean;
+ rawDataByRecordId: Map<string, unknown>;
+}
+
+export interface TrajectoryReplayExit {
+ archive: null;
+ catchUpLiveRevision: boolean;
+}
+
+function object(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function validIdentity(value: unknown): value is string {
+ return typeof value === 'string' && /^[0-9a-f]{32}:[0-9a-f]{16}$/.test(value);
+}
+
+function validOtlp(value: unknown): value is OtlpExportTraceServiceRequest {
+ return object(value) && Array.isArray(value.resourceSpans);
+}
+
+function validBase64(value: unknown): value is string {
+ if (typeof value !== 'string'
+ || value.length === 0
+ || value.length % 4 !== 0
+ || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) return false;
+ try {
+ atob(value);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function parseRecord(value: unknown): TrajectoryArchiveRecord {
+ if (!object(value)
+ || !validIdentity(value.record_id)
+ || !Number.isSafeInteger(value.record_revision)
+ || Number(value.record_revision) < 0
+ || (value.lifecycle !== 'running'
+ && value.lifecycle !== 'final'
+ && value.lifecycle !== 'abandoned')
+ || value.operation !== 'upsert'
+ || typeof value.change_seq !== 'string'
+ || !/^\d+$/.test(value.change_seq)
+ || typeof value.observed_time_unix_nano !== 'string'
+ || !/^\d+$/.test(value.observed_time_unix_nano)
+ || typeof value.trace_id !== 'string'
+ || typeof value.span_id !== 'string'
+ || `${value.trace_id}:${value.span_id}` !== value.record_id
+ || !validBase64(value.raw_json_base64)
+ || typeof value.raw_valid !== 'boolean'
+ || (value.otlp !== null && !validOtlp(value.otlp))) {
+ throw new Error('Trajectory archive contains an invalid record');
+ }
+ const record = value as unknown as TrajectoryArchiveRecord;
+ if (record.otlp !== null && recordIdentity(record.otlp) !== record.record_id) {
+ throw new Error('Trajectory archive record identity does not match its OTLP span');
+ }
+ return record;
+}
+
+export function parseTrajectoryArchive(text: string): TrajectoryArchive {
+ let value: unknown;
+ try {
+ value = JSON.parse(text);
+ } catch {
+ throw new Error('Trajectory archive is not valid JSON');
+ }
+ if (!object(value)
+ || value.format !== TRAJECTORY_ARCHIVE_FORMAT
+ || value.archive_version !== TRAJECTORY_ARCHIVE_VERSION
+ || typeof value.session_id !== 'string'
+ || value.session_id.length === 0
+ || typeof value.store_epoch !== 'string'
+ || value.store_epoch.length === 0
+ || typeof value.revision !== 'string'
+ || !/^\d+$/.test(value.revision)
+ || typeof value.exported_at !== 'string'
+ || !Number.isFinite(Date.parse(value.exported_at))
+ || !Array.isArray(value.records)
+ || value.records.length > MAX_TRAJECTORY_ARCHIVE_RECORDS) {
+ throw new Error('Trajectory archive format or version is not supported');
+ }
+ const records = value.records.map(parseRecord);
+ if (new Set(records.map(record => record.record_id)).size !== records.length) {
+ throw new Error('Trajectory archive contains duplicate record identities');
+ }
+ return { ...value, records } as unknown as TrajectoryArchive;
+}
+
+function decodeRawJson(record: TrajectoryArchiveRecord): unknown {
+ try {
+ const binary = atob(record.raw_json_base64);
+ const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));
+ const text = new TextDecoder('utf-8', { fatal: false }).decode(bytes);
+ try {
+ return JSON.parse(text);
+ } catch {
+ return text;
+ }
+ } catch {
+ return record.raw_json_base64;
+ }
+}
+
+export function trajectoryArchiveView(archive: TrajectoryArchive): TrajectoryArchiveView {
+ const buckets = new Map<string, TrajectoryTraceBucket>();
+ let invalidRecordSeen = false;
+ const rawDataByRecordId = new Map<string, unknown>();
+ for (const [index, record] of archive.records.entries()) {
+ const current = buckets.get(record.trace_id);
+ const detailRecord: TrajectoryDetailRecord = {
+ ...record,
+ ingest_seq: index + 1,
+ change_seq: undefined,
+ };
+ const applied = applyTrajectoryDetailRecords(current, {
+ schema_version: 1,
+ session_id: archive.session_id,
+ trace_id: record.trace_id,
+ revision: Math.max(current?.revision ?? 0, index + 1),
+ reset: false,
+ records: [detailRecord],
+ has_more: false,
+ next_since_revision: index + 1,
+ });
+ buckets.set(record.trace_id, applied.bucket);
+ invalidRecordSeen = invalidRecordSeen || applied.invalidRecordSeen;
+ rawDataByRecordId.set(record.record_id, decodeRawJson(record));
+ }
+ return {
+ records: [...buckets.values()].flatMap(bucket => [...bucket.records.values()]),
+ rawRecords: [...buckets.values()].flatMap(bucket => [...bucket.rawRecords.values()]),
+ lifecycleByRecordId: new Map(
+ [...buckets.values()].flatMap(bucket => [...(bucket.versions ?? [])].map(
+ ([identity, version]) => [identity, version.lifecycle] as const,
+ )),
+ ),
+ traceCount: buckets.size,
+ invalidRecordSeen,
+ rawDataByRecordId,
+ };
+}
+
+export function shouldCatchUpTrajectory(
+ previous: WebConnectionState,
+ next: WebConnectionState,
+): boolean {
+ return next === 'ready' && (previous === 'reconnecting' || previous === 'closed');
+}
+
+export function exitTrajectoryReplay(archive: TrajectoryArchive | null): TrajectoryReplayExit {
+ return { archive: null, catchUpLiveRevision: archive !== null };
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryClient.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryClient.ts
new file mode 100644
index 0000000000..a4eec8a26f
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryClient.ts
@@ -0,0 +1,381 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Same-origin HTTP client for the JiuwenSwarm trajectory read API. */
+
+import { getApiBase } from '../../utils/env';
+import type { OtlpExportTraceServiceRequest } from './shared/otlp';
+
+export interface TrajectoryTraceSummary {
+ trace_id: string;
+ revision: number;
+ start_time_unix_nano: string;
+ end_time_unix_nano: string;
+ span_count: number;
+ request_id: string | null;
+ run_id: string | null;
+ agent_mode: string | null;
+ has_error: boolean;
+}
+
+export interface TrajectoryTraceListResponse {
+ schema_version: 1;
+ session_id: string;
+ store_epoch: string;
+ items: TrajectoryTraceSummary[];
+ next_cursor: string | null;
+ revision_cursor: string;
+}
+
+export interface TrajectoryRevisionListResponse {
+ schema_version: 1;
+ session_id: string;
+ store_epoch: string;
+ reset: boolean;
+ items: TrajectoryTraceSummary[];
+ next_cursor: string;
+ watermark: string;
+ has_more: boolean;
+}
+
+export interface TrajectoryDetailRecord {
+ ingest_seq: number;
+ record_id?: string;
+ record_revision?: number;
+ lifecycle?: 'provisional' | 'running' | 'completed' | 'final' | 'abandoned' | 'error';
+ operation?: 'upsert' | 'delete';
+ change_seq?: number;
+ observed_time_unix_nano?: string;
+ otlp: OtlpExportTraceServiceRequest | null;
+ raw_valid: boolean | null;
+ trace_id?: string;
+ span_id?: string;
+ raw_size_bytes?: number;
+ projection_omitted?: 'record_too_large';
+}
+
+export interface TrajectoryTraceDetailResponse {
+ schema_version: 1;
+ session_id: string;
+ trace_id: string;
+ revision: number;
+ reset: boolean;
+ records: TrajectoryDetailRecord[];
+ has_more: boolean;
+ next_since_revision: number;
+ projected_raw_bytes?: number;
+ max_projected_raw_bytes?: number;
+}
+
+export class TrajectoryApiError extends Error {
+ readonly status: number;
+ readonly code?: string;
+
+ constructor(message: string, status: number, code?: string) {
+ super(message);
+ this.name = 'TrajectoryApiError';
+ this.status = status;
+ this.code = code;
+ }
+}
+
+export async function getTrajectoryArchive(
+ sessionId: string,
+ options: { signal?: AbortSignal } = {},
+): Promise<string> {
+ const response = await fetch(trajectoryUrl(
+ `/api/trajectory/sessions/${encodeURIComponent(sessionId)}/archive`,
+ ), {
+ cache: 'no-store',
+ signal: options.signal,
+ });
+ if (!response.ok) {
+ await readResponse(response);
+ }
+ return response.text();
+}
+
+function object(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function trajectoryUrl(path: string): string {
+ return `${getApiBase()}${path}`;
+}
+
+async function readResponse(response: Response): Promise<unknown> {
+ let payload: unknown;
+ try {
+ payload = await response.json();
+ } catch {
+ payload = undefined;
+ }
+ if (response.ok) return payload;
+ const body = object(payload) ? payload : {};
+ const message = typeof body.error === 'string'
+ ? body.error
+ : `Trajectory request failed (${response.status})`;
+ throw new TrajectoryApiError(
+ message,
+ response.status,
+ typeof body.code === 'string' ? body.code : undefined,
+ );
+}
+
+function validTraceSummary(value: unknown): value is TrajectoryTraceSummary {
+ if (!object(value)) return false;
+ return typeof value.trace_id === 'string'
+ && /^[0-9a-f]{32}$/.test(value.trace_id)
+ && Number.isSafeInteger(value.revision)
+ && typeof value.start_time_unix_nano === 'string'
+ && /^\d+$/.test(value.start_time_unix_nano)
+ && typeof value.end_time_unix_nano === 'string'
+ && /^\d+$/.test(value.end_time_unix_nano)
+ && Number.isSafeInteger(value.span_count)
+ && typeof value.has_error === 'boolean';
+}
+
+function validOtlp(value: unknown): value is OtlpExportTraceServiceRequest {
+ return object(value) && Array.isArray(value.resourceSpans);
+}
+
+function validOpaqueCursor(value: unknown): value is string {
+ return typeof value === 'string' && value.length > 0 && value.length <= 512;
+}
+
+function validStoreEpoch(value: unknown): value is string {
+ return typeof value === 'string'
+ && value.trim().length > 0
+ && value.length <= 512;
+}
+
+export async function listTrajectoryTraces(
+ sessionId: string,
+ options: {
+ signal?: AbortSignal;
+ cursor?: string | null;
+ limit?: number;
+ } = {},
+): Promise<TrajectoryTraceListResponse> {
+ const query = new URLSearchParams({ limit: String(options.limit ?? 30) });
+ if (options.cursor) query.set('cursor', options.cursor);
+ const response = await fetch(trajectoryUrl(
+ `/api/trajectory/sessions/${encodeURIComponent(sessionId)}/traces?${query.toString()}`,
+ ), {
+ cache: 'no-store',
+ signal: options.signal,
+ });
+ const payload = await readResponse(response);
+ if (!object(payload)
+ || payload.schema_version !== 1
+ || payload.session_id !== sessionId
+ || !validStoreEpoch(payload.store_epoch)
+ || !Array.isArray(payload.items)
+ || !payload.items.every(validTraceSummary)
+ || (payload.next_cursor !== null && !validOpaqueCursor(payload.next_cursor))
+ || !validOpaqueCursor(payload.revision_cursor)) {
+ throw new TrajectoryApiError('Trajectory list response is invalid', 502, 'INVALID_RESPONSE');
+ }
+ return payload as unknown as TrajectoryTraceListResponse;
+}
+
+export async function listTrajectoryTraceRevisions(
+ sessionId: string,
+ options: {
+ signal?: AbortSignal;
+ afterRevision: string;
+ limit?: number;
+ },
+): Promise<TrajectoryRevisionListResponse> {
+ const query = new URLSearchParams({
+ after_revision: options.afterRevision,
+ limit: String(options.limit ?? 100),
+ });
+ const response = await fetch(trajectoryUrl(
+ `/api/trajectory/sessions/${encodeURIComponent(sessionId)}/revisions?${query.toString()}`,
+ ), {
+ cache: 'no-store',
+ signal: options.signal,
+ });
+ const payload = await readResponse(response);
+ if (!object(payload)
+ || payload.schema_version !== 1
+ || payload.session_id !== sessionId
+ || !validStoreEpoch(payload.store_epoch)
+ || typeof payload.reset !== 'boolean'
+ || !Array.isArray(payload.items)
+ || !payload.items.every(validTraceSummary)
+ || !validOpaqueCursor(payload.next_cursor)
+ || !validOpaqueCursor(payload.watermark)
+ || typeof payload.has_more !== 'boolean'
+ || (payload.reset === true
+ && (payload.items.length !== 0
+ || payload.has_more !== false
+ || payload.next_cursor !== payload.watermark))) {
+ throw new TrajectoryApiError(
+ 'Trajectory revision response is invalid',
+ 502,
+ 'INVALID_RESPONSE',
+ );
+ }
+ return payload as unknown as TrajectoryRevisionListResponse;
+}
+
+export async function getTrajectoryTrace(
+ sessionId: string,
+ traceId: string,
+ options: {
+ signal?: AbortSignal;
+ sinceRevision?: number;
+ limit?: number;
+ } = {},
+): Promise<TrajectoryTraceDetailResponse> {
+ const query = new URLSearchParams({
+ since_revision: String(options.sinceRevision ?? 0),
+ limit: String(options.limit ?? 1000),
+ });
+ const response = await fetch(trajectoryUrl(
+ `/api/trajectory/sessions/${encodeURIComponent(sessionId)}/traces/${encodeURIComponent(traceId)}?${query.toString()}`,
+ ), {
+ cache: 'no-store',
+ signal: options.signal,
+ });
+ const payload = await readResponse(response);
+ if (!object(payload)
+ || payload.schema_version !== 1
+ || payload.session_id !== sessionId
+ || payload.trace_id !== traceId
+ || !Number.isSafeInteger(payload.revision)
+ || typeof payload.reset !== 'boolean'
+ || !Array.isArray(payload.records)
+ || typeof payload.has_more !== 'boolean'
+ || !Number.isSafeInteger(payload.next_since_revision)) {
+ throw new TrajectoryApiError('Trajectory detail response is invalid', 502, 'INVALID_RESPONSE');
+ }
+ const records: TrajectoryDetailRecord[] = payload.records.map((candidate) => {
+ if (!object(candidate) || !Number.isSafeInteger(candidate.ingest_seq)) {
+ throw new TrajectoryApiError('Trajectory record response is invalid', 502, 'INVALID_RESPONSE');
+ }
+ const otlp = validOtlp(candidate.otlp) ? candidate.otlp : null;
+ const traceId = typeof candidate.trace_id === 'string'
+ && /^[0-9a-f]{32}$/.test(candidate.trace_id)
+ ? candidate.trace_id
+ : undefined;
+ const spanId = typeof candidate.span_id === 'string'
+ && /^[0-9a-f]{16}$/.test(candidate.span_id)
+ ? candidate.span_id
+ : undefined;
+ const rawSizeBytes = Number.isSafeInteger(candidate.raw_size_bytes)
+ && Number(candidate.raw_size_bytes) >= 0
+ ? Number(candidate.raw_size_bytes)
+ : undefined;
+ const projectionOmitted = candidate.projection_omitted === 'record_too_large'
+ ? candidate.projection_omitted
+ : undefined;
+ const recordId = typeof candidate.record_id === 'string'
+ && /^[0-9a-f]{32}:[0-9a-f]{16}$/.test(candidate.record_id)
+ ? candidate.record_id
+ : undefined;
+ const recordRevision = Number.isSafeInteger(candidate.record_revision)
+ && Number(candidate.record_revision) >= 0
+ ? Number(candidate.record_revision)
+ : undefined;
+ const lifecycle = candidate.lifecycle === 'provisional'
+ || candidate.lifecycle === 'running'
+ || candidate.lifecycle === 'completed'
+ || candidate.lifecycle === 'final'
+ || candidate.lifecycle === 'abandoned'
+ || candidate.lifecycle === 'error'
+ ? candidate.lifecycle
+ : undefined;
+ const operation = candidate.operation === 'upsert' || candidate.operation === 'delete'
+ ? candidate.operation
+ : undefined;
+ const changeSeq = Number.isSafeInteger(candidate.change_seq) && Number(candidate.change_seq) >= 0
+ ? Number(candidate.change_seq)
+ : undefined;
+ const observedTime = typeof candidate.observed_time_unix_nano === 'string'
+ && /^\d+$/.test(candidate.observed_time_unix_nano)
+ ? candidate.observed_time_unix_nano
+ : undefined;
+ if (recordId !== undefined
+ && traceId !== undefined
+ && spanId !== undefined
+ && recordId !== `${traceId}:${spanId}`) {
+ throw new TrajectoryApiError('Trajectory record identity is invalid', 502, 'INVALID_RESPONSE');
+ }
+ if (projectionOmitted !== undefined
+ && (traceId === undefined || spanId === undefined || rawSizeBytes === undefined)) {
+ throw new TrajectoryApiError('Trajectory record index is invalid', 502, 'INVALID_RESPONSE');
+ }
+ return {
+ ingest_seq: Number(candidate.ingest_seq),
+ otlp,
+ raw_valid: projectionOmitted !== undefined
+ ? null
+ : candidate.raw_valid === true && otlp !== null,
+ ...(recordId === undefined ? {} : { record_id: recordId }),
+ ...(recordRevision === undefined ? {} : { record_revision: recordRevision }),
+ ...(lifecycle === undefined ? {} : { lifecycle }),
+ ...(operation === undefined ? {} : { operation }),
+ ...(changeSeq === undefined ? {} : { change_seq: changeSeq }),
+ ...(observedTime === undefined ? {} : { observed_time_unix_nano: observedTime }),
+ ...(traceId === undefined ? {} : { trace_id: traceId }),
+ ...(spanId === undefined ? {} : { span_id: spanId }),
+ ...(rawSizeBytes === undefined ? {} : { raw_size_bytes: rawSizeBytes }),
+ ...(projectionOmitted === undefined ? {} : { projection_omitted: projectionOmitted }),
+ };
+ });
+ return {
+ schema_version: 1,
+ session_id: sessionId,
+ trace_id: traceId,
+ revision: Number(payload.revision),
+ reset: payload.reset,
+ records,
+ has_more: payload.has_more,
+ next_since_revision: Number(payload.next_since_revision),
+ ...(Number.isSafeInteger(payload.projected_raw_bytes)
+ ? { projected_raw_bytes: Number(payload.projected_raw_bytes) }
+ : {}),
+ ...(Number.isSafeInteger(payload.max_projected_raw_bytes)
+ ? { max_projected_raw_bytes: Number(payload.max_projected_raw_bytes) }
+ : {}),
+ };
+}
+
+export async function getTrajectoryRawRecord(
+ sessionId: string,
+ traceId: string,
+ spanId: string,
+ options: { signal?: AbortSignal } = {},
+): Promise<unknown> {
+ const response = await fetch(trajectoryUrl(
+ `/api/trajectory/sessions/${encodeURIComponent(sessionId)}`
+ + `/traces/${encodeURIComponent(traceId)}/spans/${encodeURIComponent(spanId)}/raw`,
+ ), {
+ cache: 'no-store',
+ signal: options.signal,
+ });
+ const text = await response.text();
+ if (!response.ok) {
+ let payload: unknown;
+ try {
+ payload = JSON.parse(text) as unknown;
+ } catch {
+ payload = undefined;
+ }
+ const body = object(payload) ? payload : {};
+ throw new TrajectoryApiError(
+ typeof body.error === 'string'
+ ? body.error
+ : `Trajectory request failed (${response.status})`,
+ response.status,
+ typeof body.code === 'string' ? body.code : undefined,
+ );
+ }
+ try {
+ return JSON.parse(text) as unknown;
+ } catch {
+ return text;
+ }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryLayout.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryLayout.ts
new file mode 100644
index 0000000000..92d34511b3
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryLayout.ts
@@ -0,0 +1,77 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Deterministic sizing rules for the raw OTel inspector. */
+
+export const RAW_INSPECTOR_DEFAULT_HEIGHT = 220;
+export const RAW_INSPECTOR_MIN_HEIGHT = 120;
+export const RAW_INSPECTOR_MAX_RATIO = 0.6;
+export const RAW_INSPECTOR_KEYBOARD_STEP = 16;
+
+export interface RawInspectorHeightBounds {
+ min: number;
+ max: number;
+}
+
+export interface TrajectoryHostLayout {
+ effectiveTeamAreaExpanded: boolean;
+ hideSessions: boolean;
+ hideTasks: boolean;
+}
+
+export function resolveTrajectoryHostLayout(
+ mode: string,
+ activeView: string,
+ sessionsCollapsed: boolean,
+ tasksCollapsed: boolean,
+ teamAreaExpanded: boolean,
+): TrajectoryHostLayout {
+ const trajectoryActive = mode === 'agent' && activeView === 'trajectory';
+ const hideSessions = trajectoryActive && sessionsCollapsed;
+ const hideTasks = trajectoryActive && tasksCollapsed;
+ return {
+ effectiveTeamAreaExpanded: teamAreaExpanded && !hideTasks,
+ hideSessions,
+ hideTasks,
+ };
+}
+
+export function rawInspectorHeightBounds(containerHeight: number): RawInspectorHeightBounds {
+ return {
+ min: RAW_INSPECTOR_MIN_HEIGHT,
+ max: Math.max(
+ RAW_INSPECTOR_MIN_HEIGHT,
+ Math.floor(Math.max(0, containerHeight) * RAW_INSPECTOR_MAX_RATIO),
+ ),
+ };
+}
+
+export function clampRawInspectorHeight(height: number, containerHeight: number): number {
+ const bounds = rawInspectorHeightBounds(containerHeight);
+ return Math.min(bounds.max, Math.max(bounds.min, height));
+}
+
+export function rawInspectorKeyboardHeight(
+ currentHeight: number,
+ key: string,
+ containerHeight: number,
+): number | null {
+ const bounds = rawInspectorHeightBounds(containerHeight);
+ switch (key) {
+ case 'ArrowUp':
+ return clampRawInspectorHeight(
+ currentHeight + RAW_INSPECTOR_KEYBOARD_STEP,
+ containerHeight,
+ );
+ case 'ArrowDown':
+ return clampRawInspectorHeight(
+ currentHeight - RAW_INSPECTOR_KEYBOARD_STEP,
+ containerHeight,
+ );
+ case 'Home':
+ return bounds.min;
+ case 'End':
+ return bounds.max;
+ default:
+ return null;
+ }
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryWindow.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryWindow.ts
new file mode 100644
index 0000000000..1562412a66
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectoryWindow.ts
@@ -0,0 +1,430 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+/** Transactional browser window helpers for trajectory list and detail polling. */
+
+import type {
+ OtlpExportTraceServiceRequest,
+ OtlpSpan,
+} from './shared/otlp';
+import type {
+ TrajectoryDetailRecord,
+ TrajectoryRevisionListResponse,
+ TrajectoryTraceDetailResponse,
+ TrajectoryTraceListResponse,
+ TrajectoryTraceSummary,
+} from './trajectoryClient';
+
+export interface TrajectoryTraceBucket {
+ revision: number;
+ records: Map<string, OtlpExportTraceServiceRequest>;
+ rawRecords: Map<string, TrajectoryDetailRecord>;
+ versions?: Map<string, TrajectoryRecordVersion>;
+}
+
+export interface TrajectoryRecordVersion {
+ lifecycle: 'running' | 'completed' | 'error';
+ recordRevision: number;
+}
+
+export interface TrajectoryWindowState {
+ buckets: Map<string, TrajectoryTraceBucket>;
+ storeEpoch: string | null;
+ pageCursor: string | null;
+ revisionCursor: string | null;
+ listWindowInitialized: boolean;
+ rawSelection: string;
+}
+
+export type HeadRefreshWindow = {
+ reset: true;
+ storeEpoch: string;
+} | {
+ reset: false;
+ storeEpoch: string;
+ summaries: TrajectoryTraceSummary[];
+ firstPageNextCursor: string | null;
+ revisionCursor: string;
+};
+
+export type RevisionRefreshWindow = {
+ reset: true;
+ storeEpoch: string;
+} | {
+ reset: false;
+ storeEpoch: string;
+ summaries: TrajectoryTraceSummary[];
+ nextCursor: string;
+};
+
+export interface TrajectoryOperationCoordinator {
+ currentGeneration: () => number;
+ invalidate: (restoreBusy: () => void) => number;
+ isCurrent: (generation: number) => boolean;
+ pendingLoadEarlier: (generation: number) => Promise<boolean> | null;
+ runLoadEarlier: (
+ operation: (generation: number) => Promise<boolean>,
+ setBusy: (busy: boolean) => void,
+ ) => Promise<boolean>;
+}
+
+export interface StagedTrajectoryTrace {
+ bucket: TrajectoryTraceBucket;
+ invalidRecordSeen: boolean;
+}
+
+export type TrajectoryContentMode = 'new' | 'loading' | 'blocking-error' | 'empty' | 'data';
+
+type TraceListPageLoader = (
+ cursor: string | null,
+ signal: AbortSignal,
+) => Promise<TrajectoryTraceListResponse>;
+
+type RevisionListPageLoader = (
+ afterRevision: string,
+ signal: AbortSignal,
+) => Promise<TrajectoryRevisionListResponse>;
+
+type TraceDetailPageLoader = (
+ sinceRevision: number,
+ signal: AbortSignal,
+) => Promise<TrajectoryTraceDetailResponse>;
+
+function invalidPagination(message: string): Error {
+ const error = new Error(message);
+ error.name = 'TrajectoryPaginationError';
+ return error;
+}
+
+export function createTrajectoryWindowState(): TrajectoryWindowState {
+ return {
+ buckets: new Map<string, TrajectoryTraceBucket>(),
+ storeEpoch: null,
+ pageCursor: null,
+ revisionCursor: null,
+ listWindowInitialized: false,
+ rawSelection: '',
+ };
+}
+
+export function resetTrajectoryWindowState(state: TrajectoryWindowState): void {
+ state.buckets = new Map<string, TrajectoryTraceBucket>();
+ state.storeEpoch = null;
+ state.pageCursor = null;
+ state.revisionCursor = null;
+ state.listWindowInitialized = false;
+ state.rawSelection = '';
+}
+
+export function createTrajectoryOperationCoordinator(): TrajectoryOperationCoordinator {
+ let generation = 0;
+ let earlier: { generation: number; promise: Promise<boolean> } | null = null;
+ return {
+ currentGeneration: () => generation,
+ invalidate: (restoreBusy) => {
+ generation += 1;
+ earlier = null;
+ restoreBusy();
+ return generation;
+ },
+ isCurrent: candidate => candidate === generation,
+ pendingLoadEarlier: candidate => (
+ candidate === generation && earlier?.generation === generation
+ ? earlier.promise
+ : null
+ ),
+ runLoadEarlier: (operation, setBusy) => {
+ if (earlier?.generation === generation) return earlier.promise;
+ const operationGeneration = generation;
+ setBusy(true);
+ let start: () => void = () => {};
+ const source = new Promise<boolean>((resolve, reject) => {
+ start = () => {
+ try {
+ void operation(operationGeneration).then(resolve, reject);
+ } catch (error) {
+ reject(error);
+ }
+ };
+ });
+ let promise: Promise<boolean>;
+ promise = source.finally(() => {
+ if (earlier?.promise !== promise) return;
+ earlier = null;
+ if (operationGeneration === generation) setBusy(false);
+ });
+ earlier = { generation: operationGeneration, promise };
+ start();
+ return promise;
+ },
+ };
+}
+
+export function spansOf(record: OtlpExportTraceServiceRequest): OtlpSpan[] {
+ return record.resourceSpans.flatMap(resource => (
+ resource.scopeSpans ?? []
+ ).flatMap(scope => scope.spans ?? []));
+}
+
+export function recordIdentity(record: OtlpExportTraceServiceRequest): string | null {
+ const spans = spansOf(record);
+ if (spans.length !== 1 || spans[0] === undefined) return null;
+ return `${spans[0].traceId}:${spans[0].spanId}`;
+}
+
+export function detailRecordIdentity(record: TrajectoryDetailRecord): string | null {
+ if (record.record_id !== undefined) return record.record_id;
+ if (record.trace_id !== undefined && record.span_id !== undefined) {
+ return `${record.trace_id}:${record.span_id}`;
+ }
+ return record.otlp === null ? null : recordIdentity(record.otlp);
+}
+
+export function detailRecordLifecycle(
+ record: TrajectoryDetailRecord,
+): TrajectoryRecordVersion['lifecycle'] {
+ if (record.lifecycle === 'provisional' || record.lifecycle === 'running') return 'running';
+ if (record.lifecycle === 'abandoned' || record.lifecycle === 'error') return 'error';
+ return 'completed';
+}
+
+function detailRecordRevision(record: TrajectoryDetailRecord): number {
+ return record.record_revision ?? record.change_seq ?? record.ingest_seq;
+}
+
+function terminal(lifecycle: TrajectoryRecordVersion['lifecycle']): boolean {
+ return lifecycle === 'completed' || lifecycle === 'error';
+}
+
+/** Apply one revision page with per-record latest-wins and terminal absorption. */
+export function applyTrajectoryDetailRecords(
+ current: TrajectoryTraceBucket | undefined,
+ detail: TrajectoryTraceDetailResponse,
+): StagedTrajectoryTrace {
+ let records = new Map<string, OtlpExportTraceServiceRequest>(current?.records ?? []);
+ let rawRecords = new Map<string, TrajectoryDetailRecord>(current?.rawRecords ?? []);
+ let versions = new Map<string, TrajectoryRecordVersion>(current?.versions ?? []);
+ let invalidRecordSeen = false;
+ if (detail.reset) {
+ records = new Map();
+ rawRecords = new Map();
+ versions = new Map();
+ }
+ for (const item of detail.records) {
+ const identity = detailRecordIdentity(item);
+ if (identity === null) {
+ invalidRecordSeen = true;
+ continue;
+ }
+ const incoming = {
+ lifecycle: detailRecordLifecycle(item),
+ recordRevision: detailRecordRevision(item),
+ };
+ const prior = versions.get(identity);
+ if (prior !== undefined) {
+ if (terminal(prior.lifecycle) && incoming.lifecycle === 'running') continue;
+ const incomingTerminal = terminal(incoming.lifecycle);
+ if (!incomingTerminal || terminal(prior.lifecycle)) {
+ if (incoming.recordRevision < prior.recordRevision) continue;
+ if (incoming.recordRevision === prior.recordRevision) continue;
+ }
+ }
+ if (item.operation === 'delete') {
+ records.delete(identity);
+ rawRecords.delete(identity);
+ versions.delete(identity);
+ continue;
+ }
+ versions.set(identity, incoming);
+ rawRecords.set(identity, item);
+ if (!item.raw_valid || item.otlp === null) {
+ invalidRecordSeen = true;
+ records.delete(identity);
+ continue;
+ }
+ const otlpIdentity = recordIdentity(item.otlp);
+ if (otlpIdentity !== identity) {
+ invalidRecordSeen = true;
+ continue;
+ }
+ records.set(identity, item.otlp);
+ }
+ return {
+ bucket: {
+ revision: detail.revision,
+ records,
+ rawRecords,
+ versions,
+ },
+ invalidRecordSeen,
+ };
+}
+
+export function dedupeTraceSummaries(
+ summaries: readonly TrajectoryTraceSummary[],
+): TrajectoryTraceSummary[] {
+ const byTraceId = new Map<string, TrajectoryTraceSummary>();
+ for (const summary of summaries) {
+ const current = byTraceId.get(summary.trace_id);
+ if (current === undefined || summary.revision >= current.revision) {
+ byTraceId.set(summary.trace_id, summary);
+ }
+ }
+ return [...byTraceId.values()];
+}
+
+export function selectSummariesNeedingLoad(
+ loadedRevisions: ReadonlyMap<string, number>,
+ ...summaryGroups: Array<readonly TrajectoryTraceSummary[]>
+): TrajectoryTraceSummary[] {
+ const summaries = dedupeTraceSummaries(summaryGroups.flatMap(group => [...group]));
+ return summaries.filter((summary) => {
+ const loadedRevision = loadedRevisions.get(summary.trace_id);
+ return loadedRevision === undefined || summary.revision > loadedRevision;
+ });
+}
+
+export async function collectHeadRefreshWindow(
+ loadedRevisions: ReadonlyMap<string, number>,
+ expectedStoreEpoch: string,
+ signal: AbortSignal,
+ loadPage: TraceListPageLoader,
+): Promise<HeadRefreshWindow | null> {
+ let cursor: string | null = null;
+ let firstPageNextCursor: string | null = null;
+ let revisionCursor = '';
+ const summaries: TrajectoryTraceSummary[] = [];
+ while (true) {
+ if (signal.aborted) return null;
+ const page = await loadPage(cursor, signal);
+ if (signal.aborted) return null;
+ if (page.store_epoch !== expectedStoreEpoch) {
+ return { reset: true, storeEpoch: page.store_epoch };
+ }
+ if (cursor === null) {
+ firstPageNextCursor = page.next_cursor;
+ revisionCursor = page.revision_cursor;
+ }
+ summaries.push(...page.items);
+ const overlapsLoadedWindow = page.items.some(item => loadedRevisions.has(item.trace_id));
+ if (loadedRevisions.size === 0 || overlapsLoadedWindow || page.next_cursor === null) {
+ return {
+ reset: false,
+ storeEpoch: expectedStoreEpoch,
+ summaries: dedupeTraceSummaries(summaries),
+ firstPageNextCursor,
+ revisionCursor,
+ };
+ }
+ if (page.next_cursor === cursor) {
+ throw invalidPagination('Trajectory head pagination did not advance');
+ }
+ cursor = page.next_cursor;
+ }
+}
+
+export async function collectRevisionRefreshWindow(
+ afterRevision: string,
+ expectedStoreEpoch: string,
+ signal: AbortSignal,
+ loadPage: RevisionListPageLoader,
+): Promise<RevisionRefreshWindow | null> {
+ let cursor = afterRevision;
+ let expectedWatermark: string | null = null;
+ const summaries: TrajectoryTraceSummary[] = [];
+ while (true) {
+ if (signal.aborted) return null;
+ const page = await loadPage(cursor, signal);
+ if (signal.aborted) return null;
+ if (page.reset || page.store_epoch !== expectedStoreEpoch) {
+ return { reset: true, storeEpoch: page.store_epoch };
+ }
+ if (expectedWatermark !== null && page.watermark !== expectedWatermark) {
+ throw invalidPagination('Trajectory revision watermark changed during pagination');
+ }
+ expectedWatermark = page.watermark;
+ summaries.push(...page.items);
+ if (!page.has_more) {
+ if (page.next_cursor !== page.watermark) {
+ throw invalidPagination('Trajectory revision pagination ended before its watermark');
+ }
+ return {
+ reset: false,
+ storeEpoch: expectedStoreEpoch,
+ summaries: dedupeTraceSummaries(summaries),
+ nextCursor: page.next_cursor,
+ };
+ }
+ if (page.next_cursor === cursor) {
+ throw invalidPagination('Trajectory revision pagination did not advance');
+ }
+ cursor = page.next_cursor;
+ }
+}
+
+export async function stageTrajectoryTracePages(
+ current: TrajectoryTraceBucket | undefined,
+ signal: AbortSignal,
+ loadPage: TraceDetailPageLoader,
+): Promise<StagedTrajectoryTrace | null> {
+ let sinceRevision = current?.revision ?? 0;
+ let stagedRecords = new Map<string, OtlpExportTraceServiceRequest>(
+ current?.records ?? [],
+ );
+ let stagedRawRecords = new Map<string, TrajectoryDetailRecord>(
+ current?.rawRecords ?? [],
+ );
+ let stagedVersions = new Map<string, TrajectoryRecordVersion>(current?.versions ?? []);
+ let stagedRevision = current?.revision ?? 0;
+ let invalidRecordSeen = false;
+ while (true) {
+ if (signal.aborted) return null;
+ const detail = await loadPage(sinceRevision, signal);
+ if (signal.aborted) return null;
+ if (detail.reset) {
+ stagedRecords = new Map<string, OtlpExportTraceServiceRequest>();
+ stagedRawRecords = new Map<string, TrajectoryDetailRecord>();
+ stagedVersions = new Map<string, TrajectoryRecordVersion>();
+ sinceRevision = 0;
+ }
+ const applied = applyTrajectoryDetailRecords({
+ revision: stagedRevision,
+ records: stagedRecords,
+ rawRecords: stagedRawRecords,
+ versions: stagedVersions,
+ }, detail);
+ stagedRecords = applied.bucket.records;
+ stagedRawRecords = applied.bucket.rawRecords;
+ stagedVersions = applied.bucket.versions ?? new Map();
+ invalidRecordSeen = invalidRecordSeen || applied.invalidRecordSeen;
+ stagedRevision = detail.revision;
+ if (!detail.has_more) break;
+ if (detail.next_since_revision <= sinceRevision) {
+ throw invalidPagination('Trajectory detail pagination did not advance');
+ }
+ sinceRevision = detail.next_since_revision;
+ }
+ return {
+ bucket: {
+ revision: stagedRevision,
+ records: stagedRecords,
+ rawRecords: stagedRawRecords,
+ versions: stagedVersions,
+ },
+ invalidRecordSeen,
+ };
+}
+
+export function trajectoryContentMode(input: {
+ sessionId: string;
+ loading: boolean;
+ error: string | null;
+ projectedCount: number;
+ rawCount: number;
+}): TrajectoryContentMode {
+ if (input.sessionId === 'new') return 'new';
+ const hasData = input.projectedCount > 0 || input.rawCount > 0;
+ if (input.loading && !hasData) return 'loading';
+ if (input.error !== null && !hasData) return 'blocking-error';
+ if (!hasData) return 'empty';
+ return 'data';
+}
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index 4e329fac8f..5585287e04 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -2681,5 +2681,18 @@
},
"qaSummary": {
"title": "Clarifications"
+ },
+ "trajectory": {
+ "loading": "Loading trajectory UI…",
+ "tabs": {
+ "aria": "Single-Agent content view",
+ "trajectory": "Trajectory"
+ },
+ "layout": {
+ "hideSessions": "Collapse sessions",
+ "showSessions": "Show sessions",
+ "hideTasks": "Collapse tasks",
+ "showTasks": "Show tasks"
+ }
}
}
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 23a25bac29..967bb48a6a 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -2671,5 +2671,18 @@
},
"qaSummary": {
"title": "问题澄清"
+ },
+ "trajectory": {
+ "loading": "正在加载轨迹界面…",
+ "tabs": {
+ "aria": "单 Agent 内容视图",
+ "trajectory": "轨迹"
+ },
+ "layout": {
+ "hideSessions": "收起会话栏",
+ "showSessions": "展开会话栏",
+ "hideTasks": "收起任务栏",
+ "showTasks": "展开任务栏"
+ }
}
}
diff --git a/jiuwenswarm/channels/web/frontend/tests/singleAgentSurface.test.mjs b/jiuwenswarm/channels/web/frontend/tests/singleAgentSurface.test.mjs
new file mode 100644
index 0000000000..230e26570e
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/singleAgentSurface.test.mjs
@@ -0,0 +1,266 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+
+import React, { Suspense, act, lazy, useEffect, useState } from 'react';
+import { JSDOM } from 'jsdom';
+import { createRoot } from 'react-dom/client';
+
+import { SingleAgentSurface } from '../node_modules/.cache/trajectory-host/SingleAgentSurface.mjs';
+
+test('trajectory host exposes icon-only accessible sidebar controls', () => {
+ const appSource = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');
+ const panelSource = readFileSync(
+ new URL('../src/features/trajectory/TrajectoryPanel.tsx', import.meta.url),
+ 'utf8',
+ );
+
+ assert.match(appSource, /data-testid="trajectory-toggle-sessions"[\s\S]*?<span aria-hidden="true">/);
+ assert.match(appSource, /data-testid="trajectory-toggle-tasks"[\s\S]*?<span aria-hidden="true">/);
+ assert.match(appSource, /aria-label=\{trajectorySessionsCollapsed/);
+ assert.match(appSource, /data-tooltip=\{trajectoryTasksCollapsed/);
+ assert.doesNotMatch(panelSource, /window\.setInterval/);
+ assert.doesNotMatch(panelSource, /data-testid="trajectory-refresh"/);
+ assert.match(panelSource, /data-testid="trajectory-archive-import"/);
+ assert.match(panelSource, /data-testid="trajectory-archive-export"/);
+ assert.match(panelSource, /data-testid="trajectory-archive-exit"/);
+});
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', {
+ url: 'http://localhost/',
+});
+
+globalThis.window = dom.window;
+globalThis.document = dom.window.document;
+Object.defineProperty(globalThis, 'navigator', {
+ configurable: true,
+ value: dom.window.navigator,
+});
+globalThis.HTMLElement = dom.window.HTMLElement;
+globalThis.MouseEvent = dom.window.MouseEvent;
+globalThis.IS_REACT_ACT_ENVIRONMENT = true;
+
+function click(element) {
+ element.dispatchEvent(new dom.window.MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ }));
+}
+
+test('single-Agent tabs keep chat mounted and load trajectory only after first request', async () => {
+ const counters = {
+ chatMounts: 0,
+ chatUnmounts: 0,
+ trajectoryLoads: 0,
+ trajectoryMounts: 0,
+ trajectoryUnmounts: 0,
+ };
+ const LazyTrajectoryProbe = lazy(async () => {
+ counters.trajectoryLoads += 1;
+ return {
+ default: function TrajectoryProbe() {
+ useEffect(() => {
+ counters.trajectoryMounts += 1;
+ return () => {
+ counters.trajectoryUnmounts += 1;
+ };
+ }, []);
+ return React.createElement('div', { 'data-testid': 'trajectory-probe' }, 'trace');
+ },
+ };
+ });
+
+ function ChatProbe() {
+ useEffect(() => {
+ counters.chatMounts += 1;
+ return () => {
+ counters.chatUnmounts += 1;
+ };
+ }, []);
+ return React.createElement('input', { 'data-testid': 'chat-probe' });
+ }
+
+ function Harness() {
+ const [activeView, setActiveView] = useState('chat');
+ const [trajectoryRequested, setTrajectoryRequested] = useState(false);
+ const onViewChange = (nextView) => {
+ if (nextView === 'trajectory') {
+ setTrajectoryRequested(true);
+ }
+ setActiveView(nextView);
+ };
+ return React.createElement(SingleAgentSurface, {
+ activeView,
+ chat: React.createElement(ChatProbe),
+ chatLabel: 'Chat',
+ mode: 'agent',
+ onViewChange,
+ tabListLabel: 'Single Agent surface',
+ trajectory: React.createElement(
+ Suspense,
+ { fallback: React.createElement('div', null, 'Loading') },
+ React.createElement(LazyTrajectoryProbe),
+ ),
+ trajectoryLabel: 'Trajectory',
+ trajectoryRequested,
+ });
+ }
+
+ const container = document.createElement('div');
+ document.body.append(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(React.createElement(Harness));
+ });
+
+ const originalChatInput = container.querySelector('[data-testid="chat-probe"]');
+ assert.ok(originalChatInput);
+ originalChatInput.value = 'draft stays mounted';
+ assert.equal(container.querySelectorAll('[role="tab"]').length, 2);
+ assert.equal(counters.chatMounts, 1);
+ assert.equal(counters.trajectoryLoads, 0);
+ assert.equal(container.querySelector('[data-testid="single-agent-trajectory-view"]'), null);
+
+ await act(async () => {
+ click(container.querySelector('[data-testid="single-agent-trajectory-tab"]'));
+ await Promise.resolve();
+ });
+
+ assert.equal(counters.trajectoryLoads, 1);
+ assert.equal(counters.trajectoryMounts, 1);
+ assert.equal(counters.chatMounts, 1);
+ assert.equal(counters.chatUnmounts, 0);
+ assert.equal(container.querySelector('[data-testid="chat-probe"]'), originalChatInput);
+ assert.equal(originalChatInput.value, 'draft stays mounted');
+ assert.equal(
+ container.querySelector('[data-testid="single-agent-chat-view"]').getAttribute('aria-hidden'),
+ 'true',
+ );
+
+ await act(async () => {
+ click(container.querySelector('[data-testid="single-agent-chat-tab"]'));
+ });
+
+ assert.equal(container.querySelector('[data-testid="trajectory-probe"]').textContent, 'trace');
+ assert.equal(counters.trajectoryMounts, 1);
+ assert.equal(counters.trajectoryUnmounts, 0);
+ assert.equal(
+ container.querySelector('[data-testid="single-agent-trajectory-view"]').getAttribute('aria-hidden'),
+ 'true',
+ );
+
+ await act(async () => {
+ root.unmount();
+ });
+ container.remove();
+ assert.equal(counters.chatUnmounts, 1);
+ assert.equal(counters.trajectoryUnmounts, 1);
+});
+
+test('non-Agent modes never expose tabs or mount trajectory UI', async () => {
+ let trajectoryMounts = 0;
+ function TrajectoryProbe() {
+ trajectoryMounts += 1;
+ return React.createElement('div', null, 'trace');
+ }
+
+ const container = document.createElement('div');
+ document.body.append(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(React.createElement(SingleAgentSurface, {
+ activeView: 'trajectory',
+ chat: React.createElement('div', { 'data-testid': 'chat-probe' }, 'chat'),
+ chatLabel: 'Chat',
+ mode: 'team',
+ onViewChange: () => {},
+ tabListLabel: 'Single Agent surface',
+ trajectory: React.createElement(TrajectoryProbe),
+ trajectoryLabel: 'Trajectory',
+ trajectoryRequested: true,
+ }));
+ });
+
+ assert.equal(container.querySelector('[data-testid="single-agent-surface-tabs"]'), null);
+ assert.equal(container.querySelector('[data-testid="single-agent-trajectory-view"]'), null);
+ assert.equal(
+ container.querySelector('[data-testid="single-agent-chat-view"]').getAttribute('aria-hidden'),
+ 'false',
+ );
+ assert.equal(trajectoryMounts, 0);
+
+ await act(async () => {
+ root.unmount();
+ });
+ container.remove();
+});
+
+test('trajectory layout controls retain their state while chat stays mounted', async () => {
+ function Harness() {
+ const [activeView, setActiveView] = useState('chat');
+ const [collapsed, setCollapsed] = useState(false);
+ return React.createElement(SingleAgentSurface, {
+ activeView,
+ chat: React.createElement('div', { 'data-testid': 'chat-probe' }, 'chat'),
+ chatLabel: 'Chat',
+ mode: 'agent',
+ onViewChange: setActiveView,
+ tabListLabel: 'Single Agent surface',
+ trajectory: React.createElement('div', { 'data-testid': 'trajectory-probe' }, 'trace'),
+ trajectoryControls: React.createElement('button', {
+ 'aria-pressed': collapsed,
+ 'data-testid': 'layout-control',
+ onClick: () => setCollapsed((value) => !value),
+ type: 'button',
+ }, collapsed ? 'Show sessions' : 'Collapse sessions'),
+ trajectoryLabel: 'Trajectory',
+ trajectoryRequested: true,
+ });
+ }
+
+ const container = document.createElement('div');
+ document.body.append(container);
+ const root = createRoot(container);
+ await act(async () => {
+ root.render(React.createElement(Harness));
+ });
+
+ assert.equal(container.querySelector('[data-testid="trajectory-layout-controls"]'), null);
+
+ await act(async () => {
+ click(container.querySelector('[data-testid="single-agent-trajectory-tab"]'));
+ });
+ assert.equal(
+ container.querySelector('[data-testid="layout-control"]').getAttribute('aria-pressed'),
+ 'false',
+ );
+
+ await act(async () => {
+ click(container.querySelector('[data-testid="layout-control"]'));
+ });
+ assert.equal(
+ container.querySelector('[data-testid="layout-control"]').getAttribute('aria-pressed'),
+ 'true',
+ );
+
+ await act(async () => {
+ click(container.querySelector('[data-testid="single-agent-chat-tab"]'));
+ });
+ assert.equal(container.querySelector('[data-testid="trajectory-layout-controls"]'), null);
+ assert.ok(container.querySelector('[data-testid="chat-probe"]'));
+
+ await act(async () => {
+ click(container.querySelector('[data-testid="single-agent-trajectory-tab"]'));
+ });
+ assert.equal(
+ container.querySelector('[data-testid="layout-control"]').getAttribute('aria-pressed'),
+ 'true',
+ );
+
+ await act(async () => {
+ root.unmount();
+ });
+ container.remove();
+});
diff --git a/jiuwenswarm/channels/web/frontend/tests/trajectoryLayout.test.mjs b/jiuwenswarm/channels/web/frontend/tests/trajectoryLayout.test.mjs
new file mode 100644
index 0000000000..75c7c44cff
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/trajectoryLayout.test.mjs
@@ -0,0 +1,46 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import {
+ RAW_INSPECTOR_DEFAULT_HEIGHT,
+ RAW_INSPECTOR_MIN_HEIGHT,
+ clampRawInspectorHeight,
+ rawInspectorHeightBounds,
+ rawInspectorKeyboardHeight,
+ resolveTrajectoryHostLayout,
+} from '../node_modules/.cache/trajectory-layout/trajectoryLayout.js';
+
+test('raw inspector height is clamped to its fixed minimum and container-relative maximum', () => {
+ assert.deepEqual(rawInspectorHeightBounds(600), { min: 120, max: 360 });
+ assert.equal(clampRawInspectorHeight(40, 600), RAW_INSPECTOR_MIN_HEIGHT);
+ assert.equal(clampRawInspectorHeight(500, 600), 360);
+ assert.equal(clampRawInspectorHeight(RAW_INSPECTOR_DEFAULT_HEIGHT, 600), 220);
+ assert.deepEqual(rawInspectorHeightBounds(100), { min: 120, max: 120 });
+});
+
+test('raw inspector separator supports keyboard resizing and ignores unrelated keys', () => {
+ assert.equal(rawInspectorKeyboardHeight(220, 'ArrowUp', 600), 236);
+ assert.equal(rawInspectorKeyboardHeight(220, 'ArrowDown', 600), 204);
+ assert.equal(rawInspectorKeyboardHeight(220, 'Home', 600), 120);
+ assert.equal(rawInspectorKeyboardHeight(220, 'End', 600), 360);
+ assert.equal(rawInspectorKeyboardHeight(220, 'Escape', 600), null);
+ assert.equal(rawInspectorKeyboardHeight(355, 'ArrowUp', 600), 360);
+ assert.equal(rawInspectorKeyboardHeight(125, 'ArrowDown', 600), 120);
+});
+
+test('sidebar suppression applies only to the single-Agent trajectory view', () => {
+ assert.deepEqual(
+ resolveTrajectoryHostLayout('agent', 'trajectory', true, true, true),
+ { hideSessions: true, hideTasks: true, effectiveTeamAreaExpanded: false },
+ );
+ assert.deepEqual(
+ resolveTrajectoryHostLayout('agent', 'chat', true, true, true),
+ { hideSessions: false, hideTasks: false, effectiveTeamAreaExpanded: true },
+ );
+ assert.deepEqual(
+ resolveTrajectoryHostLayout('team', 'trajectory', true, true, true),
+ { hideSessions: false, hideTasks: false, effectiveTeamAreaExpanded: true },
+ );
+});
diff --git a/jiuwenswarm/channels/web/frontend/tests/trajectoryProjector.test.mjs b/jiuwenswarm/channels/web/frontend/tests/trajectoryProjector.test.mjs
new file mode 100644
index 0000000000..86d4f7a3d6
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/trajectoryProjector.test.mjs
@@ -0,0 +1,305 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import test from 'node:test';
+
+import { projectOtelTrajectory } from '../node_modules/.cache/trajectory-projector/projector.mjs';
+
+function fixtureUrl(name) {
+ return new URL(`../src/features/trajectory/fixtures/${name}`, import.meta.url);
+}
+
+async function fixtureRecords(name) {
+ return JSON.parse(await readFile(fixtureUrl(name), 'utf8'));
+}
+
+async function projectFixture(name) {
+ return projectOtelTrajectory(await fixtureRecords(name));
+}
+
+function cellsOf(snapshot) {
+ return snapshot.turns.flatMap(turn => (
+ turn.groups.flatMap(group => group.cells)
+ ));
+}
+
+test('Core forced-close child projects as error with its diagnostic reason', async () => {
+ const snapshot = await projectFixture('core-contract-records.json');
+ const forcedTool = cellsOf(snapshot).find(cell => (
+ cell.kind === 'tool' && cell.callId === 'call-1'
+ ));
+
+ assert.ok(forcedTool, 'authoritative tool Span should remain visible');
+ assert.equal(forcedTool.status, 'error');
+ assert.equal(forcedTool.isError, true);
+ assert.equal(forcedTool.result, 'trace_safety_flush');
+});
+
+test('standard and OpenJiuwen fields win over conflicting legacy aliases', async () => {
+ const snapshot = await projectFixture('core-contract-records.json');
+ const request = snapshot.requests?.[0];
+ const assistant = cellsOf(snapshot).find(cell => cell.kind === 'message');
+
+ assert.ok(request, 'Core generation should produce a request inspector row');
+ assert.equal(request.provider, 'openai');
+ assert.equal(request.requestConfig?.temperature, 0);
+ assert.equal(request.requestConfig?.maxTokens, 0);
+ assert.equal(request.recordedFacts?.correlation?.sessionId, 'core-session');
+ assert.deepEqual(request.recordedFacts?.response?.finishReasons, ['tool_calls']);
+ assert.equal(request.usage?.input, 0);
+ assert.equal(assistant?.text, 'Core answer');
+});
+
+test('legacy Langfuse and indexed gen_ai records remain projectable', async () => {
+ const snapshot = await projectFixture('legacy-langfuse-records.json');
+ const cells = cellsOf(snapshot);
+
+ assert.equal(cells.find(cell => cell.kind === 'system')?.text, 'legacy system');
+ assert.ok(cells.some(cell => cell.kind === 'message' && cell.text === 'langfuse answer'));
+ assert.ok(cells.some(cell => (
+ cell.kind === 'tool'
+ && cell.callId === 'call-legacy'
+ && cell.result?.includes('legacy-result')
+ )));
+ assert.ok(snapshot.requests?.some(request => (
+ request.recordedFacts?.correlation?.sessionId === 'old-openjiuwen-session'
+ && request.usage?.input === 0
+ && request.usage?.output === 4
+ )));
+});
+
+test('behavior projection tracks session prompts, repeated users, attachments, and tools', async () => {
+ const snapshot = await projectFixture('agent-loop-records.json');
+ const cells = cellsOf(snapshot);
+ const inputCells = cells.filter(cell => (
+ cell.kind === 'system' || cell.kind === 'user' || cell.kind === 'context'
+ ));
+ const tool = cells.find(cell => cell.kind === 'tool');
+ const assistantCells = cells.filter(cell => cell.kind === 'message');
+ const attachmentCells = cells.filter(cell => cell.text.includes('Dynamic context'));
+ const contextCells = cells.filter(cell => cell.kind === 'context');
+ const repeatedUserCells = cells.filter(cell => cell.text === 'Repeat question');
+ const systemCells = cells.filter(cell => cell.kind === 'system');
+
+ assert.deepEqual(systemCells.map(cell => cell.text), [
+ 'Session system v1',
+ 'Session system v2',
+ ]);
+ assert.equal(repeatedUserCells.length, 2);
+ assert.equal(cells.filter(cell => cell.text === 'New context fact').length, 1);
+ assert.equal(attachmentCells.length, 4);
+ assert.ok(attachmentCells.every(cell => cell.kind === 'context'));
+ assert.equal(contextCells.length, attachmentCells.length);
+ assert.ok(attachmentCells.every(cell => (
+ cell.messageSource.role === 'user'
+ && cell.messageSource.kind === 'prompt_attachment'
+ )));
+ assert.deepEqual(
+ attachmentCells.map(cell => cell.messageSource.inputIndex),
+ [1, 3, 5, 4],
+ );
+ assert.ok(inputCells.every(cell => cell.timeSeconds === null));
+
+ assert.ok(tool, 'authoritative tool Span should produce one tool item');
+ assert.equal(tool.callId, 'call-loop-1');
+ assert.match(tool.inputDetail, /"q": "fact"/);
+ assert.match(tool.outputDetail, /"answer": 42/);
+ assert.equal(tool.timeSeconds, 0.2);
+
+ assert.deepEqual(assistantCells.map(cell => cell.text), [
+ 'Historical output',
+ 'I will search',
+ 'The answer is 42',
+ 'Done',
+ ]);
+ assert.deepEqual(assistantCells.map(cell => cell.timeSeconds), [1, 1, 0.6, 0.7]);
+ assert.ok(inputCells.every(input => assistantCells.every(assistant => (
+ input.timeSeconds === null
+ || input.startedAt + input.timeSeconds * 1_000 <= assistant.startedAt
+ || assistant.startedAt + assistant.timeSeconds * 1_000 <= input.startedAt
+ ))));
+});
+
+test('legacy tool records without call ids use trace-local name and order fallback', async () => {
+ const records = await fixtureRecords('agent-loop-records.json');
+ const spans = records.flatMap(record => (
+ record.resourceSpans.flatMap(resource => (
+ resource.scopeSpans.flatMap(scope => scope.spans)
+ ))
+ ));
+ for (const span of spans) {
+ span.attributes = span.attributes.filter(attribute => (
+ attribute.key !== 'gen_ai.tool.call.id'
+ ));
+ for (const attribute of span.attributes) {
+ if (
+ attribute.key !== 'gen_ai.input.messages'
+ && attribute.key !== 'gen_ai.output.messages'
+ ) continue;
+ const messages = JSON.parse(attribute.value.stringValue);
+ for (const message of messages) {
+ for (const part of message.parts) delete part.id;
+ }
+ attribute.value.stringValue = JSON.stringify(messages);
+ }
+ }
+
+ const tool = cellsOf(projectOtelTrajectory(records)).find(cell => cell.kind === 'tool');
+ assert.ok(tool);
+ assert.match(tool.outputDetail, /"answer": 42/);
+});
+
+test('additive OpenJiuwen provenance identifies attachments before XML fallback', async () => {
+ const records = await fixtureRecords('agent-loop-records.json');
+ for (const record of records) {
+ for (const resource of record.resourceSpans) {
+ for (const scope of resource.scopeSpans) {
+ for (const span of scope.spans) {
+ const provenance = [];
+ for (const attribute of span.attributes) {
+ if (attribute.key !== 'gen_ai.input.messages') continue;
+ const messages = JSON.parse(attribute.value.stringValue);
+ for (const [index, message] of messages.entries()) {
+ const attachment = message.parts.some(part => (
+ part.type === 'text' && part.content?.includes('Dynamic context')
+ ));
+ if (!attachment) continue;
+ message.parts = [{ type: 'text', content: 'metadata attachment' }];
+ provenance.push({
+ request_message_index: index + 1,
+ input_message_index: index,
+ kind: 'prompt_attachment',
+ scope: 'request',
+ items: [],
+ });
+ }
+ attribute.value.stringValue = JSON.stringify(messages);
+ }
+ if (provenance.length > 0) {
+ span.attributes.push({
+ key: 'openjiuwen.gen_ai.input.message_provenance',
+ value: { stringValue: JSON.stringify(provenance) },
+ });
+ }
+ }
+ }
+ }
+ }
+
+ const attachments = cellsOf(projectOtelTrajectory(records))
+ .filter(cell => cell.text === 'metadata attachment');
+ assert.equal(attachments.length, 4);
+ assert.ok(attachments.every(cell => (
+ cell.kind === 'context'
+ && cell.messageSource.role === 'user'
+ && cell.messageSource.kind === 'prompt_attachment'
+ )));
+});
+
+test('ordered snapshots preserve reintroductions while output replay expires after one inference', async () => {
+ const snapshot = await projectFixture('behavior-edge-records.json');
+ const cells = cellsOf(snapshot);
+ const inputCells = cells.filter(cell => (
+ cell.kind === 'system' || cell.kind === 'user' || cell.kind === 'context'
+ ));
+
+ assert.deepEqual(
+ cells.filter(cell => cell.kind === 'system').map(cell => cell.text),
+ ['Stable system'],
+ );
+ assert.deepEqual(
+ cells.filter(cell => cell.kind === 'message').map(cell => cell.text),
+ ['Same output', 'Same output', 'Same output', 'Final output', 'Unique output', 'End output'],
+ );
+ assert.equal(cells.filter(cell => cell.kind === 'user' && cell.text === 'A').length, 1);
+ assert.equal(cells.filter(cell => cell.kind === 'user' && cell.text === 'B').length, 3);
+ assert.equal(cells.filter(cell => cell.kind === 'user' && cell.text === 'C').length, 1);
+ assert.deepEqual(
+ cells.filter(cell => cell.kind === 'context' && cell.text === 'Same output')
+ .map(cell => cell.messageSource.inputIndex),
+ [3],
+ );
+ assert.ok(inputCells.every(cell => cell.timeSeconds === null));
+ assert.deepEqual(
+ snapshot.requests?.map(request => request.model),
+ ['model-a', 'model-b', 'model-c', 'model-d', 'model-e', 'model-f'],
+ );
+});
+
+test('adjacent assistant replay uses stable text and tool-call projections across shape changes', async () => {
+ const snapshot = await projectFixture('output-replay-shape-records.json');
+ const contextCells = cellsOf(snapshot).filter(cell => cell.kind === 'context');
+
+ assert.deepEqual(contextCells.map(cell => cell.text), ['Reasoned answer']);
+ assert.equal(contextCells[0]?.messageSource.role, 'assistant');
+ assert.equal(contextCells[0]?.messageSource.inputIndex, 3);
+ assert.ok(contextCells.every(cell => cell.timeSeconds === null));
+});
+
+test('provisional inference projects running lifecycle without a fabricated end time', async () => {
+ const records = await fixtureRecords('standard-records.json');
+ const inferenceRecord = records.find(record => record.resourceSpans.some(resource => (
+ resource.scopeSpans.some(scope => scope.spans.some(span => (
+ span.attributes.some(attribute => (
+ attribute.key === 'openjiuwen.trajectory.record.kind'
+ && attribute.value.stringValue === 'inference'
+ ))
+ )))
+ )));
+ assert.ok(inferenceRecord);
+ const inferenceSpan = inferenceRecord.resourceSpans
+ .flatMap(resource => resource.scopeSpans)
+ .flatMap(scope => scope.spans)
+ .find(span => span.attributes.some(attribute => (
+ attribute.key === 'openjiuwen.trajectory.record.kind'
+ && attribute.value.stringValue === 'inference'
+ )));
+ assert.ok(inferenceSpan);
+ delete inferenceSpan.endTimeUnixNano;
+ const identity = `${inferenceSpan.traceId}:${inferenceSpan.spanId}`;
+ const snapshot = projectOtelTrajectory(records, {
+ lifecycleByRecordId: new Map([[identity, 'running']]),
+ });
+ const assistant = cellsOf(snapshot).find(cell => cell.recordId === `${identity}:assistant`);
+ const request = snapshot.requests?.find(candidate => candidate.status === 'running');
+
+ assert.ok(assistant);
+ assert.equal(assistant.status, 'running');
+ assert.equal(assistant.timeSeconds, null);
+ assert.equal(assistant.assistantMetrics.completedTime, null);
+ assert.ok(request);
+ assert.equal(request.completedAt, null);
+});
+
+test('every inference keeps an independent request identity inside a shared step', async () => {
+ const records = await fixtureRecords('agent-loop-records.json');
+ for (const record of records) {
+ for (const resource of record.resourceSpans) {
+ for (const scope of resource.scopeSpans) {
+ for (const span of scope.spans) {
+ if (span.name === 'llm.call') {
+ span.attributes.push({
+ key: 'openjiuwen.inference.id',
+ value: { stringValue: span.spanId },
+ });
+ }
+ for (const attribute of span.attributes) {
+ if (attribute.key !== 'openjiuwen.step.number') continue;
+ attribute.value = { intValue: '1' };
+ }
+ }
+ }
+ }
+ }
+ const snapshot = projectOtelTrajectory(records);
+ const assistants = cellsOf(snapshot).filter(cell => cell.kind === 'message');
+ const requestIds = snapshot.requests?.map(request => request.recordId) ?? [];
+
+ assert.equal(snapshot.turns[0].groups[0].title, 'Step 1');
+ assert.equal(new Set(requestIds).size, requestIds.length);
+ assert.ok(requestIds.every(recordId => typeof recordId === 'string'));
+ assert.ok(requestIds.every(recordId => recordId.includes(':inference:')));
+ assert.deepEqual(
+ assistants.map(cell => cell.requestRecordId),
+ requestIds,
+ );
+});
diff --git a/jiuwenswarm/channels/web/frontend/tests/trajectoryWindow.test.mjs b/jiuwenswarm/channels/web/frontend/tests/trajectoryWindow.test.mjs
new file mode 100644
index 0000000000..31b8ab54da
--- /dev/null
+++ b/jiuwenswarm/channels/web/frontend/tests/trajectoryWindow.test.mjs
@@ -0,0 +1,1105 @@
+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import {
+ applyTrajectoryDetailRecords,
+ collectHeadRefreshWindow,
+ collectRevisionRefreshWindow,
+ createTrajectoryOperationCoordinator,
+ createTrajectoryWindowState,
+ resetTrajectoryWindowState,
+ selectSummariesNeedingLoad,
+ stageTrajectoryTracePages,
+ trajectoryContentMode,
+} from '../node_modules/.cache/trajectory-window/trajectoryWindow.mjs';
+import {
+ getTrajectoryArchive,
+ getTrajectoryTrace,
+ listTrajectoryTraceRevisions,
+ listTrajectoryTraces,
+} from '../node_modules/.cache/trajectory-window/trajectoryClient.mjs';
+import {
+ exitTrajectoryReplay,
+ parseTrajectoryArchive,
+ shouldCatchUpTrajectory,
+ trajectoryArchiveView,
+} from '../node_modules/.cache/trajectory-window/trajectoryArchive.mjs';
+import { liveElapsedSeconds } from '../node_modules/.cache/trajectory-window/record.mjs';
+
+const SESSION_ID = 'session-1';
+const STORE_EPOCH = 'epoch-1';
+
+function hexId(value, width) {
+ return value.toString(16).padStart(width, '0');
+}
+
+function summary(value, revision = value) {
+ return {
+ trace_id: hexId(value, 32),
+ revision,
+ start_time_unix_nano: String(value * 10),
+ end_time_unix_nano: String(value * 10 + 1),
+ span_count: 1,
+ request_id: null,
+ run_id: null,
+ agent_mode: 'agent',
+ has_error: false,
+ };
+}
+
+function listPages(items) {
+ const pages = [];
+ for (let offset = 0; offset < items.length; offset += 30) {
+ pages.push(items.slice(offset, offset + 30));
+ }
+ return pages;
+}
+
+async function collectNewPrefix(newCount) {
+ const newItems = Array.from({ length: newCount }, (_, index) => summary(1 + index));
+ const oldItems = Array.from({ length: 30 }, (_, index) => summary(10_000 + index));
+ const pages = listPages([...newItems, ...oldItems]);
+ const loaded = new Map(oldItems.map(item => [item.trace_id, item.revision]));
+ const cursors = [];
+ const controller = new AbortController();
+ const window = await collectHeadRefreshWindow(
+ loaded,
+ STORE_EPOCH,
+ controller.signal,
+ async (cursor) => {
+ cursors.push(cursor);
+ const pageIndex = cursor === null ? 0 : Number(cursor.slice('page-'.length));
+ return {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: STORE_EPOCH,
+ items: pages[pageIndex],
+ next_cursor: pageIndex + 1 < pages.length ? `page-${pageIndex + 1}` : null,
+ revision_cursor: 'revision-baseline',
+ };
+ },
+ );
+ assert.ok(window);
+ return {
+ cursors,
+ selected: selectSummariesNeedingLoad(loaded, window.summaries),
+ };
+}
+
+function otlpRecord(traceId, spanId) {
+ return {
+ resourceSpans: [{
+ scopeSpans: [{
+ spans: [{
+ traceId,
+ spanId,
+ name: `span-${spanId}`,
+ }],
+ }],
+ }],
+ };
+}
+
+function backendArchiveRecord({
+ traceId = hexId(91_000, 32),
+ spanId = hexId(1, 16),
+ lifecycle = 'final',
+ otlp = otlpRecord(traceId, spanId),
+ raw = otlp,
+ rawValid = true,
+} = {}) {
+ return {
+ record_id: `${traceId}:${spanId}`,
+ trace_id: traceId,
+ span_id: spanId,
+ parent_span_id: null,
+ record_revision: 3,
+ lifecycle,
+ operation: 'upsert',
+ change_seq: '9007199254740993',
+ start_time_unix_nano: '1000000000',
+ observed_time_unix_nano: '1500000000',
+ end_time_unix_nano: lifecycle === 'running' ? '0' : '2000000000',
+ session_id: SESSION_ID,
+ request_id: null,
+ run_id: null,
+ agent_mode: 'agent',
+ schema_version: '1',
+ source: 'openjiuwen',
+ created_at: 1,
+ update_kind: lifecycle === 'final' ? 'span_end' : 'stream',
+ raw_sha256: '0'.repeat(64),
+ raw_json_base64: Buffer.from(
+ typeof raw === 'string' ? raw : JSON.stringify(raw),
+ 'utf8',
+ ).toString('base64'),
+ otlp,
+ raw_valid: rawValid,
+ };
+}
+
+function backendArchive(records) {
+ return {
+ format: 'openjiuwen.trajectory.archive',
+ archive_version: 1,
+ session_id: SESSION_ID,
+ exported_at: '2026-08-21T00:00:00Z',
+ store_epoch: STORE_EPOCH,
+ revision: '9007199254740995',
+ records,
+ };
+}
+
+test('frontend parses and replays the real backend Archive v1 wire payload', () => {
+ const finalRecord = backendArchiveRecord();
+ const invalidRecord = backendArchiveRecord({
+ spanId: hexId(2, 16),
+ lifecycle: 'abandoned',
+ otlp: null,
+ raw: '{invalid-json',
+ rawValid: false,
+ });
+ const archive = parseTrajectoryArchive(JSON.stringify(
+ backendArchive([finalRecord, invalidRecord]),
+ ));
+ const view = trajectoryArchiveView(archive);
+
+ assert.equal(archive.revision, '9007199254740995');
+ assert.equal(archive.records[0].change_seq, '9007199254740993');
+ assert.equal(view.traceCount, 1);
+ assert.equal(view.records.length, 1);
+ assert.equal(view.rawRecords.length, 2);
+ assert.deepEqual(view.rawRecords.map(record => record.ingest_seq), [1, 2]);
+ assert.equal(view.lifecycleByRecordId.get(invalidRecord.record_id), 'error');
+ assert.equal(view.rawDataByRecordId.get(invalidRecord.record_id), '{invalid-json');
+});
+
+test('archive parser rejects frontend-only draft names and non-string cursors', () => {
+ const record = backendArchiveRecord();
+ const wrongVersionField = {
+ ...backendArchive([record]),
+ archive_version: undefined,
+ format_version: 1,
+ };
+ const numericRevision = { ...backendArchive([record]), revision: 42 };
+ const numericChangeSeq = backendArchive([{ ...record, change_seq: 42 }]);
+
+ assert.throws(() => parseTrajectoryArchive(JSON.stringify(wrongVersionField)), /not supported/);
+ assert.throws(() => parseTrajectoryArchive(JSON.stringify(numericRevision)), /not supported/);
+ assert.throws(() => parseTrajectoryArchive(JSON.stringify(numericChangeSeq)), /invalid record/);
+});
+
+test('archive export client downloads the backend session archive endpoint', async () => {
+ const originalFetch = globalThis.fetch;
+ const payload = backendArchive([backendArchiveRecord()]);
+ let requestedUrl = '';
+ globalThis.fetch = async (input) => {
+ requestedUrl = String(input);
+ return new Response(JSON.stringify(payload), { status: 200 });
+ };
+ try {
+ const text = await getTrajectoryArchive('session / one');
+ assert.equal(parseTrajectoryArchive(text).records.length, 1);
+ assert.match(requestedUrl, /\/sessions\/session%20%2F%20one\/archive$/);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test('only a recovered websocket connection triggers revision catch-up', () => {
+ assert.equal(shouldCatchUpTrajectory('reconnecting', 'ready'), true);
+ assert.equal(shouldCatchUpTrajectory('closed', 'ready'), true);
+ assert.equal(shouldCatchUpTrajectory('connecting', 'ready'), false);
+ assert.equal(shouldCatchUpTrajectory('ready', 'ready'), false);
+ assert.equal(shouldCatchUpTrajectory('ready', 'reconnecting'), false);
+});
+
+test('exiting browser-only replay requests one live revision catch-up', () => {
+ const archive = parseTrajectoryArchive(JSON.stringify(
+ backendArchive([backendArchiveRecord()]),
+ ));
+
+ assert.deepEqual(exitTrajectoryReplay(archive), {
+ archive: null,
+ catchUpLiveRevision: true,
+ });
+ assert.deepEqual(exitTrajectoryReplay(null), {
+ archive: null,
+ catchUpLiveRevision: false,
+ });
+});
+
+function projectedRecord(ingestSeq, traceValue = 70_000) {
+ const traceId = hexId(traceValue, 32);
+ const spanId = hexId(ingestSeq, 16);
+ return {
+ ingest_seq: ingestSeq,
+ trace_id: traceId,
+ span_id: spanId,
+ raw_size_bytes: 256,
+ otlp: otlpRecord(traceId, spanId),
+ raw_valid: true,
+ };
+}
+
+function detailPage({
+ revision,
+ records,
+ hasMore,
+ nextSinceRevision,
+}) {
+ return {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ trace_id: hexId(70_000, 32),
+ revision,
+ reset: false,
+ records,
+ has_more: hasMore,
+ next_since_revision: nextSinceRevision,
+ };
+}
+
+test('head refresh crosses the page boundary for 31 new traces', async () => {
+ const result = await collectNewPrefix(31);
+
+ assert.deepEqual(result.cursors, [null, 'page-1']);
+ assert.equal(result.selected.length, 31);
+ assert.equal(new Set(result.selected.map(item => item.trace_id)).size, 31);
+});
+
+test('head refresh crosses three fixed-size pages for 61 new traces', async () => {
+ const result = await collectNewPrefix(61);
+
+ assert.deepEqual(result.cursors, [null, 'page-1', 'page-2']);
+ assert.equal(result.selected.length, 61);
+ assert.equal(new Set(result.selected.map(item => item.trace_id)).size, 61);
+});
+
+test('revision feed finds a late update for an already loaded old trace', async () => {
+ const oldTrace = summary(80_000, 10);
+ const unchangedTrace = summary(80_001, 20);
+ const newTrace = summary(80_002, 1);
+ const loaded = new Map([
+ [oldTrace.trace_id, oldTrace.revision],
+ [unchangedTrace.trace_id, unchangedTrace.revision],
+ ]);
+ const requestedCursors = [];
+ const controller = new AbortController();
+ const revisions = await collectRevisionRefreshWindow(
+ 'revision-10',
+ STORE_EPOCH,
+ controller.signal,
+ async (cursor) => {
+ requestedCursors.push(cursor);
+ if (cursor === 'revision-10') {
+ return {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: STORE_EPOCH,
+ reset: false,
+ items: [{ ...oldTrace, revision: 11 }, newTrace],
+ next_cursor: 'revision-page-1',
+ watermark: 'revision-30',
+ has_more: true,
+ };
+ }
+ return {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: STORE_EPOCH,
+ reset: false,
+ items: [{ ...oldTrace, revision: 12 }, unchangedTrace],
+ next_cursor: 'revision-30',
+ watermark: 'revision-30',
+ has_more: false,
+ };
+ },
+ );
+
+ assert.ok(revisions);
+ assert.deepEqual(requestedCursors, ['revision-10', 'revision-page-1']);
+ assert.equal(revisions.nextCursor, 'revision-30');
+ const selected = selectSummariesNeedingLoad(loaded, revisions.summaries);
+ assert.deepEqual(
+ selected.map(item => [item.trace_id, item.revision]),
+ [[oldTrace.trace_id, 12], [newTrace.trace_id, 1]],
+ );
+});
+
+test('trajectory client consumes opaque list and revision cursors', async () => {
+ const requestedUrls = [];
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async (input) => {
+ const url = String(input);
+ requestedUrls.push(url);
+ if (url.includes('/revisions?')) {
+ return new Response(JSON.stringify({
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: STORE_EPOCH,
+ reset: false,
+ items: [summary(85_001, 8)],
+ next_cursor: 'revision-next',
+ watermark: 'revision-next',
+ has_more: false,
+ }), { status: 200 });
+ }
+ return new Response(JSON.stringify({
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: STORE_EPOCH,
+ items: [summary(85_000, 7)],
+ next_cursor: 'list-next',
+ revision_cursor: 'revision-baseline',
+ }), { status: 200 });
+ };
+ try {
+ const list = await listTrajectoryTraces(SESSION_ID, { limit: 30 });
+ const revisions = await listTrajectoryTraceRevisions(SESSION_ID, {
+ afterRevision: 'opaque cursor/with symbols',
+ limit: 100,
+ });
+
+ assert.equal(list.revision_cursor, 'revision-baseline');
+ assert.equal(revisions.next_cursor, 'revision-next');
+ assert.equal(requestedUrls.length, 2);
+ assert.match(requestedUrls[0], /\/traces\?limit=30$/);
+ assert.match(
+ requestedUrls[1],
+ /\/revisions\?after_revision=opaque\+cursor%2Fwith\+symbols&limit=100$/,
+ );
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test('trajectory client accepts the additive provisional detail contract', async () => {
+ const originalFetch = globalThis.fetch;
+ const record = projectedRecord(11);
+ const span = record.otlp.resourceSpans[0].scopeSpans[0].spans[0];
+ span.startTimeUnixNano = '1000000000';
+ try {
+ globalThis.fetch = async () => new Response(JSON.stringify({
+ schema_version: 1,
+ session_id: SESSION_ID,
+ trace_id: record.trace_id,
+ revision: 44,
+ reset: false,
+ records: [{
+ ...record,
+ change_seq: 44,
+ record_id: `${record.trace_id}:${record.span_id}`,
+ record_revision: 2,
+ lifecycle: 'provisional',
+ operation: 'upsert',
+ observed_time_unix_nano: '1500000000',
+ }],
+ has_more: false,
+ next_since_revision: 44,
+ }), { status: 200 });
+ const detail = await getTrajectoryTrace(SESSION_ID, record.trace_id);
+
+ assert.equal(detail.records[0].lifecycle, 'provisional');
+ assert.equal(detail.records[0].record_revision, 2);
+ assert.equal(detail.records[0].change_seq, 44);
+ assert.equal(detail.records[0].record_id, `${record.trace_id}:${record.span_id}`);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+test('trajectory client rejects missing, blank, and oversized epochs plus missing reset', async () => {
+ const originalFetch = globalThis.fetch;
+ const state = populatedWindowState();
+ const invalidPayloads = [
+ {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ items: [],
+ next_cursor: null,
+ revision_cursor: 'revision-baseline',
+ },
+ {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: ' ',
+ items: [],
+ next_cursor: null,
+ revision_cursor: 'revision-baseline',
+ },
+ {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: 'x'.repeat(513),
+ items: [],
+ next_cursor: null,
+ revision_cursor: 'revision-baseline',
+ },
+ {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: STORE_EPOCH,
+ items: [],
+ next_cursor: 'revision-baseline',
+ watermark: 'revision-baseline',
+ has_more: false,
+ },
+ ];
+ try {
+ for (let index = 0; index < invalidPayloads.length; index += 1) {
+ globalThis.fetch = async () => new Response(JSON.stringify(invalidPayloads[index]), {
+ status: 200,
+ });
+ const request = index < 3
+ ? listTrajectoryTraces(SESSION_ID)
+ : listTrajectoryTraceRevisions(SESSION_ID, {
+ afterRevision: 'revision-baseline',
+ });
+ await assert.rejects(request, error => error.code === 'INVALID_RESPONSE');
+ assert.equal(state.buckets.size, 1);
+ assert.equal(state.storeEpoch, STORE_EPOCH);
+ assert.equal(state.pageCursor, 'list-page-2');
+ assert.equal(state.revisionCursor, 'revision-9');
+ assert.notEqual(state.rawSelection, '');
+ }
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
+
+function populatedWindowState() {
+ const state = createTrajectoryWindowState();
+ const record = projectedRecord(1);
+ const identity = `${record.trace_id}:${record.span_id}`;
+ state.buckets.set(record.trace_id, {
+ revision: 9,
+ records: new Map([[identity, record.otlp]]),
+ rawRecords: new Map([[identity, record]]),
+ });
+ state.storeEpoch = STORE_EPOCH;
+ state.pageCursor = 'list-page-2';
+ state.revisionCursor = 'revision-9';
+ state.listWindowInitialized = true;
+ state.rawSelection = identity;
+ return state;
+}
+
+function assertWindowReset(state) {
+ assert.equal(state.buckets.size, 0);
+ assert.equal(state.storeEpoch, null);
+ assert.equal(state.pageCursor, null);
+ assert.equal(state.revisionCursor, null);
+ assert.equal(state.listWindowInitialized, false);
+ assert.equal(state.rawSelection, '');
+}
+
+test('same-epoch revision reset still fully clears the browser window', async () => {
+ const controller = new AbortController();
+ const result = await collectRevisionRefreshWindow(
+ 'revision-9',
+ STORE_EPOCH,
+ controller.signal,
+ async () => ({
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: STORE_EPOCH,
+ reset: true,
+ items: [],
+ next_cursor: 'revision-baseline',
+ watermark: 'revision-baseline',
+ has_more: false,
+ }),
+ );
+ const state = populatedWindowState();
+
+ assert.deepEqual(result, { reset: true, storeEpoch: STORE_EPOCH });
+ resetTrajectoryWindowState(state);
+ assertWindowReset(state);
+});
+
+test('partial retention epoch reset removes buckets, cursors, and raw selection', async () => {
+ const controller = new AbortController();
+ const result = await collectRevisionRefreshWindow(
+ 'revision-9',
+ STORE_EPOCH,
+ controller.signal,
+ async () => ({
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: 'epoch-after-partial-retention',
+ reset: true,
+ items: [],
+ next_cursor: 'revision-baseline',
+ watermark: 'revision-baseline',
+ has_more: false,
+ }),
+ );
+ const state = populatedWindowState();
+
+ assert.deepEqual(result, {
+ reset: true,
+ storeEpoch: 'epoch-after-partial-retention',
+ });
+ resetTrajectoryWindowState(state);
+ assertWindowReset(state);
+});
+
+test('an eligible-to-mixed epoch change yields reset and removes old trace state', async () => {
+ const controller = new AbortController();
+ const result = await collectRevisionRefreshWindow(
+ 'revision-9',
+ STORE_EPOCH,
+ controller.signal,
+ async () => ({
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: 'epoch-mixed',
+ reset: false,
+ items: [],
+ next_cursor: 'revision-baseline',
+ watermark: 'revision-baseline',
+ has_more: false,
+ }),
+ );
+ const state = populatedWindowState();
+
+ assert.deepEqual(result, { reset: true, storeEpoch: 'epoch-mixed' });
+ resetTrajectoryWindowState(state);
+ assertWindowReset(state);
+});
+
+test('a cross-page head epoch change discards every provisional summary', async () => {
+ const loaded = new Map([[summary(99_999).trace_id, 1]]);
+ const requested = [];
+ const controller = new AbortController();
+ const result = await collectHeadRefreshWindow(
+ loaded,
+ STORE_EPOCH,
+ controller.signal,
+ async (cursor) => {
+ requested.push(cursor);
+ if (cursor === null) {
+ return {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: STORE_EPOCH,
+ items: [summary(1)],
+ next_cursor: 'page-1',
+ revision_cursor: 'revision-1',
+ };
+ }
+ return {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: 'epoch-after-retention',
+ items: [],
+ next_cursor: null,
+ revision_cursor: 'revision-new',
+ };
+ },
+ );
+
+ assert.deepEqual(requested, [null, 'page-1']);
+ assert.deepEqual(result, { reset: true, storeEpoch: 'epoch-after-retention' });
+ assert.equal('summaries' in result, false);
+});
+
+test('a cross-page revision epoch change discards the fixed-window first page', async () => {
+ const requested = [];
+ const controller = new AbortController();
+ const result = await collectRevisionRefreshWindow(
+ 'revision-1',
+ STORE_EPOCH,
+ controller.signal,
+ async (cursor) => {
+ requested.push(cursor);
+ if (cursor === 'revision-1') {
+ return {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: STORE_EPOCH,
+ reset: false,
+ items: [summary(1)],
+ next_cursor: 'revision-page-1',
+ watermark: 'revision-20',
+ has_more: true,
+ };
+ }
+ return {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: 'epoch-replaced-between-pages',
+ reset: true,
+ items: [],
+ next_cursor: 'revision-new-baseline',
+ watermark: 'revision-new-baseline',
+ has_more: false,
+ };
+ },
+ );
+
+ assert.deepEqual(requested, ['revision-1', 'revision-page-1']);
+ assert.deepEqual(result, {
+ reset: true,
+ storeEpoch: 'epoch-replaced-between-pages',
+ });
+ assert.equal('summaries' in result, false);
+});
+
+test('load-earlier has one panel-level flight for two synchronous entry points', async () => {
+ const coordinator = createTrajectoryOperationCoordinator();
+ const busy = [];
+ let calls = 0;
+ let resolveRequest;
+ const request = new Promise(resolve => {
+ resolveRequest = resolve;
+ });
+ const operation = async () => {
+ calls += 1;
+ return request;
+ };
+
+ const timelinePromise = coordinator.runLoadEarlier(operation, value => busy.push(value));
+ const tablePromise = coordinator.runLoadEarlier(operation, value => busy.push(value));
+
+ assert.equal(timelinePromise, tablePromise);
+ assert.equal(calls, 1);
+ assert.deepEqual(busy, [true]);
+ resolveRequest(true);
+ assert.equal(await timelinePromise, true);
+ assert.deepEqual(busy, [true, false]);
+});
+
+test('head refresh waits for the shared load-earlier flight before reading its cursor', async () => {
+ const coordinator = createTrajectoryOperationCoordinator();
+ let pageCursor = 'list-page-2';
+ let earlierCalls = 0;
+ let resolveEarlierRequest;
+ const earlierRequest = new Promise(resolve => {
+ resolveEarlierRequest = resolve;
+ });
+ const earlierPromise = coordinator.runLoadEarlier(async (generation) => {
+ earlierCalls += 1;
+ const nextCursor = await earlierRequest;
+ if (!coordinator.isCurrent(generation)) return false;
+ pageCursor = nextCursor;
+ return true;
+ }, () => {});
+
+ const headGeneration = coordinator.currentGeneration();
+ const headPromise = (async () => {
+ const pendingEarlier = coordinator.pendingLoadEarlier(headGeneration);
+ if (pendingEarlier !== null) await pendingEarlier;
+ if (!coordinator.isCurrent(headGeneration)) return null;
+ return pageCursor;
+ })();
+
+ assert.equal(earlierCalls, 1);
+ let headSettled = false;
+ void headPromise.finally(() => {
+ headSettled = true;
+ });
+ await Promise.resolve();
+ assert.equal(headSettled, false);
+
+ resolveEarlierRequest('list-page-3');
+ assert.equal(await earlierPromise, true);
+ assert.equal(await headPromise, 'list-page-3');
+ assert.equal(earlierCalls, 1);
+});
+
+test('generation invalidation restores busy and rejects stale load-earlier writes', async () => {
+ const coordinator = createTrajectoryOperationCoordinator();
+ const busy = [];
+ const state = populatedWindowState();
+ const controller = new AbortController();
+ let resolveOldRequest;
+ const oldRequest = new Promise(resolve => {
+ resolveOldRequest = resolve;
+ });
+ const oldPromise = coordinator.runLoadEarlier(async (generation) => {
+ const nextCursor = await oldRequest;
+ if (controller.signal.aborted || !coordinator.isCurrent(generation)) return false;
+ state.pageCursor = nextCursor;
+ return true;
+ }, value => busy.push(value));
+
+ controller.abort();
+ coordinator.invalidate(() => busy.push(false));
+ resetTrajectoryWindowState(state);
+ assert.deepEqual(busy, [true, false]);
+
+ let resolveNewRequest;
+ const newRequest = new Promise(resolve => {
+ resolveNewRequest = resolve;
+ });
+ const newPromise = coordinator.runLoadEarlier(
+ async () => newRequest,
+ value => busy.push(value),
+ );
+ assert.deepEqual(busy, [true, false, true]);
+
+ resolveOldRequest('stale-page');
+ assert.equal(await oldPromise, false);
+ assert.equal(state.pageCursor, null);
+ assert.deepEqual(busy, [true, false, true]);
+
+ resolveNewRequest(true);
+ assert.equal(await newPromise, true);
+ assert.deepEqual(busy, [true, false, true, false]);
+});
+
+test('a failed revision page yields no advanced cursor and retries from the baseline', async () => {
+ const controller = new AbortController();
+ const requestedCursors = [];
+ await assert.rejects(
+ collectRevisionRefreshWindow(
+ 'revision-baseline',
+ STORE_EPOCH,
+ controller.signal,
+ async (cursor) => {
+ requestedCursors.push(cursor);
+ if (cursor === 'revision-baseline') {
+ return {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: STORE_EPOCH,
+ reset: false,
+ items: [summary(86_000, 2)],
+ next_cursor: 'revision-page-1',
+ watermark: 'revision-watermark',
+ has_more: true,
+ };
+ }
+ throw new Error('revision page two failed');
+ },
+ ),
+ /revision page two failed/,
+ );
+
+ const retried = await collectRevisionRefreshWindow(
+ 'revision-baseline',
+ STORE_EPOCH,
+ controller.signal,
+ async (cursor) => {
+ requestedCursors.push(cursor);
+ return {
+ schema_version: 1,
+ session_id: SESSION_ID,
+ store_epoch: STORE_EPOCH,
+ reset: false,
+ items: [summary(86_000, 3)],
+ next_cursor: 'revision-watermark',
+ watermark: 'revision-watermark',
+ has_more: false,
+ };
+ },
+ );
+
+ assert.ok(retried);
+ assert.deepEqual(requestedCursors, [
+ 'revision-baseline',
+ 'revision-page-1',
+ 'revision-baseline',
+ ]);
+ assert.equal(retried.nextCursor, 'revision-watermark');
+});
+
+test('head and revision windows deduplicate one trace at its highest revision', () => {
+ const target = summary(90_000, 3);
+ const selected = selectSummariesNeedingLoad(
+ new Map([[target.trace_id, 2]]),
+ [target, target],
+ [{ ...target, revision: 4 }, { ...target, revision: 4 }],
+ );
+
+ assert.equal(selected.length, 1);
+ assert.equal(selected[0].revision, 4);
+});
+
+test('detail pages stage 1001 records and retain an oversize raw descriptor', async () => {
+ const current = {
+ revision: 0,
+ records: new Map(),
+ rawRecords: new Map(),
+ };
+ const firstRecords = Array.from({ length: 1000 }, (_, index) => projectedRecord(index + 1));
+ const traceId = hexId(70_000, 32);
+ const oversize = {
+ ingest_seq: 1001,
+ trace_id: traceId,
+ span_id: hexId(1001, 16),
+ raw_size_bytes: 8_388_608,
+ otlp: null,
+ raw_valid: null,
+ projection_omitted: 'record_too_large',
+ };
+ let resolveSecondPage;
+ let secondPageStarted;
+ const secondPageStartedPromise = new Promise(resolve => {
+ secondPageStarted = resolve;
+ });
+ const secondPagePromise = new Promise(resolve => {
+ resolveSecondPage = resolve;
+ });
+ const controller = new AbortController();
+ let calls = 0;
+ const stagedPromise = stageTrajectoryTracePages(
+ current,
+ controller.signal,
+ async (sinceRevision) => {
+ calls += 1;
+ if (calls === 1) {
+ assert.equal(sinceRevision, 0);
+ return detailPage({
+ revision: 1001,
+ records: firstRecords,
+ hasMore: true,
+ nextSinceRevision: 1000,
+ });
+ }
+ assert.equal(sinceRevision, 1000);
+ secondPageStarted();
+ return secondPagePromise;
+ },
+ );
+
+ await secondPageStartedPromise;
+ assert.equal(current.records.size, 0);
+ assert.equal(current.rawRecords.size, 0);
+ assert.equal(current.revision, 0);
+ resolveSecondPage(detailPage({
+ revision: 1001,
+ records: [oversize],
+ hasMore: false,
+ nextSinceRevision: 1001,
+ }));
+ const staged = await stagedPromise;
+
+ assert.ok(staged);
+ assert.equal(staged.bucket.revision, 1001);
+ assert.equal(staged.bucket.records.size, 1000);
+ assert.equal(staged.bucket.rawRecords.size, 1001);
+ assert.equal(staged.invalidRecordSeen, true);
+ assert.equal(
+ staged.bucket.rawRecords.get(`${traceId}:${oversize.span_id}`)?.projection_omitted,
+ 'record_too_large',
+ );
+});
+
+test('a later detail-page failure leaves the current bucket untouched', async () => {
+ const existing = projectedRecord(10);
+ const identity = `${existing.trace_id}:${existing.span_id}`;
+ const current = {
+ revision: 10,
+ records: new Map([[identity, existing.otlp]]),
+ rawRecords: new Map([[identity, existing]]),
+ };
+ let calls = 0;
+ const controller = new AbortController();
+
+ await assert.rejects(
+ stageTrajectoryTracePages(current, controller.signal, async () => {
+ calls += 1;
+ if (calls === 1) {
+ return detailPage({
+ revision: 12,
+ records: [projectedRecord(11)],
+ hasMore: true,
+ nextSinceRevision: 11,
+ });
+ }
+ throw new Error('page two failed');
+ }),
+ /page two failed/,
+ );
+ assert.equal(current.revision, 10);
+ assert.deepEqual([...current.records.keys()], [identity]);
+ assert.deepEqual([...current.rawRecords.keys()], [identity]);
+});
+
+test('aborting after a staged detail page never returns a publishable bucket', async () => {
+ const current = {
+ revision: 0,
+ records: new Map(),
+ rawRecords: new Map(),
+ };
+ let resolveSecondPage;
+ let secondPageStarted;
+ const secondPageStartedPromise = new Promise(resolve => {
+ secondPageStarted = resolve;
+ });
+ const secondPagePromise = new Promise(resolve => {
+ resolveSecondPage = resolve;
+ });
+ const controller = new AbortController();
+ let calls = 0;
+ const stagedPromise = stageTrajectoryTracePages(
+ current,
+ controller.signal,
+ async () => {
+ calls += 1;
+ if (calls === 1) {
+ return detailPage({
+ revision: 2,
+ records: [projectedRecord(1)],
+ hasMore: true,
+ nextSinceRevision: 1,
+ });
+ }
+ secondPageStarted();
+ return secondPagePromise;
+ },
+ );
+
+ await secondPageStartedPromise;
+ controller.abort();
+ resolveSecondPage(detailPage({
+ revision: 2,
+ records: [projectedRecord(2)],
+ hasMore: false,
+ nextSinceRevision: 2,
+ }));
+
+ assert.equal(await stagedPromise, null);
+ assert.equal(current.revision, 0);
+ assert.equal(current.records.size, 0);
+ assert.equal(current.rawRecords.size, 0);
+});
+
+test('raw-only data keeps the content surface available during a refresh error', () => {
+ assert.equal(trajectoryContentMode({
+ sessionId: SESSION_ID,
+ loading: false,
+ error: 'gateway offline',
+ projectedCount: 0,
+ rawCount: 1,
+ }), 'data');
+ assert.equal(trajectoryContentMode({
+ sessionId: SESSION_ID,
+ loading: false,
+ error: 'gateway offline',
+ projectedCount: 0,
+ rawCount: 0,
+ }), 'blocking-error');
+});
+
+test('versioned upsert replaces one running identity with its terminal record', () => {
+ const running = projectedRecord(1);
+ running.record_id = `${running.trace_id}:${running.span_id}`;
+ running.record_revision = 1;
+ running.change_seq = 10;
+ running.lifecycle = 'running';
+ const started = applyTrajectoryDetailRecords(undefined, detailPage({
+ revision: 10,
+ records: [running],
+ hasMore: false,
+ nextSinceRevision: 10,
+ }));
+ const final = {
+ ...projectedRecord(2),
+ trace_id: running.trace_id,
+ span_id: running.span_id,
+ record_id: running.record_id,
+ record_revision: 3,
+ change_seq: 12,
+ lifecycle: 'final',
+ };
+ final.otlp = otlpRecord(final.trace_id, final.span_id);
+ const completed = applyTrajectoryDetailRecords(started.bucket, detailPage({
+ revision: 12,
+ records: [final],
+ hasMore: false,
+ nextSinceRevision: 12,
+ }));
+
+ assert.equal(completed.bucket.records.size, 1);
+ assert.equal(completed.bucket.rawRecords.size, 1);
+ assert.deepEqual(completed.bucket.versions.get(running.record_id), {
+ lifecycle: 'completed',
+ recordRevision: 3,
+ });
+ assert.equal(completed.bucket.rawRecords.get(running.record_id).change_seq, 12);
+});
+
+test('late running revisions cannot downgrade a terminal trajectory identity', () => {
+ const record = projectedRecord(3);
+ record.record_id = `${record.trace_id}:${record.span_id}`;
+ record.record_revision = 5;
+ record.lifecycle = 'completed';
+ const completed = applyTrajectoryDetailRecords(undefined, detailPage({
+ revision: 20,
+ records: [record],
+ hasMore: false,
+ nextSinceRevision: 20,
+ }));
+ const late = {
+ ...record,
+ ingest_seq: 4,
+ record_revision: 6,
+ lifecycle: 'running',
+ };
+ const unchanged = applyTrajectoryDetailRecords(completed.bucket, detailPage({
+ revision: 21,
+ records: [late],
+ hasMore: false,
+ nextSinceRevision: 21,
+ }));
+
+ assert.deepEqual(unchanged.bucket.versions.get(record.record_id), {
+ lifecycle: 'completed',
+ recordRevision: 5,
+ });
+ assert.equal(unchanged.bucket.rawRecords.get(record.record_id).ingest_seq, 3);
+});
+
+test('authoritative final absorbs a higher provisional record revision', () => {
+ const provisional = projectedRecord(5);
+ provisional.record_id = `${provisional.trace_id}:${provisional.span_id}`;
+ provisional.record_revision = 9;
+ provisional.lifecycle = 'provisional';
+ const started = applyTrajectoryDetailRecords(undefined, detailPage({
+ revision: 30,
+ records: [provisional],
+ hasMore: false,
+ nextSinceRevision: 30,
+ }));
+ const final = {
+ ...provisional,
+ ingest_seq: 6,
+ record_revision: 1,
+ lifecycle: 'final',
+ };
+ const completed = applyTrajectoryDetailRecords(started.bucket, detailPage({
+ revision: 31,
+ records: [final],
+ hasMore: false,
+ nextSinceRevision: 31,
+ }));
+
+ assert.deepEqual(completed.bucket.versions.get(provisional.record_id), {
+ lifecycle: 'completed',
+ recordRevision: 1,
+ });
+ assert.equal(completed.bucket.rawRecords.get(provisional.record_id).ingest_seq, 6);
+});
+
+test('live elapsed grows only for running open intervals', () => {
+ const running = {
+ index: 1,
+ kind: 'message',
+ status: 'running',
+ text: 'streaming',
+ startedAt: 1_000,
+ timeSeconds: null,
+ };
+ const completed = { ...running, status: 'complete', timeSeconds: 1.25 };
+ const input = { ...running, kind: 'user', status: 'complete' };
+
+ assert.equal(liveElapsedSeconds(running, 2_750), 1.75);
+ assert.equal(liveElapsedSeconds(completed, 99_000), 1.25);
+ assert.equal(liveElapsedSeconds(input, 99_000), null);
+});
diff --git a/jiuwenswarm/common/mode_matrix.py b/jiuwenswarm/common/mode_matrix.py
new file mode 100644
index 0000000000..920609a422
--- /dev/null
+++ b/jiuwenswarm/common/mode_matrix.py
@@ -0,0 +1,472 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""统一的运行模式解析(Web 组合模式 + 历史完整模式)。
+
+背景:仓库里长期存在两个正交概念。
+
+- ``work_mode``:``work`` / ``code``,表示工作环境(项目归属、Git 上下文)。
+- ``mode``:决定 Adapter(Deep / Code)、单 agent 还是集群、以及是否 plan。
+
+Web 前端只表达 ``agent`` / ``team`` / ``agent.plan`` 三个值。其中 ``work_mode``
+决定使用 work profile 还是 code profile,本模块负责把这两个字段组合成后端既有的
+manager mode / sub_mode / canonical mode。Web 的 ``team + code`` 组合归一为
+``code.team``(TUI 对外显示为 ``team.code``)。
+
+TUI、CLI、IM、cron 等客户端可以直接发送完整模式串。本模块同时负责将正式别名
+``team.plan`` 归一为 ``team.plan.normal``,并把两个 Team Plan profile 分别路由到
+DeepAdapter(normal)和 CodeAdapter(code)。
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from typing import Any, Callable, Mapping
+
+from jiuwenswarm.common.work_mode import SUPPORTED_WORK_MODES
+
+logger = logging.getLogger(__name__)
+
+# ── 新三段命名:8 种 canonical 模式 ──
+# 提前到这里定义,因为下面的 WEB_COMPOSABLE_MODES 需要引用其中的两个
+# agent.work.* 串(P6.4:让组合分支接住 Web 前端 wireMode.ts 产出的新串)。
+NEW_AGENT_WORK_NORMAL = "agent.work.normal"
+NEW_AGENT_WORK_PLAN = "agent.work.plan"
+NEW_AGENT_CODE_NORMAL = "agent.code.normal"
+NEW_AGENT_CODE_PLAN = "agent.code.plan"
+NEW_TEAM_WORK_NORMAL = "team.work.normal"
+NEW_TEAM_WORK_PLAN = "team.work.plan"
+NEW_TEAM_CODE_NORMAL = "team.code.normal"
+NEW_TEAM_CODE_PLAN = "team.code.plan"
+
+# Web 组合模式覆盖单 agent 和 Team 的 work/code profile。其余取值一律按历史完整
+# 模式处理。Team 不支持独立的 Web Plan,但 ``team + code`` 必须进入与 TUI
+# ``team.code`` 相同的 code-team profile。
+WEB_BASE_AGENT: str = "agent"
+WEB_PLAN_AGENT: str = "agent.plan"
+
+# P6.4:把 Web 前端 wireMode.ts 产出的新三段命名串(agent.work.normal /
+# agent.work.plan)也纳入 Web 组合分支,使 resolve_request_mode 的组合路径
+# 接住新串而不落 legacy。``team`` / ``agent`` / ``agent.plan`` 等旧串保留
+# 作历史兼容。
+WEB_COMPOSABLE_MODES: frozenset[str] = frozenset(
+ {
+ WEB_BASE_AGENT,
+ WEB_PLAN_AGENT,
+ "team",
+ NEW_AGENT_WORK_NORMAL,
+ NEW_AGENT_WORK_PLAN,
+ }
+)
+
+# Team plan 的规范模式与兼容别名。
+TEAM_PLAN_NORMAL_MODE: str = "team.plan.normal"
+TEAM_PLAN_CODE_MODE: str = "team.plan.code"
+MODE_ALIASES: dict[str, str] = {
+ "team.plan": TEAM_PLAN_NORMAL_MODE,
+ # TUI 的用户-facing 名称;运行时沿用历史 canonical ID。
+ "team.code": "code.team",
+}
+
+NEW_CANONICAL_MODES: frozenset[str] = frozenset(
+ {
+ NEW_AGENT_WORK_NORMAL,
+ NEW_AGENT_WORK_PLAN,
+ NEW_AGENT_CODE_NORMAL,
+ NEW_AGENT_CODE_PLAN,
+ NEW_TEAM_WORK_NORMAL,
+ NEW_TEAM_WORK_PLAN,
+ NEW_TEAM_CODE_NORMAL,
+ NEW_TEAM_CODE_PLAN,
+ }
+)
+
+# 旧 canonical → 新 canonical 的静默映射表。
+DEPRECATION_MAP: dict[str, str] = {
+ "agent": NEW_AGENT_WORK_NORMAL,
+ "agent.plan": NEW_AGENT_WORK_PLAN,
+ "agent.fast": NEW_AGENT_WORK_NORMAL, # 历史已归一 agent
+ "code": NEW_AGENT_CODE_NORMAL, # 裸 code 语义等价旧 code.normal
+ "code.normal": NEW_AGENT_CODE_NORMAL,
+ "code.plan": NEW_AGENT_CODE_PLAN,
+ "code.team": NEW_TEAM_CODE_NORMAL,
+ "team": NEW_TEAM_WORK_NORMAL,
+ TEAM_PLAN_NORMAL_MODE: NEW_TEAM_WORK_PLAN, # team.plan.normal
+ TEAM_PLAN_CODE_MODE: NEW_TEAM_CODE_PLAN, # team.plan.code
+}
+
+# 所有表示"集群"的 canonical 模式。
+TEAM_CANONICAL_MODES: frozenset[str] = frozenset(
+ {
+ "team",
+ TEAM_PLAN_NORMAL_MODE,
+ "code.team",
+ TEAM_PLAN_CODE_MODE,
+ NEW_TEAM_WORK_NORMAL,
+ NEW_TEAM_WORK_PLAN,
+ NEW_TEAM_CODE_NORMAL,
+ NEW_TEAM_CODE_PLAN,
+ }
+)
+
+# Modes whose traces are eligible for the first-phase single-Agent trajectory
+# UI. This is deliberately an allowlist: future modes must opt in explicitly
+# instead of becoming readable merely because they are not known Team modes.
+SINGLE_AGENT_CANONICAL_MODES: frozenset[str] = frozenset(
+ {"agent", "agent.fast", "agent.plan", "code", "code.normal", "code.plan"}
+)
+
+# 所有表示"正处于 plan"的 canonical 模式。
+PLAN_CANONICAL_MODES: frozenset[str] = frozenset(
+ {
+ "agent.plan",
+ "code.plan",
+ TEAM_PLAN_NORMAL_MODE,
+ TEAM_PLAN_CODE_MODE,
+ NEW_AGENT_WORK_PLAN,
+ NEW_AGENT_CODE_PLAN,
+ NEW_TEAM_WORK_PLAN,
+ NEW_TEAM_CODE_PLAN,
+ }
+)
+
+# canonical plan 模式退出 plan 后应回到的普通模式。
+_PLAN_EXIT_MODES: dict[str, str] = {
+ "agent.plan": "agent",
+ "code.plan": "code.normal",
+ TEAM_PLAN_NORMAL_MODE: "team",
+ TEAM_PLAN_CODE_MODE: "code.team",
+ NEW_AGENT_WORK_PLAN: NEW_AGENT_WORK_NORMAL,
+ NEW_AGENT_CODE_PLAN: NEW_AGENT_CODE_NORMAL,
+ NEW_TEAM_WORK_PLAN: NEW_TEAM_WORK_NORMAL,
+ NEW_TEAM_CODE_PLAN: NEW_TEAM_CODE_NORMAL,
+}
+
+# (mode, work_mode) -> (manager_mode, sub_mode, canonical_mode)
+# P6.4:加入 agent.work.normal / agent.work.plan 两个新串的 work profile 项。
+# code profile 不在 Web 组合表里 —— 这两个新串已经自带 work profile,前端
+# wireMode.ts 只在 plan on 时产出 agent.work.plan,code 系走 legacy 路径。
+_WEB_MODE_TABLE: dict[tuple[str, str], tuple[str, str | None, str]] = {
+ (WEB_BASE_AGENT, "work"): ("agent", None, "agent"),
+ (WEB_PLAN_AGENT, "work"): ("agent", "plan", "agent.plan"),
+ (WEB_BASE_AGENT, "code"): ("code", "normal", "code.normal"),
+ (WEB_PLAN_AGENT, "code"): ("code", "plan", "code.plan"),
+ ("team", "work"): ("team", None, "team"),
+ ("team", "code"): ("code", "team", "code.team"),
+ (NEW_AGENT_WORK_NORMAL, "work"): ("agent", None, NEW_AGENT_WORK_NORMAL),
+ (NEW_AGENT_WORK_PLAN, "work"): ("agent", "plan", NEW_AGENT_WORK_PLAN),
+}
+
+# 新三段命名 canonical → 按 ``.`` 直接切分的原始三段 ``(role, environment, state)``。
+# 不再手写 manager/sub 等派生语义(那样写容易与实际串语义漂移),三段就是串本身
+# 的分割,manager/sub 由 :func:`resolve_new_canonical_mode` 从三段按命名规则推导:
+# agent.work.normal ↔ ("agent", "work", "normal") team.work.normal ↔ ("team", "work", "normal")
+# agent.work.plan ↔ ("agent", "work", "plan") team.work.plan ↔ ("team", "work", "plan")
+# agent.code.normal ↔ ("agent", "code", "normal") team.code.normal ↔ ("team", "code", "normal")
+# agent.code.plan ↔ ("agent", "code", "plan") team.code.plan ↔ ("team", "code", "plan")
+NEW_CANONICAL_MODE_RESOLUTION: dict[str, tuple[str, str, str]] = {
+ NEW_AGENT_WORK_NORMAL: ("agent", "work", "normal"),
+ NEW_AGENT_WORK_PLAN: ("agent", "work", "plan"),
+ NEW_AGENT_CODE_NORMAL: ("agent", "code", "normal"),
+ NEW_AGENT_CODE_PLAN: ("agent", "code", "plan"),
+ NEW_TEAM_WORK_NORMAL: ("team", "work", "normal"),
+ NEW_TEAM_WORK_PLAN: ("team", "work", "plan"),
+ NEW_TEAM_CODE_NORMAL: ("team", "code", "normal"),
+ NEW_TEAM_CODE_PLAN: ("team", "code", "plan"),
+}
+
+
+@dataclass(frozen=True)
+class ResolvedMode:
+ """一次请求解析出的完整运行模式视图。
+
+ Attributes:
+ manager_mode: AgentManager / adapter 选型用的一级模式。
+ sub_mode: 子模式(``normal`` / ``plan`` / ``team`` / None)。
+ canonical_mode: 写回 ``params["mode"]`` 的规范值。
+ work_mode: 归一化后的 ``work`` / ``code``;历史请求为 None。
+ is_plan: 本次请求是否要求处于 plan。
+ is_team: 本次请求是否集群模式。
+ is_code_profile: 是否使用 CodeAdapter / code 团队 profile。
+ profile: 本次请求使用的 profile(``normal`` / ``code``)。
+ normal_mode: 退出 plan 后应回到的 canonical 模式。
+ from_web_composition: 是否由 Web 的 mode + work_mode 组合而来。
+ """
+
+ manager_mode: str
+ sub_mode: str | None
+ canonical_mode: str
+ work_mode: str | None
+ is_plan: bool
+ is_team: bool
+ is_code_profile: bool
+ profile: str
+ normal_mode: str
+ from_web_composition: bool
+
+
+def normalize_mode_text(raw_mode: Any) -> str:
+ """把请求里的 mode 归一成小写字符串,空值回落到 ``agent``。"""
+ raw_value = getattr(raw_mode, "value", raw_mode)
+ text = raw_value.strip().lower() if isinstance(raw_value, str) else ""
+ return text or "agent"
+
+
+def canonicalize_mode_text(raw_mode: Any) -> str:
+ """归一化 mode 文本并解析正式别名。"""
+ text = normalize_mode_text(raw_mode)
+ return MODE_ALIASES.get(text, text)
+
+
+def normalize_work_mode(raw: Any) -> str | None:
+ """把任意来源的 ``work_mode`` 归一成 ``work`` / ``code``;非法时返回 None。"""
+ if not isinstance(raw, str):
+ return None
+ value = raw.strip().lower()
+ return value if value in SUPPORTED_WORK_MODES else None
+
+
+def read_request_work_mode(params: Mapping[str, Any] | None) -> str | None:
+ """读取请求中显式携带的 ``work_mode``;缺失或非法时返回 None。
+
+ 只有 Web 会携带该字段,因此它同时充当"这是 Web 组合模式请求"的判据。
+ TUI / CLI / IM / cron 都不发送 ``work_mode``,会走历史解析分支。
+ """
+ if not isinstance(params, Mapping):
+ return None
+ return normalize_work_mode(params.get("work_mode"))
+
+
+def is_web_composable_mode(mode_text: str) -> bool:
+ """给定 mode 是否参与 Web 的 mode + work_mode 组合。"""
+ return mode_text in WEB_COMPOSABLE_MODES
+
+
+def is_plan_mode(canonical_mode: Any) -> bool:
+ """canonical 模式是否处于 plan。"""
+ return canonicalize_mode_text(canonical_mode) in PLAN_CANONICAL_MODES
+
+
+def is_team_mode(canonical_mode: Any) -> bool:
+ """canonical 模式是否为集群。"""
+ return canonicalize_mode_text(canonical_mode) in TEAM_CANONICAL_MODES
+
+
+def is_single_agent_mode(canonical_mode: Any) -> bool:
+ """Return whether *mode* is explicitly eligible for single-Agent flows."""
+ return canonicalize_mode_text(canonical_mode) in SINGLE_AGENT_CANONICAL_MODES
+
+
+def is_team_plan_mode(mode: Any) -> bool:
+ """Return whether *mode* is either normal or code Team Plan."""
+ return canonicalize_mode_text(mode) in {
+ TEAM_PLAN_NORMAL_MODE,
+ TEAM_PLAN_CODE_MODE,
+ NEW_TEAM_WORK_PLAN,
+ NEW_TEAM_CODE_PLAN,
+ }
+
+
+def is_code_profile_mode(mode: Any) -> bool:
+ """Return whether *mode* selects the code profile."""
+ return canonicalize_mode_text(mode) in {
+ # 裸 code:DEPRECATION_MAP["code"] -> agent.code.normal,语义等价旧 code.normal。
+ # 补齐它使未先经 deprecate_mode 归一就直接判定的调用方行为一致。
+ "code",
+ "code.normal",
+ "code.plan",
+ "code.team",
+ TEAM_PLAN_CODE_MODE,
+ NEW_AGENT_CODE_NORMAL,
+ NEW_AGENT_CODE_PLAN,
+ NEW_TEAM_CODE_NORMAL,
+ NEW_TEAM_CODE_PLAN,
+ }
+
+
+def base_mode_without_plan(canonical_mode: Any) -> str:
+ """canonical plan 模式退出后应回到的普通模式。非 plan 模式原样返回。"""
+ text = canonicalize_mode_text(canonical_mode)
+ return _PLAN_EXIT_MODES.get(text, text)
+
+
+def is_new_canonical_mode(mode: Any) -> bool:
+ """是否为新三段命名 canonical。"""
+ return canonicalize_mode_text(mode) in NEW_CANONICAL_MODES
+
+
+def deprecate_mode(mode: Any) -> str:
+ """旧 canonical 静默映射到新 canonical;非旧串原样返回。
+
+ 铁律 3:None / 空 / 空白串原样返回(``deprecate_mode(None) is None``、
+ ``deprecate_mode("") == ""``),不做 ``normalize_mode_text`` 的空串回落,
+ 避免把空值误映射成 ``agent.work.normal``。归一化由调用方在上游完成。
+ """
+ raw_value = getattr(mode, "value", mode)
+ if raw_value is None or (isinstance(raw_value, str) and not raw_value.strip()):
+ return raw_value
+ text = canonicalize_mode_text(mode)
+ new_text = DEPRECATION_MAP.get(text, text)
+ if new_text != text:
+ logger.debug(
+ "deprecate_mode: legacy canonical '%s' -> new canonical '%s'",
+ text, new_text,
+ )
+ return new_text
+
+
+def compose_web_mode(
+ mode_text: str, work_mode: str
+) -> tuple[str, str | None, str] | None:
+ """把 Web 的 ``mode`` + ``work_mode`` 组合成后端三元组。
+
+ Args:
+ mode_text: 归一化后的 Web mode(agent / agent.plan)。
+ work_mode: 归一化后的 work / code。
+
+ Returns:
+ ``(manager_mode, sub_mode, canonical_mode)``;不是 Web 组合时返回 None。
+ """
+ return _WEB_MODE_TABLE.get((mode_text, work_mode))
+
+
+def resolve_new_canonical_mode(mode: Any) -> tuple[str, str | None, str] | None:
+ """把新三段命名 canonical 直接解析成三元组,不经过 legacy 归并。
+
+ 新 canonical 的 environment / state 段已经内嵌在串里(``agent.work.plan``
+ 即 agent + work + plan),交给 legacy ``resolve_agent_request_mode`` 反而会被
+ 错误归并(如 ``agent.work.plan`` + work_mode="code" 被折叠成 ``code.normal``,
+ 造成 TUI 显示与模型感知的模式不一致)。此处按串自身语义短路返回:
+ work environment 下 manager 即 role(agent/team),state=plan 时 sub_mode 为
+ plan、否则 None;code environment 单 agent 的 manager 为 code、sub_mode 即
+ state;``team.code.*`` 沿用 ``code.team`` 历史约定(manager code、sub team,
+ is_team 由 canonical 串判定,不走 sub)。
+
+ Args:
+ mode: 任意 mode 值(Mode 枚举 / str)。
+
+ Returns:
+ ``(manager_mode, sub_mode, canonical_mode)``;非新 canonical 时返回 None。
+ """
+ text = canonicalize_mode_text(mode)
+ segments = NEW_CANONICAL_MODE_RESOLUTION.get(text)
+ if segments is None:
+ return None
+ role, environment, state = segments
+ if role == "team" and environment == "code":
+ manager_mode, sub_mode = "code", "team"
+ elif environment == "code":
+ manager_mode, sub_mode = "code", state
+ else:
+ manager_mode = role
+ sub_mode = "plan" if state == "plan" else None
+ logger.debug(
+ "resolve_new_canonical_mode: '%s' -> manager='%s' sub='%s' canonical='%s'",
+ text, manager_mode, sub_mode, text,
+ )
+ return manager_mode, sub_mode, text
+
+
+def resolve_request_mode(
+ params: Mapping[str, Any] | None,
+ legacy_resolver: Callable[..., tuple[str, str | None, str]],
+ *,
+ work_mode: Any = None,
+) -> ResolvedMode:
+ """解析一次请求的运行模式。
+
+ 优先走 Web 组合分支;只有当请求同时满足"存在合法 ``work_mode``"和
+ "mode 是 Web 支持的基础模式"时才生效。其余取值(``code.plan`` / ``code.team`` /
+ ``team.plan.*`` / ``agent.fast`` 等完整模式串)都交给 *legacy_resolver*。
+
+ Args:
+ params: 请求 params。
+ legacy_resolver: 历史解析函数(``resolve_agent_request_mode``)。
+ work_mode: 调用方已解析出的 ``work_mode``(如来自 session metadata),
+ 优先于 ``params["work_mode"]``;同时透传给 *legacy_resolver*。
+
+ Returns:
+ 解析后的 :class:`ResolvedMode`。
+ """
+ raw_mode = params.get("mode") if isinstance(params, Mapping) else None
+ mode_text = canonicalize_mode_text(raw_mode)
+ work_mode = normalize_work_mode(work_mode) or read_request_work_mode(params)
+
+ if work_mode is not None and is_web_composable_mode(mode_text):
+ composed = compose_web_mode(mode_text, work_mode)
+ if composed is not None:
+ manager_mode, sub_mode, canonical_mode = composed
+ logger.debug(
+ "resolve_request_mode: web-composed mode='%s' work_mode='%s' -> "
+ "manager='%s' sub='%s' canonical='%s' is_plan=%s is_team=%s",
+ mode_text, work_mode, manager_mode, sub_mode,
+ canonical_mode,
+ canonical_mode in PLAN_CANONICAL_MODES,
+ canonical_mode in TEAM_CANONICAL_MODES,
+ )
+ return ResolvedMode(
+ manager_mode=manager_mode,
+ sub_mode=sub_mode,
+ canonical_mode=canonical_mode,
+ work_mode=work_mode,
+ is_plan=canonical_mode in PLAN_CANONICAL_MODES,
+ is_team=canonical_mode in TEAM_CANONICAL_MODES,
+ is_code_profile=work_mode == "code",
+ profile="code" if work_mode == "code" else "normal",
+ normal_mode=base_mode_without_plan(canonical_mode),
+ from_web_composition=True,
+ )
+
+ manager_mode, sub_mode, canonical_mode = legacy_resolver(
+ mode_text, work_mode=work_mode
+ )
+ logger.debug(
+ "resolve_request_mode: legacy mode='%s' work_mode='%s' -> "
+ "manager='%s' sub='%s' canonical='%s' is_plan=%s is_team=%s",
+ mode_text, work_mode, manager_mode, sub_mode,
+ canonical_mode,
+ canonical_mode in PLAN_CANONICAL_MODES,
+ canonical_mode in TEAM_CANONICAL_MODES,
+ )
+ return ResolvedMode(
+ manager_mode=manager_mode,
+ sub_mode=sub_mode,
+ canonical_mode=canonical_mode,
+ work_mode=work_mode,
+ is_plan=canonical_mode in PLAN_CANONICAL_MODES,
+ is_team=canonical_mode in TEAM_CANONICAL_MODES,
+ is_code_profile=manager_mode == "code",
+ profile="code" if manager_mode == "code" else "normal",
+ normal_mode=base_mode_without_plan(canonical_mode),
+ from_web_composition=False,
+ )
+
+
+__all__ = [
+ "PLAN_CANONICAL_MODES",
+ "SINGLE_AGENT_CANONICAL_MODES",
+ "MODE_ALIASES",
+ "DEPRECATION_MAP",
+ "NEW_CANONICAL_MODES",
+ "ResolvedMode",
+ "TEAM_PLAN_CODE_MODE",
+ "TEAM_PLAN_NORMAL_MODE",
+ "TEAM_CANONICAL_MODES",
+ "WEB_COMPOSABLE_MODES",
+ "base_mode_without_plan",
+ "canonicalize_mode_text",
+ "compose_web_mode",
+ "deprecate_mode",
+ "is_single_agent_mode",
+ "is_code_profile_mode",
+ "is_new_canonical_mode",
+ "is_plan_mode",
+ "is_team_plan_mode",
+ "is_team_mode",
+ "is_web_composable_mode",
+ "normalize_mode_text",
+ "normalize_work_mode",
+ "read_request_work_mode",
+ "resolve_new_canonical_mode",
+ "resolve_request_mode",
+]
diff --git a/jiuwenswarm/gateway/channel_manager/web/trajectory_http.py b/jiuwenswarm/gateway/channel_manager/web/trajectory_http.py
new file mode 100644
index 0000000000..f4005915c8
--- /dev/null
+++ b/jiuwenswarm/gateway/channel_manager/web/trajectory_http.py
@@ -0,0 +1,707 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Gateway HTTP read API for persisted single-Agent trajectory records."""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import logging
+import re
+from collections.abc import Awaitable, Callable, Mapping
+from datetime import datetime, timezone
+from typing import TYPE_CHECKING, Any
+from urllib.parse import urlsplit
+
+from fastapi import FastAPI, Query, Request
+from fastapi.responses import JSONResponse, Response
+
+from jiuwenswarm.common.mode_matrix import canonicalize_mode_text, is_single_agent_mode
+from jiuwenswarm.common.security.ws_origin import (
+ get_allowed_origin_hosts,
+ is_allowed_browser_origin,
+ is_origin_check_enabled,
+)
+from jiuwenswarm.observability.config import (
+ TrajectoryStoreSettings,
+ load_trajectory_store_settings,
+)
+from jiuwenswarm.observability.store import AsyncTrajectoryReader, TrajectoryCursorError
+from jiuwenswarm.server.runtime.session.session_history import is_valid_session_id
+
+if TYPE_CHECKING:
+ from jiuwenswarm.gateway.channel_manager.web.web_connect import WebChannel
+
+logger = logging.getLogger(__name__)
+
+TRAJECTORY_API_PREFIX = "/api/trajectory"
+_TRACE_ID_PATTERN = re.compile(r"^[0-9a-f]{32}$")
+_SPAN_ID_PATTERN = re.compile(r"^[0-9a-f]{16}$")
+_CURSOR_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$")
+_NO_STORE_HEADERS = {"Cache-Control": "no-store"}
+_MAX_SQLITE_INTEGER = (1 << 63) - 1
+_MAX_INTEGER_QUERY_CHARS = len(str(_MAX_SQLITE_INTEGER))
+_MAX_CURSOR_LENGTH = 512
+
+SessionMetadataLoader = Callable[[str], Mapping[str, Any]]
+
+
+class TrajectoryHttpService:
+ """Validated HTTP response layer over the asynchronous SQLite reader."""
+
+ def __init__(
+ self,
+ settings: TrajectoryStoreSettings,
+ *,
+ reader: AsyncTrajectoryReader | None = None,
+ metadata_loader: SessionMetadataLoader | None = None,
+ ) -> None:
+ self.settings = settings
+ self.reader = reader or AsyncTrajectoryReader(settings.database_path)
+ self._metadata_loader = metadata_loader or _load_session_metadata
+
+ async def list_traces(
+ self,
+ session_id: str,
+ *,
+ limit: int,
+ cursor: str | None,
+ ) -> Response:
+ """Build the paginated trace-list response for one single-Agent session."""
+ error = self._validate_access(session_id)
+ if error is not None:
+ return error
+ if not 1 <= limit <= 100:
+ return _error_response(
+ "limit must be between 1 and 100",
+ "BAD_REQUEST",
+ 400,
+ )
+ if cursor is not None and not _is_valid_cursor_text(cursor):
+ return _error_response("invalid trajectory cursor", "BAD_REQUEST", 400)
+ try:
+ (
+ items,
+ next_cursor,
+ revision_cursor,
+ store_epoch,
+ ) = await self.reader.list_traces_with_revision_cursor(
+ session_id,
+ limit=limit,
+ cursor=cursor,
+ )
+ except TrajectoryCursorError:
+ return _error_response("invalid trajectory cursor", "BAD_REQUEST", 400)
+ except Exception:
+ logger.exception("Trajectory trace-list query failed: session_id=%s", session_id)
+ return _error_response(
+ "trajectory query failed",
+ "TRAJECTORY_QUERY_FAILED",
+ 500,
+ )
+ return _json_response(
+ {
+ "schema_version": 1,
+ "session_id": session_id,
+ "items": [_http_trace_summary(item) for item in items],
+ "next_cursor": next_cursor,
+ "revision_cursor": revision_cursor,
+ "store_epoch": store_epoch,
+ }
+ )
+
+ async def export_archive(self, session_id: str) -> Response:
+ """Export a stable archive of every current record in one session."""
+ error = self._validate_access(session_id)
+ if error is not None:
+ return error
+ try:
+ records, store_epoch, revision = (
+ await self.reader.get_session_archive_records(session_id)
+ )
+ except Exception:
+ logger.exception(
+ "Trajectory archive query failed: session_id=%s",
+ session_id,
+ )
+ return _error_response(
+ "trajectory query failed",
+ "TRAJECTORY_QUERY_FAILED",
+ 500,
+ )
+ response = _json_response(
+ {
+ "format": "openjiuwen.trajectory.archive",
+ "archive_version": 1,
+ "session_id": session_id,
+ "exported_at": datetime.now(timezone.utc).isoformat().replace(
+ "+00:00",
+ "Z",
+ ),
+ "store_epoch": store_epoch,
+ "revision": str(revision),
+ "records": records,
+ }
+ )
+ response.headers["Content-Disposition"] = (
+ f'attachment; filename="trajectory-{session_id}.archive.json"'
+ )
+ return response
+
+ async def list_revisions(
+ self,
+ session_id: str,
+ *,
+ after_revision: str,
+ limit: int,
+ ) -> Response:
+ """Build one stable page of trace summaries changed since a cursor."""
+ error = self._validate_access(session_id)
+ if error is not None:
+ return error
+ if not 1 <= limit <= 100:
+ return _error_response(
+ "limit must be between 1 and 100",
+ "BAD_REQUEST",
+ 400,
+ )
+ if not _is_valid_cursor_text(after_revision):
+ return _error_response(
+ "invalid trajectory revision cursor",
+ "BAD_REQUEST",
+ 400,
+ )
+ try:
+ (
+ items,
+ next_cursor,
+ watermark,
+ has_more,
+ reset,
+ store_epoch,
+ ) = await self.reader.list_trace_revisions(
+ session_id,
+ after_revision=after_revision,
+ limit=limit,
+ )
+ except TrajectoryCursorError:
+ return _error_response(
+ "invalid trajectory revision cursor",
+ "BAD_REQUEST",
+ 400,
+ )
+ except Exception:
+ logger.exception(
+ "Trajectory revision query failed: session_id=%s",
+ session_id,
+ )
+ return _error_response(
+ "trajectory query failed",
+ "TRAJECTORY_QUERY_FAILED",
+ 500,
+ )
+ return _json_response(
+ {
+ "schema_version": 1,
+ "session_id": session_id,
+ "items": [_http_trace_summary(item) for item in items],
+ "next_cursor": next_cursor,
+ "watermark": watermark,
+ "has_more": has_more,
+ "reset": reset,
+ "store_epoch": store_epoch,
+ }
+ )
+
+ async def get_trace(
+ self,
+ session_id: str,
+ trace_id: str,
+ *,
+ since_revision: int,
+ limit: int,
+ ) -> Response:
+ """Build a complete or incremental trace-detail response."""
+ error = self._validate_access(session_id)
+ if error is not None:
+ return error
+ normalized_trace_id = str(trace_id or "").strip().lower()
+ if _TRACE_ID_PATTERN.fullmatch(normalized_trace_id) is None:
+ return _error_response("invalid trace_id", "BAD_REQUEST", 400)
+ if since_revision < 0:
+ return _error_response("since_revision must be >= 0", "BAD_REQUEST", 400)
+ if since_revision > _MAX_SQLITE_INTEGER:
+ return _error_response("since_revision is too large", "BAD_REQUEST", 400)
+ if not 1 <= limit <= 1000:
+ return _error_response(
+ "limit must be between 1 and 1000",
+ "BAD_REQUEST",
+ 400,
+ )
+ try:
+ result = await self.reader.get_trace_records(
+ session_id,
+ normalized_trace_id,
+ since_revision=since_revision,
+ limit=limit,
+ max_bytes=self.settings.detail_max_bytes,
+ )
+ except Exception:
+ logger.exception(
+ "Trajectory trace-detail query failed: session_id=%s trace_id=%s",
+ session_id,
+ normalized_trace_id,
+ )
+ return _error_response(
+ "trajectory query failed",
+ "TRAJECTORY_QUERY_FAILED",
+ 500,
+ )
+ if result is None:
+ return _error_response("trace not found", "NOT_FOUND", 404)
+ return _json_response(
+ {
+ "schema_version": 1,
+ "session_id": session_id,
+ "trace_id": normalized_trace_id,
+ **result,
+ }
+ )
+
+ async def get_raw_record(
+ self,
+ session_id: str,
+ trace_id: str,
+ span_id: str,
+ ) -> Response:
+ """Return the exact stored OTLP bytes for one session-owned span."""
+ error = self._validate_access(session_id)
+ if error is not None:
+ return error
+ normalized_trace_id = str(trace_id or "").strip().lower()
+ normalized_span_id = str(span_id or "").strip().lower()
+ if _TRACE_ID_PATTERN.fullmatch(normalized_trace_id) is None:
+ return _error_response("invalid trace_id", "BAD_REQUEST", 400)
+ if _SPAN_ID_PATTERN.fullmatch(normalized_span_id) is None:
+ return _error_response("invalid span_id", "BAD_REQUEST", 400)
+ try:
+ raw_json = await self.reader.get_raw_record(
+ session_id,
+ normalized_trace_id,
+ normalized_span_id,
+ )
+ except Exception:
+ logger.exception(
+ "Trajectory raw-record query failed: session_id=%s trace_id=%s span_id=%s",
+ session_id,
+ normalized_trace_id,
+ normalized_span_id,
+ )
+ return _error_response(
+ "trajectory query failed",
+ "TRAJECTORY_QUERY_FAILED",
+ 500,
+ )
+ if raw_json is None:
+ return _error_response("span not found", "NOT_FOUND", 404)
+ return Response(
+ content=raw_json,
+ status_code=200,
+ headers={
+ **_NO_STORE_HEADERS,
+ "Content-Type": "application/json; charset=utf-8",
+ },
+ )
+
+ def _validate_access(self, session_id: str) -> Response | None:
+ if not self.settings.enabled:
+ return _error_response(
+ "trajectory UI is disabled",
+ "TRAJECTORY_DISABLED",
+ 503,
+ )
+ normalized_session_id = str(session_id or "").strip()
+ if normalized_session_id != session_id or not is_valid_session_id(normalized_session_id):
+ return _error_response("invalid session_id", "BAD_REQUEST", 400)
+ try:
+ metadata = self._metadata_loader(normalized_session_id)
+ except Exception:
+ logger.exception(
+ "Trajectory session metadata lookup failed: session_id=%s",
+ normalized_session_id,
+ )
+ return _error_response(
+ "session lookup failed",
+ "SESSION_LOOKUP_FAILED",
+ 500,
+ )
+ if not metadata:
+ return _error_response("session not found", "NOT_FOUND", 404)
+ raw_mode = metadata.get("mode")
+ raw_mode_value = getattr(raw_mode, "value", raw_mode)
+ if not isinstance(raw_mode_value, str) or not raw_mode_value.strip():
+ return _error_response(
+ "trajectory UI supports known single-Agent sessions only",
+ "UNSUPPORTED_SESSION_MODE",
+ 403,
+ )
+ normalized_mode = canonicalize_mode_text(raw_mode)
+ team_name = str(metadata.get("team_name") or "").strip()
+ if not is_single_agent_mode(normalized_mode) or team_name:
+ return _error_response(
+ "trajectory UI supports single-Agent sessions only",
+ "UNSUPPORTED_SESSION_MODE",
+ 403,
+ )
+ return None
+
+
+def attach_trajectory_routes(
+ app: FastAPI,
+ channel: WebChannel,
+ *,
+ settings: TrajectoryStoreSettings | None = None,
+ reader: AsyncTrajectoryReader | None = None,
+ metadata_loader: SessionMetadataLoader | None = None,
+) -> TrajectoryHttpService:
+ """Mount the trajectory HTTP routes on the WebChannel FastAPI app.
+
+ Args:
+ app: WebChannel FastAPI application.
+ channel: Owning WebChannel, retained on app state for route provenance.
+ settings: Optional resolved settings override.
+ reader: Optional reader override for tests.
+ metadata_loader: Optional session metadata loader override.
+
+ Returns:
+ Mounted service instance.
+ """
+ service = TrajectoryHttpService(
+ settings or load_trajectory_store_settings(),
+ reader=reader,
+ metadata_loader=metadata_loader,
+ )
+ app.state.trajectory_http_service = service
+ app.state.trajectory_web_channel = channel
+
+ @app.middleware("http")
+ async def trajectory_error_boundary(
+ request: Request,
+ call_next: Callable[[Request], Awaitable[Response]],
+ ) -> Response:
+ """Keep framework-level trajectory failures private and non-cacheable."""
+ path = request.url.path
+ if (
+ path != TRAJECTORY_API_PREFIX
+ and not path.startswith(f"{TRAJECTORY_API_PREFIX}/")
+ ):
+ return await call_next(request)
+ try:
+ response = await call_next(request)
+ except Exception:
+ logger.exception("Unhandled trajectory HTTP request failure: path=%s", path)
+ return _error_response(
+ "trajectory request failed",
+ "TRAJECTORY_REQUEST_FAILED",
+ 500,
+ )
+ route_handled = bool(
+ getattr(request.state, "trajectory_route_handled", False)
+ )
+ if response.status_code == 404 and not route_handled:
+ return _error_response("trajectory route not found", "NOT_FOUND", 404)
+ if response.status_code == 405 and not route_handled:
+ error_response = _error_response(
+ "trajectory method not allowed",
+ "METHOD_NOT_ALLOWED",
+ 405,
+ )
+ allowed_methods = response.headers.get("allow")
+ if allowed_methods:
+ error_response.headers["Allow"] = allowed_methods
+ return error_response
+ if response.status_code == 422:
+ return _error_response("invalid trajectory request", "BAD_REQUEST", 400)
+ response.headers["Cache-Control"] = "no-store"
+ return response
+
+ @app.get(f"{TRAJECTORY_API_PREFIX}/sessions/{{session_id}}/traces")
+ async def list_trajectory_traces(
+ session_id: str,
+ request: Request,
+ limit: str = Query(default="30"),
+ cursor: str | None = Query(default=None),
+ ) -> Response:
+ """List trajectory traces for one session."""
+ request.state.trajectory_route_handled = True
+ origin_error = _validate_http_origin(request)
+ if origin_error is not None:
+ return origin_error
+ parsed_limit = _parse_integer_query(limit)
+ if parsed_limit is None:
+ return _error_response("limit must be an integer", "BAD_REQUEST", 400)
+ return await service.list_traces(
+ session_id,
+ limit=parsed_limit,
+ cursor=cursor,
+ )
+
+ @app.get(f"{TRAJECTORY_API_PREFIX}/sessions/{{session_id}}/revisions")
+ async def list_trajectory_revisions(
+ session_id: str,
+ request: Request,
+ after_revision: str = Query(default=""),
+ limit: str = Query(default="100"),
+ ) -> Response:
+ """List trace summaries changed after an opaque polling cursor."""
+ request.state.trajectory_route_handled = True
+ origin_error = _validate_http_origin(request)
+ if origin_error is not None:
+ return origin_error
+ parsed_limit = _parse_integer_query(limit)
+ if parsed_limit is None:
+ return _error_response("limit must be an integer", "BAD_REQUEST", 400)
+ return await service.list_revisions(
+ session_id,
+ after_revision=after_revision,
+ limit=parsed_limit,
+ )
+
+ @app.get(f"{TRAJECTORY_API_PREFIX}/sessions/{{session_id}}/archive")
+ async def export_trajectory_archive(
+ session_id: str,
+ request: Request,
+ ) -> Response:
+ """Export all current trajectory records for one session."""
+ request.state.trajectory_route_handled = True
+ origin_error = _validate_http_origin(request)
+ if origin_error is not None:
+ return origin_error
+ return await service.export_archive(session_id)
+
+ @app.get(f"{TRAJECTORY_API_PREFIX}/sessions/{{session_id}}/traces/{{trace_id}}")
+ async def get_trajectory_trace(
+ session_id: str,
+ trace_id: str,
+ request: Request,
+ since_revision: str = Query(default="0"),
+ limit: str = Query(default="1000"),
+ ) -> Response:
+ """Read complete or incremental trajectory records."""
+ request.state.trajectory_route_handled = True
+ origin_error = _validate_http_origin(request)
+ if origin_error is not None:
+ return origin_error
+ parsed_since_revision = _parse_integer_query(since_revision)
+ parsed_limit = _parse_integer_query(limit)
+ if parsed_since_revision is None:
+ return _error_response(
+ "since_revision must be an integer",
+ "BAD_REQUEST",
+ 400,
+ )
+ if parsed_limit is None:
+ return _error_response("limit must be an integer", "BAD_REQUEST", 400)
+ return await service.get_trace(
+ session_id,
+ trace_id,
+ since_revision=parsed_since_revision,
+ limit=parsed_limit,
+ )
+
+ @app.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/{{session_id}}/traces/{{trace_id}}/spans/{{span_id}}/raw"
+ )
+ async def get_trajectory_raw_record(
+ session_id: str,
+ trace_id: str,
+ span_id: str,
+ request: Request,
+ ) -> Response:
+ """Read one lossless raw OTLP record."""
+ request.state.trajectory_route_handled = True
+ origin_error = _validate_http_origin(request)
+ if origin_error is not None:
+ return origin_error
+ return await service.get_raw_record(session_id, trace_id, span_id)
+
+ return service
+
+
+def _load_session_metadata(session_id: str) -> Mapping[str, Any]:
+ from jiuwenswarm.server.runtime.session.session_metadata import get_session_metadata
+
+ return get_session_metadata(
+ session_id,
+ cache_bust=True,
+ enable_writeback=False,
+ )
+
+
+def _http_trace_summary(item: Mapping[str, Any]) -> dict[str, Any]:
+ return {
+ **item,
+ "start_time_unix_nano": str(item["start_time_unix_nano"]),
+ "end_time_unix_nano": str(item["end_time_unix_nano"]),
+ }
+
+
+def _parse_integer_query(value: str) -> int | None:
+ normalized = str(value or "").strip()
+ if (
+ not normalized
+ or len(normalized) > _MAX_INTEGER_QUERY_CHARS
+ or not normalized.isascii()
+ or not normalized.isdecimal()
+ ):
+ return None
+ try:
+ parsed = int(normalized)
+ except (ValueError, OverflowError):
+ return None
+ return parsed if parsed <= _MAX_SQLITE_INTEGER else None
+
+
+def _is_valid_cursor_text(value: str) -> bool:
+ """Accept only canonical unpadded base64url before touching the reader."""
+ normalized = str(value or "")
+ if (
+ normalized != normalized.strip()
+ or not 0 < len(normalized) <= _MAX_CURSOR_LENGTH
+ or not normalized.isascii()
+ or _CURSOR_PATTERN.fullmatch(normalized) is None
+ or len(normalized) % 4 == 1
+ ):
+ return False
+ padding = "=" * (-len(normalized) % 4)
+ try:
+ decoded = base64.b64decode(
+ f"{normalized}{padding}".encode("ascii"),
+ altchars=b"-_",
+ validate=True,
+ )
+ except (binascii.Error, ValueError):
+ return False
+ canonical = base64.urlsafe_b64encode(decoded).decode("ascii").rstrip("=")
+ return canonical == normalized
+
+
+def _request_host_name(request: Request) -> str | None:
+ """Return a canonical Host hostname without trusting forwarding headers."""
+ host_values = request.headers.getlist("host")
+ if len(host_values) != 1:
+ return None
+ raw_host = str(host_values[0] or "").strip()
+ if (
+ not raw_host
+ or len(raw_host) > 512
+ or not raw_host.isascii()
+ or raw_host.endswith(":")
+ or any(
+ character.isspace() or ord(character) < 32 or ord(character) == 127
+ for character in raw_host
+ )
+ or any(
+ separator in raw_host
+ for separator in ("/", "\\", "?", "#", "@", ",")
+ )
+ ):
+ return None
+ try:
+ parsed_host = urlsplit(f"//{raw_host}")
+ hostname = parsed_host.hostname
+ parsed_host.port
+ except ValueError:
+ return None
+ if (
+ hostname is None
+ or parsed_host.username is not None
+ or parsed_host.password is not None
+ or parsed_host.path
+ or parsed_host.query
+ or parsed_host.fragment
+ ):
+ return None
+ normalized_hostname = hostname.lower().rstrip(".")
+ if (
+ not normalized_hostname
+ or not normalized_hostname.isascii()
+ or "%" in normalized_hostname
+ ):
+ return None
+ return normalized_hostname
+
+
+def _is_allowed_request_host(request: Request) -> bool:
+ """Return whether the browser-facing Host belongs to the configured allowlist."""
+ hostname = _request_host_name(request)
+ if hostname is None:
+ return False
+ allowed_hosts = {
+ host.lower().rstrip(".")
+ for host in get_allowed_origin_hosts()
+ if host.lower().rstrip(".") != "none"
+ }
+ return hostname in allowed_hosts
+
+
+def _validate_http_origin(request: Request) -> Response | None:
+ """Apply the WebChannel browser-origin gate to sensitive trace reads."""
+ if not is_origin_check_enabled():
+ return None
+ fetch_site = str(request.headers.get("sec-fetch-site") or "").strip().lower()
+ if fetch_site == "cross-site":
+ logger.warning(
+ "Trajectory HTTP cross-site request rejected: path=%s host=%s",
+ request.url.path,
+ request.headers.get("host"),
+ )
+ return _error_response("origin not allowed", "FORBIDDEN_ORIGIN", 403)
+ origin = request.headers.get("origin")
+ if origin is not None and is_allowed_browser_origin(origin):
+ return None
+ referer = request.headers.get("referer")
+ if origin is None and _is_allowed_request_host(request):
+ fetch_metadata_allows = fetch_site in {"same-origin", "none"}
+ referer_allows = (
+ not fetch_site
+ and referer is not None
+ and is_allowed_browser_origin(referer)
+ )
+ non_browser_allows = (
+ not fetch_site
+ and referer is None
+ and is_allowed_browser_origin(None)
+ )
+ if fetch_metadata_allows or referer_allows or non_browser_allows:
+ return None
+ logger.warning(
+ "Trajectory HTTP request rejected: path=%s host=%s origin=%s fetch_site=%s",
+ request.url.path,
+ request.headers.get("host"),
+ origin,
+ fetch_site,
+ )
+ return _error_response("origin not allowed", "FORBIDDEN_ORIGIN", 403)
+
+
+def _json_response(content: dict[str, Any], status_code: int = 200) -> JSONResponse:
+ return JSONResponse(
+ content=content,
+ status_code=status_code,
+ headers=_NO_STORE_HEADERS,
+ )
+
+
+def _error_response(error: str, code: str, status_code: int) -> JSONResponse:
+ return _json_response(
+ {"error": error, "code": code},
+ status_code=status_code,
+ )
+
+
+__all__ = [
+ "TRAJECTORY_API_PREFIX",
+ "TrajectoryHttpService",
+ "attach_trajectory_routes",
+]
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_connect.py b/jiuwenswarm/gateway/channel_manager/web/web_connect.py
index 1b8c007e26..637897618d 100644
--- a/jiuwenswarm/gateway/channel_manager/web/web_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/web/web_connect.py
@@ -12,6 +12,7 @@ Public API is unchanged (``WebChannel`` / ``WebChannelConfig``). Internally:
from __future__ import annotations
+import asyncio
from typing import Any, Callable
from jiuwenswarm.common.schema.message import Message, Mode, ReqMethod
@@ -59,6 +60,9 @@ class WebChannel(BaseChannel):
self.ws = WebWsTransport(config, router, self)
self.http = WebHttpTransport(self)
self.git_watcher_registry: Any = None
+ self._trajectory_event_loop: asyncio.AbstractEventLoop | None = None
+ self._trajectory_listener_registered = False
+ self._trajectory_update_listener = self._on_trajectory_updates
# ── Compatibility shims (invoke / handlers access private attrs) ──
@@ -249,6 +253,12 @@ class WebChannel(BaseChannel):
if self._running:
return
self._running = True
+ self._trajectory_event_loop = asyncio.get_running_loop()
+ if not self._trajectory_listener_registered:
+ from jiuwenswarm.observability.updates import trajectory_update_broker
+
+ trajectory_update_broker.register(self._trajectory_update_listener)
+ self._trajectory_listener_registered = True
self.rpc.maybe_start_history_capture()
await self.ws.start_ws_server()
await self.http.start()
@@ -259,14 +269,51 @@ class WebChannel(BaseChannel):
logger_info += f" http://{self.config.host}:{self.http.port}"
import logging
logging.getLogger(__name__).info(logger_info)
- await self.ws.wait_closed()
+ try:
+ await self.ws.wait_closed()
+ finally:
+ self._unregister_trajectory_listener()
async def stop(self) -> None:
self._running = False
+ self._unregister_trajectory_listener()
await self.http.stop()
self.rpc.shutdown()
await self.ws.stop_ws_server()
+ def _unregister_trajectory_listener(self) -> None:
+ if self._trajectory_listener_registered:
+ from jiuwenswarm.observability.updates import trajectory_update_broker
+
+ trajectory_update_broker.unregister(self._trajectory_update_listener)
+ self._trajectory_listener_registered = False
+ self._trajectory_event_loop = None
+
+ def _on_trajectory_updates(self, updates: tuple[Any, ...]) -> None:
+ loop = self._trajectory_event_loop
+ if loop is None or loop.is_closed():
+ return
+ loop.call_soon_threadsafe(self._schedule_trajectory_updates, updates)
+
+ def _schedule_trajectory_updates(self, updates: tuple[Any, ...]) -> None:
+ asyncio.create_task(self._send_trajectory_updates(updates))
+
+ async def _send_trajectory_updates(self, updates: tuple[Any, ...]) -> None:
+ for update in updates:
+ session_id = str(getattr(update, "session_id", "") or "").strip()
+ if not session_id:
+ continue
+ payload = {
+ "session_id": session_id,
+ "trace_id": str(getattr(update, "trace_id", "") or ""),
+ "revision": int(getattr(update, "revision", 0)),
+ "store_epoch": getattr(update, "store_epoch", None),
+ "lifecycle": str(getattr(update, "lifecycle", "final") or "final"),
+ }
+ for peer in self.peers_for_session(session_id):
+ if peer in self.clients and not getattr(peer, "closed", False):
+ await self.send_event(peer, "trace.updated", payload)
+
async def connect(self) -> None:
await self.start()
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py b/jiuwenswarm/gateway/channel_manager/web/web_http_app.py
index 6513f32c02..4d3bb79f64 100644
--- a/jiuwenswarm/gateway/channel_manager/web/web_http_app.py
+++ b/jiuwenswarm/gateway/channel_manager/web/web_http_app.py
@@ -37,6 +37,9 @@ from jiuwenswarm.gateway.channel_manager.web.web_http_sessions_compat import (
catalog_sessions_compat_entries,
register_sessions_compat_routes,
)
+from jiuwenswarm.gateway.channel_manager.web.trajectory_http import (
+ attach_trajectory_routes,
+)
_HEADER_TO_PARAM = {
"x-user-id": "user_id",
@@ -613,6 +616,7 @@ def create_web_http_app(channel: Any) -> FastAPI:
_register_mapped_routes(app, channel, mapped_routes)
register_sessions_compat_routes(app)
register_file_compat_routes(app)
+ attach_trajectory_routes(app, channel)
return app
diff --git a/jiuwenswarm/observability/__init__.py b/jiuwenswarm/observability/__init__.py
new file mode 100644
index 0000000000..ea8e89157e
--- /dev/null
+++ b/jiuwenswarm/observability/__init__.py
@@ -0,0 +1,37 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""JiuwenSwarm persistence and delivery for OTLP trajectory records."""
+
+from jiuwenswarm.observability.config import TrajectoryStoreSettings, load_trajectory_store_settings
+from jiuwenswarm.observability.models import (
+ CommittedTraceUpdate,
+ OtlpSpanRecordLike,
+ TraceRecordData,
+ TraceSinkStats,
+ WriteBatchResult,
+)
+from jiuwenswarm.observability.sink import TrajectoryRecordSink
+from jiuwenswarm.observability.runtime import (
+ get_trajectory_runtime_sink,
+ shutdown_trajectory_runtime,
+ start_trajectory_runtime,
+ sync_trajectory_runtime,
+)
+from jiuwenswarm.observability.store import AsyncTrajectoryReader, TrajectoryStore
+
+__all__ = [
+ "AsyncTrajectoryReader",
+ "CommittedTraceUpdate",
+ "OtlpSpanRecordLike",
+ "TraceRecordData",
+ "TraceSinkStats",
+ "TrajectoryRecordSink",
+ "TrajectoryStore",
+ "TrajectoryStoreSettings",
+ "WriteBatchResult",
+ "get_trajectory_runtime_sink",
+ "load_trajectory_store_settings",
+ "shutdown_trajectory_runtime",
+ "start_trajectory_runtime",
+ "sync_trajectory_runtime",
+]
diff --git a/jiuwenswarm/observability/config.py b/jiuwenswarm/observability/config.py
new file mode 100644
index 0000000000..41874b2d74
--- /dev/null
+++ b/jiuwenswarm/observability/config.py
@@ -0,0 +1,119 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Configuration resolution for the local trajectory read store."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from jiuwenswarm.common.config import get_config
+from jiuwenswarm.common.utils import get_user_workspace_dir
+
+DEFAULT_QUEUE_SIZE = 4096
+DEFAULT_BATCH_SIZE = 64
+DEFAULT_FLUSH_INTERVAL_MS = 200
+DEFAULT_RETENTION_DAYS = 7
+DEFAULT_POLL_INTERVAL_MS = 2000
+DEFAULT_DETAIL_MAX_BYTES = 4 * 1024 * 1024
+
+
+@dataclass(frozen=True, slots=True)
+class TrajectoryStoreSettings:
+ """Resolved settings shared by the AgentServer writer and Gateway reader."""
+
+ enabled: bool
+ database_path: Path
+ retention_days: int
+ queue_size: int
+ batch_size: int
+ flush_interval_ms: int
+ poll_interval_ms: int
+ detail_max_bytes: int = DEFAULT_DETAIL_MAX_BYTES
+
+
+def _as_bool(value: Any, default: bool) -> bool:
+ if value is None:
+ return default
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, (int, float)):
+ return bool(value)
+ normalized = str(value).strip().lower()
+ if normalized in {"1", "true", "yes", "on"}:
+ return True
+ if normalized in {"0", "false", "no", "off"}:
+ return False
+ return default
+
+
+def _positive_int(value: Any, default: int, *, minimum: int = 1) -> int:
+ try:
+ parsed = int(value)
+ except (TypeError, ValueError):
+ return default
+ return parsed if parsed >= minimum else default
+
+
+def _resolve_database_path(value: Any, workspace: Path) -> Path:
+ raw_path = str(value or "").strip()
+ if not raw_path:
+ return workspace / ".trace" / "trajectory.sqlite3"
+ configured = Path(raw_path).expanduser()
+ if configured.is_absolute():
+ return configured
+ return workspace / configured
+
+
+def load_trajectory_store_settings(
+ config: Mapping[str, Any] | None = None,
+ *,
+ workspace: Path | None = None,
+) -> TrajectoryStoreSettings:
+ """Resolve the ``trajectory_ui`` block without mutating user configuration.
+
+ Args:
+ config: Optional complete JiuwenSwarm configuration mapping.
+ workspace: Optional data root override, primarily for isolated tests.
+
+ Returns:
+ Validated settings with conservative defaults from the data contract.
+ """
+ source = config if config is not None else get_config()
+ raw_section = source.get("trajectory_ui", {}) if isinstance(source, Mapping) else {}
+ section = raw_section if isinstance(raw_section, Mapping) else {}
+ resolved_workspace = workspace if workspace is not None else get_user_workspace_dir()
+ return TrajectoryStoreSettings(
+ # The packaged config opts in explicitly. A caller supplying an older
+ # config without this section keeps the additive data plane disabled.
+ enabled=_as_bool(section.get("enabled"), False),
+ database_path=_resolve_database_path(section.get("db_path"), resolved_workspace),
+ retention_days=_positive_int(
+ section.get("retention_days"),
+ DEFAULT_RETENTION_DAYS,
+ ),
+ queue_size=_positive_int(section.get("queue_size"), DEFAULT_QUEUE_SIZE),
+ batch_size=_positive_int(section.get("batch_size"), DEFAULT_BATCH_SIZE),
+ flush_interval_ms=_positive_int(
+ section.get("flush_interval_ms"),
+ DEFAULT_FLUSH_INTERVAL_MS,
+ ),
+ poll_interval_ms=_positive_int(
+ section.get("poll_interval_ms"),
+ DEFAULT_POLL_INTERVAL_MS,
+ ),
+ detail_max_bytes=_positive_int(
+ section.get("detail_max_bytes"),
+ DEFAULT_DETAIL_MAX_BYTES,
+ minimum=64 * 1024,
+ ),
+ )
+
+
+__all__ = [
+ "DEFAULT_DETAIL_MAX_BYTES",
+ "TrajectoryStoreSettings",
+ "load_trajectory_store_settings",
+]
diff --git a/jiuwenswarm/observability/models.py b/jiuwenswarm/observability/models.py
new file mode 100644
index 0000000000..e8e85e3971
--- /dev/null
+++ b/jiuwenswarm/observability/models.py
@@ -0,0 +1,242 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Typed records used by the Swarm trajectory persistence boundary."""
+
+from __future__ import annotations
+
+import hashlib
+import time
+from dataclasses import dataclass
+from typing import Protocol
+
+
+class OtlpSpanRecordLike(Protocol):
+ """Structural contract implemented by the Agent Core OTLP processor record."""
+
+ raw_json: bytes
+ trace_id: str
+ span_id: str
+ parent_span_id: str | None
+ start_time_unix_nano: int
+ end_time_unix_nano: int
+ session_id: str | None
+ request_id: str | None
+ run_id: str | None
+ agent_mode: str | None
+ schema_version: str
+
+
+class OtlpSpanSnapshotRecordLike(Protocol):
+ """Structural contract implemented by the Agent Core live snapshot record."""
+
+ raw_json: bytes
+ trace_id: str
+ span_id: str
+ parent_span_id: str | None
+ start_time_unix_nano: int
+ observed_time_unix_nano: int
+ record_revision: int
+ update_kind: str
+ lifecycle: str
+ session_id: str | None
+ request_id: str | None
+ run_id: str | None
+ agent_mode: str | None
+ schema_version: str
+
+
+@dataclass(frozen=True, slots=True)
+class TraceRecordData:
+ """Immutable copy queued by Swarm without parsing or rewriting raw JSON."""
+
+ raw_json: bytes
+ raw_sha256: str
+ trace_id: str
+ span_id: str
+ parent_span_id: str | None
+ start_time_unix_nano: int
+ end_time_unix_nano: int
+ session_id: str | None
+ request_id: str | None
+ run_id: str | None
+ agent_mode: str | None
+ schema_version: str
+ source: str
+ created_at: int
+ lifecycle: str = "final"
+ record_revision: int = 1
+ observed_time_unix_nano: int = 0
+ update_kind: str = "completed"
+
+ @classmethod
+ def from_core_record(
+ cls,
+ record: OtlpSpanRecordLike,
+ *,
+ source: str = "processor",
+ created_at: int | None = None,
+ ) -> TraceRecordData:
+ """Copy one Core record while preserving its original UTF-8 bytes.
+
+ Args:
+ record: Core record implementing the frozen inter-repository contract.
+ source: Ingestion source label used only for diagnostics.
+ created_at: Optional Unix-second ingestion timestamp.
+
+ Returns:
+ A validated immutable record ready for the writer queue.
+
+ Raises:
+ TypeError: If ``raw_json`` is not bytes-like.
+ ValueError: If required identity or timestamp fields are invalid.
+ """
+ raw_value = record.raw_json
+ if not isinstance(raw_value, (bytes, bytearray, memoryview)):
+ raise TypeError("raw_json must be bytes-like")
+ raw_json = bytes(raw_value)
+ trace_id = str(record.trace_id or "").strip().lower()
+ span_id = str(record.span_id or "").strip().lower()
+ if not trace_id or not span_id:
+ raise ValueError("trace_id and span_id are required")
+ start_time = int(record.start_time_unix_nano)
+ end_time = int(record.end_time_unix_nano)
+ if start_time < 0 or end_time < 0:
+ raise ValueError("span timestamps must be non-negative")
+ source_value = str(source or "").strip()
+ if not source_value:
+ raise ValueError("source is required")
+ return cls(
+ raw_json=raw_json,
+ raw_sha256=hashlib.sha256(raw_json).hexdigest(),
+ trace_id=trace_id,
+ span_id=span_id,
+ parent_span_id=_normalize_text(record.parent_span_id, lowercase=True),
+ start_time_unix_nano=start_time,
+ end_time_unix_nano=end_time,
+ session_id=_normalize_text(record.session_id),
+ request_id=_normalize_text(record.request_id),
+ run_id=_normalize_text(record.run_id),
+ agent_mode=_normalize_text(record.agent_mode),
+ schema_version=str(record.schema_version or "1"),
+ source=source_value,
+ created_at=int(created_at if created_at is not None else time.time()),
+ lifecycle="final",
+ record_revision=max(1, int(getattr(record, "record_revision", 1))),
+ observed_time_unix_nano=max(
+ 0,
+ int(getattr(record, "observed_time_unix_nano", end_time) or end_time),
+ ),
+ update_kind="completed",
+ )
+
+ @classmethod
+ def from_core_snapshot(
+ cls,
+ record: OtlpSpanSnapshotRecordLike,
+ *,
+ source: str = "processor_snapshot",
+ created_at: int | None = None,
+ ) -> TraceRecordData:
+ """Copy one independently recoverable live span snapshot."""
+ raw_value = record.raw_json
+ if not isinstance(raw_value, (bytes, bytearray, memoryview)):
+ raise TypeError("raw_json must be bytes-like")
+ raw_json = bytes(raw_value)
+ trace_id = str(record.trace_id or "").strip().lower()
+ span_id = str(record.span_id or "").strip().lower()
+ if not trace_id or not span_id:
+ raise ValueError("trace_id and span_id are required")
+ start_time = int(record.start_time_unix_nano)
+ observed_time = int(record.observed_time_unix_nano)
+ revision = int(record.record_revision)
+ if start_time < 0 or observed_time < 0:
+ raise ValueError("span timestamps must be non-negative")
+ if revision < 1:
+ raise ValueError("record_revision must be positive")
+ source_value = str(source or "").strip()
+ update_kind = str(record.update_kind or "").strip()
+ snapshot_lifecycle = str(
+ getattr(record, "lifecycle", "running") or "running"
+ ).strip().lower()
+ if not source_value or not update_kind:
+ raise ValueError("source and update_kind are required")
+ if snapshot_lifecycle not in {"running", "provisional"}:
+ raise ValueError("snapshot lifecycle must be running or provisional")
+ return cls(
+ raw_json=raw_json,
+ raw_sha256=hashlib.sha256(raw_json).hexdigest(),
+ trace_id=trace_id,
+ span_id=span_id,
+ parent_span_id=_normalize_text(record.parent_span_id, lowercase=True),
+ start_time_unix_nano=start_time,
+ end_time_unix_nano=0,
+ session_id=_normalize_text(record.session_id),
+ request_id=_normalize_text(record.request_id),
+ run_id=_normalize_text(record.run_id),
+ agent_mode=_normalize_text(record.agent_mode),
+ schema_version=str(record.schema_version or "1"),
+ source=source_value,
+ created_at=int(created_at if created_at is not None else time.time()),
+ # ``running`` is the current storage contract. Accept the earlier
+ # ``provisional`` alias additively, but normalize it before the
+ # restart recovery and finalization state machine sees the record.
+ lifecycle="running",
+ record_revision=revision,
+ observed_time_unix_nano=observed_time,
+ update_kind=update_kind,
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class CommittedTraceUpdate:
+ """Highest committed revision for one session and trace in a writer batch."""
+
+ session_id: str
+ trace_id: str
+ revision: int
+ store_epoch: str | None = None
+ lifecycle: str = "final"
+
+
+@dataclass(frozen=True, slots=True)
+class WriteBatchResult:
+ """Result of one committed writer transaction."""
+
+ inserted: int
+ conflicts: int
+ updates: tuple[CommittedTraceUpdate, ...]
+
+
+@dataclass(frozen=True, slots=True)
+class TraceSinkStats:
+ """Snapshot of record sink counters."""
+
+ accepted: int
+ committed: int
+ dropped: int
+ failed: int
+ conflicts: int
+ queued: int
+ coalesced: int = 0
+ evicted_provisional: int = 0
+ dropped_final: int = 0
+ stale_ignored: int = 0
+
+
+def _normalize_text(value: str | None, *, lowercase: bool = False) -> str | None:
+ if value is None:
+ return None
+ normalized = str(value).strip()
+ if not normalized:
+ return None
+ return normalized.lower() if lowercase else normalized
+
+
+__all__ = [
+ "CommittedTraceUpdate",
+ "OtlpSpanRecordLike",
+ "OtlpSpanSnapshotRecordLike",
+ "TraceRecordData",
+ "TraceSinkStats",
+ "WriteBatchResult",
+]
diff --git a/jiuwenswarm/observability/runtime.py b/jiuwenswarm/observability/runtime.py
new file mode 100644
index 0000000000..234b344dcd
--- /dev/null
+++ b/jiuwenswarm/observability/runtime.py
@@ -0,0 +1,183 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""AgentServer lifecycle for the Core OTLP record consumer."""
+
+from __future__ import annotations
+
+import logging
+import threading
+from typing import Protocol
+
+from jiuwenswarm.observability.config import (
+ TrajectoryStoreSettings,
+ load_trajectory_store_settings,
+)
+from jiuwenswarm.observability.sink import CommitCallback, TrajectoryRecordSink
+from jiuwenswarm.observability.updates import trajectory_update_broker
+
+logger = logging.getLogger(__name__)
+
+
+class _SpanRecordProcessorLike(Protocol):
+ def register_consumer(self, consumer: TrajectoryRecordSink) -> None:
+ """Register one sink by object identity."""
+ ...
+
+ def unregister_consumer(self, consumer: TrajectoryRecordSink) -> None:
+ """Unregister one sink by object identity."""
+ ...
+
+
+_runtime_lock = threading.RLock()
+_runtime_sink: TrajectoryRecordSink | None = None
+_runtime_processor: _SpanRecordProcessorLike | None = None
+_runtime_settings: TrajectoryStoreSettings | None = None
+
+
+def sync_trajectory_runtime(
+ settings: TrajectoryStoreSettings | None = None,
+ *,
+ on_commit: CommitCallback | None = None,
+) -> TrajectoryRecordSink | None:
+ """Synchronize the AgentServer sink with the current trajectory settings."""
+ resolved = settings or load_trajectory_store_settings()
+ if not resolved.enabled:
+ shutdown_trajectory_runtime()
+ return None
+ return start_trajectory_runtime(resolved, on_commit=on_commit)
+
+
+def start_trajectory_runtime(
+ settings: TrajectoryStoreSettings | None = None,
+ *,
+ on_commit: CommitCallback | None = None,
+) -> TrajectoryRecordSink | None:
+ """Start and register the process-wide sink once.
+
+ The sink is ready before it is exposed to Core. A settings change performs
+ the inverse lifecycle first: unregister, drain, close, then replace.
+ """
+ global _runtime_processor, _runtime_settings, _runtime_sink
+
+ resolved = settings or load_trajectory_store_settings()
+ if not resolved.enabled:
+ shutdown_trajectory_runtime()
+ return None
+ with _runtime_lock:
+ if (
+ _runtime_sink is not None
+ and _runtime_processor is not None
+ and _runtime_settings == resolved
+ ):
+ _runtime_sink.set_commit_callback(_combined_commit_callback(on_commit))
+ return _runtime_sink
+ if _runtime_sink is not None or _runtime_processor is not None:
+ if not _shutdown_locked():
+ raise RuntimeError("Previous trajectory runtime did not stop cleanly")
+
+ sink = _create_sink(
+ resolved,
+ on_commit=_combined_commit_callback(on_commit),
+ )
+ try:
+ sink.start()
+ processor = _get_core_span_record_processor()
+ processor.register_consumer(sink)
+ except Exception:
+ try:
+ sink.close()
+ except Exception:
+ logger.exception("Trajectory runtime startup cleanup failed")
+ raise
+ _runtime_sink = sink
+ _runtime_processor = processor
+ _runtime_settings = resolved
+ logger.info(
+ "Trajectory runtime enabled: database=%s queue_size=%d",
+ resolved.database_path,
+ resolved.queue_size,
+ )
+ return sink
+
+
+def shutdown_trajectory_runtime(*, timeout: float = 15.0) -> bool:
+ """Unregister first, then drain and close the process-wide sink."""
+ with _runtime_lock:
+ return _shutdown_locked(timeout=timeout)
+
+
+def get_trajectory_runtime_sink() -> TrajectoryRecordSink | None:
+ """Return the active process-local sink for diagnostics."""
+ with _runtime_lock:
+ return _runtime_sink
+
+
+def _shutdown_locked(*, timeout: float = 15.0) -> bool:
+ global _runtime_processor, _runtime_settings, _runtime_sink
+
+ sink = _runtime_sink
+ processor = _runtime_processor
+ if sink is None and processor is None:
+ _runtime_settings = None
+ return True
+
+ unregistered = processor is None
+ if processor is not None and sink is not None:
+ try:
+ processor.unregister_consumer(sink)
+ except Exception:
+ logger.exception("Trajectory runtime consumer unregister failed")
+ # Keep the still-running sink reachable and registered. Closing it
+ # here would leave a stopped singleton behind while Core may still
+ # retain the consumer reference.
+ return False
+ else:
+ _runtime_processor = None
+ unregistered = True
+
+ stopped = sink is None
+ if sink is not None:
+ try:
+ stopped = sink.close(timeout=timeout)
+ except Exception:
+ logger.exception("Trajectory runtime sink shutdown failed")
+ stopped = False
+
+ if unregistered and stopped:
+ _runtime_sink = None
+ _runtime_processor = None
+ _runtime_settings = None
+ logger.info("Trajectory runtime disabled")
+ return True
+ return False
+
+
+def _create_sink(
+ settings: TrajectoryStoreSettings,
+ *,
+ on_commit: CommitCallback | None,
+) -> TrajectoryRecordSink:
+ return TrajectoryRecordSink(settings, on_commit=on_commit)
+
+
+def _combined_commit_callback(on_commit: CommitCallback | None) -> CommitCallback:
+ def _publish(updates) -> None:
+ trajectory_update_broker.publish(updates)
+ if on_commit is not None:
+ on_commit(updates)
+
+ return _publish
+
+
+def _get_core_span_record_processor() -> _SpanRecordProcessorLike:
+ from openjiuwen.extensions.observability.demand import get_span_record_processor
+
+ return get_span_record_processor()
+
+
+__all__ = [
+ "get_trajectory_runtime_sink",
+ "shutdown_trajectory_runtime",
+ "start_trajectory_runtime",
+ "sync_trajectory_runtime",
+]
diff --git a/jiuwenswarm/observability/sink.py b/jiuwenswarm/observability/sink.py
new file mode 100644
index 0000000000..9599740b27
--- /dev/null
+++ b/jiuwenswarm/observability/sink.py
@@ -0,0 +1,386 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Bounded AgentServer consumer and SQLite writer for Core OTLP records."""
+
+from __future__ import annotations
+
+import logging
+import queue
+import sqlite3
+import threading
+import time
+from collections import OrderedDict
+from collections.abc import Callable
+
+from jiuwenswarm.observability.config import TrajectoryStoreSettings
+from jiuwenswarm.observability.models import (
+ CommittedTraceUpdate,
+ OtlpSpanRecordLike,
+ OtlpSpanSnapshotRecordLike,
+ TraceRecordData,
+ TraceSinkStats,
+)
+from jiuwenswarm.observability.store import TrajectoryStore
+
+logger = logging.getLogger(__name__)
+
+CommitCallback = Callable[[tuple[CommittedTraceUpdate, ...]], None]
+_RETENTION_INTERVAL_SECONDS = 3600
+# One retry keeps the two five-second SQLite busy waits below the default
+# fifteen-second shutdown deadline, including the retry delay.
+_WRITE_RETRY_DELAYS_SECONDS = (0.05,)
+
+
+class TrajectoryRecordSink:
+ """Fast Core consumer backed by a bounded queue and one writer thread."""
+
+ def __init__(
+ self,
+ settings: TrajectoryStoreSettings,
+ *,
+ on_commit: CommitCallback | None = None,
+ store: TrajectoryStore | None = None,
+ ) -> None:
+ self.settings = settings
+ self._on_commit = on_commit
+ self._store = store or TrajectoryStore(
+ settings.database_path,
+ retention_days=settings.retention_days,
+ )
+ self._queue: queue.Queue[OtlpSpanRecordLike] = queue.Queue(
+ maxsize=settings.queue_size,
+ )
+ self._snapshot_pending: OrderedDict[
+ tuple[str, str], OtlpSpanSnapshotRecordLike
+ ] = OrderedDict()
+ self._work_available = threading.Event()
+ self._state_lock = threading.Lock()
+ self._stats_lock = threading.Lock()
+ self._ready = threading.Event()
+ self._stop_requested = threading.Event()
+ self._thread: threading.Thread | None = None
+ self._startup_error: BaseException | None = None
+ self._accepting = False
+ self._accepted = 0
+ self._committed = 0
+ self._dropped = 0
+ self._failed = 0
+ self._conflicts = 0
+ self._coalesced = 0
+ self._evicted_provisional = 0
+ self._dropped_final = 0
+ self._stale_ignored = 0
+
+ def start(self, *, timeout: float = 10.0) -> None:
+ """Initialize SQLite on the writer thread and enable fast consumption.
+
+ Args:
+ timeout: Maximum seconds to wait for schema initialization.
+
+ Raises:
+ RuntimeError: If the writer cannot initialize or times out.
+ """
+ with self._state_lock:
+ if self._thread is not None:
+ if self._startup_error is not None:
+ raise RuntimeError("Trajectory writer failed to initialize") from self._startup_error
+ return
+ self._startup_error = None
+ self._stop_requested.clear()
+ self._ready.clear()
+ thread = threading.Thread(
+ target=self._writer_main,
+ name="trajectory-record-writer",
+ daemon=True,
+ )
+ self._thread = thread
+ thread.start()
+ if not self._ready.wait(timeout=max(0.1, float(timeout))):
+ self._stop_requested.set()
+ raise RuntimeError("Trajectory writer initialization timed out")
+ if self._startup_error is not None:
+ raise RuntimeError("Trajectory writer failed to initialize") from self._startup_error
+ with self._state_lock:
+ if (
+ self._thread is not thread
+ or self._stop_requested.is_set()
+ or not thread.is_alive()
+ ):
+ raise RuntimeError("Trajectory writer stopped during initialization")
+ self._accepting = True
+
+ def consume(self, record: OtlpSpanRecordLike) -> None:
+ """Atomically accept one frozen Core record without storage work.
+
+ Core's processor publishes an immutable record whose ``raw_json`` is
+ already ``bytes``. Validation, copying, hashing, and SQLite work stay
+ on the writer thread so a full queue remains a constant-cost decision.
+ """
+ if not isinstance(getattr(record, "raw_json", None), bytes):
+ self._increment("failed")
+ logger.warning("Trajectory record rejected before queueing: raw_json must be bytes")
+ return
+ with self._state_lock:
+ if not self._accepting:
+ self._increment("dropped")
+ logger.warning("Trajectory record dropped because the sink is not accepting records")
+ return
+ identity = (
+ str(getattr(record, "trace_id", "") or "").strip().lower(),
+ str(getattr(record, "span_id", "") or "").strip().lower(),
+ )
+ if identity in self._snapshot_pending:
+ self._snapshot_pending.pop(identity, None)
+ self._increment("coalesced")
+ try:
+ # Keep this non-blocking enqueue under the same lock used by
+ # close(): every accepted record is therefore visible before
+ # the writer receives its stop request.
+ self._queue.put_nowait(record)
+ except queue.Full:
+ self._increment("dropped")
+ self._increment("dropped_final")
+ logger.warning(
+ "Trajectory queue is full; SQLite fan-out dropped the record "
+ "while other configured exporters remain unaffected: "
+ "trace_id=%s span_id=%s",
+ getattr(record, "trace_id", None),
+ getattr(record, "span_id", None),
+ )
+ return
+ self._work_available.set()
+ self._increment("accepted")
+
+ def consume_snapshot(self, record: OtlpSpanSnapshotRecordLike) -> None:
+ """Accept a live snapshot using identity-keyed latest-wins coalescing."""
+ if not isinstance(getattr(record, "raw_json", None), bytes):
+ self._increment("failed")
+ logger.warning("Trajectory snapshot rejected before queueing: raw_json must be bytes")
+ return
+ identity = (
+ str(getattr(record, "trace_id", "") or "").strip().lower(),
+ str(getattr(record, "span_id", "") or "").strip().lower(),
+ )
+ try:
+ revision = int(getattr(record, "record_revision"))
+ except (TypeError, ValueError, OverflowError):
+ self._increment("failed")
+ logger.warning("Trajectory snapshot rejected before queueing: invalid record_revision")
+ return
+ if not identity[0] or not identity[1] or revision < 1:
+ self._increment("failed")
+ logger.warning("Trajectory snapshot rejected before queueing: invalid identity or revision")
+ return
+ with self._state_lock:
+ if not self._accepting:
+ self._increment("dropped")
+ return
+ current = self._snapshot_pending.get(identity)
+ if current is not None:
+ current_revision = int(getattr(current, "record_revision", 0))
+ if revision <= current_revision:
+ self._increment("stale_ignored")
+ return
+ self._snapshot_pending[identity] = record
+ self._snapshot_pending.move_to_end(identity)
+ self._increment("coalesced")
+ self._work_available.set()
+ self._increment("accepted")
+ return
+ if self._queue.qsize() + len(self._snapshot_pending) >= self.settings.queue_size:
+ if self._snapshot_pending:
+ self._snapshot_pending.popitem(last=False)
+ self._increment("evicted_provisional")
+ self._increment("dropped")
+ else:
+ self._increment("dropped")
+ return
+ self._snapshot_pending[identity] = record
+ self._work_available.set()
+ self._increment("accepted")
+
+ def close(self, *, timeout: float = 15.0) -> bool:
+ """Stop accepting, drain queued records, and close SQLite.
+
+ Args:
+ timeout: Maximum seconds to wait for the writer thread.
+
+ Returns:
+ ``True`` when the writer drained and stopped before the timeout.
+ """
+ with self._state_lock:
+ self._accepting = False
+ thread = self._thread
+ if thread is None:
+ return True
+ self._stop_requested.set()
+ self._work_available.set()
+ thread.join(timeout=max(0.1, float(timeout)))
+ stopped = not thread.is_alive()
+ if not stopped:
+ logger.warning(
+ "Trajectory writer shutdown timed out with %d queued records",
+ self._queue.qsize(),
+ )
+ return False
+ with self._state_lock:
+ self._thread = None
+ return True
+
+ def stats(self) -> TraceSinkStats:
+ """Return an atomic snapshot of sink counters."""
+ with self._stats_lock:
+ return TraceSinkStats(
+ accepted=self._accepted,
+ committed=self._committed,
+ dropped=self._dropped,
+ failed=self._failed,
+ conflicts=self._conflicts,
+ queued=self._queue.qsize() + len(self._snapshot_pending),
+ coalesced=self._coalesced,
+ evicted_provisional=self._evicted_provisional,
+ dropped_final=self._dropped_final,
+ stale_ignored=self._stale_ignored,
+ )
+
+ def set_commit_callback(self, on_commit: CommitCallback | None) -> None:
+ """Replace the post-commit notification callback atomically."""
+ with self._state_lock:
+ self._on_commit = on_commit
+
+ def _writer_main(self) -> None:
+ try:
+ self._store.initialize()
+ try:
+ self._store.delete_expired()
+ except Exception:
+ logger.exception("Initial trajectory retention cleanup failed")
+ except BaseException as exc:
+ self._startup_error = exc
+ self._ready.set()
+ logger.exception("Trajectory writer initialization failed")
+ return
+ self._ready.set()
+ next_retention_at = time.monotonic() + _RETENTION_INTERVAL_SECONDS
+ flush_timeout = self.settings.flush_interval_ms / 1000
+ try:
+ while (
+ not self._stop_requested.is_set()
+ or not self._queue.empty()
+ or bool(self._snapshot_pending)
+ ):
+ batch = self._take_batch(flush_timeout)
+ if batch:
+ self._write_batch(batch)
+ if time.monotonic() >= next_retention_at:
+ try:
+ self._store.delete_expired()
+ except Exception:
+ logger.exception("Trajectory retention cleanup failed")
+ next_retention_at = time.monotonic() + _RETENTION_INTERVAL_SECONDS
+ finally:
+ self._store.close()
+
+ def _take_batch(
+ self,
+ timeout: float,
+ ) -> list[tuple[OtlpSpanRecordLike | OtlpSpanSnapshotRecordLike, bool]]:
+ self._work_available.wait(timeout=max(0.001, timeout))
+ self._work_available.clear()
+ batch: list[tuple[OtlpSpanRecordLike | OtlpSpanSnapshotRecordLike, bool]] = []
+ while len(batch) < self.settings.batch_size:
+ try:
+ batch.append((self._queue.get_nowait(), True))
+ except queue.Empty:
+ break
+ with self._state_lock:
+ while len(batch) < self.settings.batch_size and self._snapshot_pending:
+ _identity, snapshot = self._snapshot_pending.popitem(last=False)
+ batch.append((snapshot, False))
+ if not self._queue.empty() or self._snapshot_pending:
+ self._work_available.set()
+ return batch
+
+ def _write_batch(
+ self,
+ batch: list[tuple[OtlpSpanRecordLike | OtlpSpanSnapshotRecordLike, bool]],
+ ) -> None:
+ try:
+ records: list[TraceRecordData] = []
+ for record, queued_final in batch:
+ try:
+ if queued_final:
+ records.append(TraceRecordData.from_core_record(record))
+ else:
+ records.append(TraceRecordData.from_core_snapshot(record))
+ except (AttributeError, TypeError, ValueError, OverflowError) as exc:
+ self._increment("failed")
+ logger.warning("Trajectory record rejected by writer: %s", exc)
+ if not records:
+ return
+ result = self._write_records_with_retry(records)
+ except Exception:
+ self._increment("failed", len(records))
+ logger.exception(
+ "Trajectory batch commit failed; records remain available only through existing exporters"
+ )
+ else:
+ self._increment("committed", result.inserted)
+ self._increment("conflicts", result.conflicts)
+ with self._state_lock:
+ on_commit = self._on_commit
+ if result.updates and on_commit is not None:
+ try:
+ on_commit(result.updates)
+ except Exception:
+ logger.exception("Trajectory commit notification callback failed")
+ finally:
+ for _record, queued_final in batch:
+ if queued_final:
+ self._queue.task_done()
+
+ def _write_records_with_retry(
+ self,
+ records: list[TraceRecordData],
+ ):
+ """Retry transient SQLite contention without creating an infinite drain."""
+ for attempt, delay in enumerate((*_WRITE_RETRY_DELAYS_SECONDS, None)):
+ try:
+ return self._store.write_records(records)
+ except sqlite3.OperationalError as exc:
+ message = str(exc).lower()
+ retryable = "locked" in message or "busy" in message
+ if not retryable or delay is None:
+ raise
+ logger.warning(
+ "Trajectory SQLite commit contention; retrying batch: attempt=%d",
+ attempt + 1,
+ )
+ time.sleep(delay)
+ raise AssertionError("unreachable trajectory write retry state")
+
+ def _increment(self, counter: str, amount: int = 1) -> None:
+ with self._stats_lock:
+ if counter == "accepted":
+ self._accepted += amount
+ elif counter == "committed":
+ self._committed += amount
+ elif counter == "dropped":
+ self._dropped += amount
+ elif counter == "failed":
+ self._failed += amount
+ elif counter == "conflicts":
+ self._conflicts += amount
+ elif counter == "coalesced":
+ self._coalesced += amount
+ elif counter == "evicted_provisional":
+ self._evicted_provisional += amount
+ elif counter == "dropped_final":
+ self._dropped_final += amount
+ elif counter == "stale_ignored":
+ self._stale_ignored += amount
+ else:
+ raise ValueError(f"unknown trajectory counter: {counter}")
+
+
+__all__ = ["CommitCallback", "TrajectoryRecordSink"]
diff --git a/jiuwenswarm/observability/store.py b/jiuwenswarm/observability/store.py
new file mode 100644
index 0000000000..c960a5717f
--- /dev/null
+++ b/jiuwenswarm/observability/store.py
@@ -0,0 +1,1948 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Lossless SQLite storage and read queries for single-Agent OTLP records."""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import json
+import logging
+import math
+import sqlite3
+import time
+import uuid
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+import aiosqlite
+
+from jiuwenswarm.common.mode_matrix import SINGLE_AGENT_CANONICAL_MODES
+from jiuwenswarm.observability.config import DEFAULT_DETAIL_MAX_BYTES
+from jiuwenswarm.observability.models import (
+ CommittedTraceUpdate,
+ TraceRecordData,
+ WriteBatchResult,
+)
+
+logger = logging.getLogger(__name__)
+
+_SCHEMA_VERSION = 3
+_BUSY_TIMEOUT_MS = 5000
+_MAX_SQLITE_INTEGER = (1 << 63) - 1
+_MAX_JSON_NESTING_DEPTH = 256
+_ABSENT_STORE_EPOCH = "absent"
+_SINGLE_AGENT_MODE_VALUES = tuple(sorted(SINGLE_AGENT_CANONICAL_MODES))
+_SINGLE_AGENT_MODE_PLACEHOLDERS = ",".join("?" for _ in _SINGLE_AGENT_MODE_VALUES)
+_ELIGIBLE_TRACES_CTE = f"""
+eligible_traces AS (
+ SELECT trace_id
+ FROM trajectory_current_records
+ GROUP BY trace_id
+ HAVING SUM(
+ CASE
+ WHEN agent_mode IS NOT NULL
+ AND TRIM(agent_mode) <> ''
+ AND LOWER(TRIM(agent_mode)) IN ({_SINGLE_AGENT_MODE_PLACEHOLDERS})
+ THEN 1 ELSE 0
+ END
+ ) > 0
+ AND SUM(
+ CASE
+ WHEN agent_mode IS NOT NULL
+ AND TRIM(agent_mode) <> ''
+ AND LOWER(TRIM(agent_mode)) NOT IN ({_SINGLE_AGENT_MODE_PLACEHOLDERS})
+ THEN 1 ELSE 0
+ END
+ ) = 0
+)
+"""
+
+_SCHEMA_SQL = """
+CREATE TABLE IF NOT EXISTS otlp_span_records (
+ ingest_seq INTEGER PRIMARY KEY AUTOINCREMENT,
+ trace_id TEXT NOT NULL,
+ span_id TEXT NOT NULL,
+ parent_span_id TEXT,
+ session_id TEXT,
+ request_id TEXT,
+ run_id TEXT,
+ agent_mode TEXT,
+ start_time_unix_nano INTEGER NOT NULL,
+ end_time_unix_nano INTEGER NOT NULL,
+ schema_version TEXT NOT NULL,
+ source TEXT NOT NULL DEFAULT 'processor',
+ created_at INTEGER NOT NULL,
+ has_error INTEGER NOT NULL DEFAULT 0,
+ raw_json BLOB NOT NULL,
+ raw_sha256 TEXT NOT NULL,
+ UNIQUE(trace_id, span_id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_otlp_records_session_start_ingest
+ ON otlp_span_records(session_id, start_time_unix_nano DESC, ingest_seq DESC);
+CREATE INDEX IF NOT EXISTS idx_otlp_records_session_ingest
+ ON otlp_span_records(session_id, ingest_seq);
+CREATE INDEX IF NOT EXISTS idx_otlp_records_session_request_ingest
+ ON otlp_span_records(session_id, request_id, ingest_seq);
+CREATE INDEX IF NOT EXISTS idx_otlp_records_trace_ingest
+ ON otlp_span_records(trace_id, ingest_seq);
+
+CREATE TABLE IF NOT EXISTS otlp_record_conflicts (
+ conflict_id INTEGER PRIMARY KEY AUTOINCREMENT,
+ trace_id TEXT NOT NULL,
+ span_id TEXT NOT NULL,
+ existing_sha256 TEXT NOT NULL,
+ incoming_sha256 TEXT NOT NULL,
+ source TEXT NOT NULL,
+ created_at INTEGER NOT NULL
+);
+
+CREATE INDEX IF NOT EXISTS idx_otlp_conflicts_identity
+ ON otlp_record_conflicts(trace_id, span_id, created_at);
+
+CREATE TABLE IF NOT EXISTS trajectory_store_state (
+ singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
+ store_epoch TEXT NOT NULL,
+ max_ingest_seq INTEGER NOT NULL,
+ max_change_seq INTEGER NOT NULL DEFAULT 0
+);
+
+CREATE TABLE IF NOT EXISTS trajectory_current_records (
+ trace_id TEXT NOT NULL,
+ span_id TEXT NOT NULL,
+ parent_span_id TEXT,
+ session_id TEXT,
+ request_id TEXT,
+ run_id TEXT,
+ agent_mode TEXT,
+ lifecycle TEXT NOT NULL,
+ record_revision INTEGER NOT NULL,
+ change_seq INTEGER NOT NULL,
+ start_time_unix_nano INTEGER NOT NULL,
+ observed_time_unix_nano INTEGER NOT NULL,
+ end_time_unix_nano INTEGER NOT NULL,
+ schema_version TEXT NOT NULL,
+ source TEXT NOT NULL,
+ created_at INTEGER NOT NULL,
+ has_error INTEGER NOT NULL DEFAULT 0,
+ raw_json BLOB NOT NULL,
+ raw_sha256 TEXT NOT NULL,
+ update_kind TEXT NOT NULL,
+ PRIMARY KEY(trace_id, span_id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_trajectory_current_session_change
+ ON trajectory_current_records(session_id, change_seq);
+CREATE INDEX IF NOT EXISTS idx_trajectory_current_trace_change
+ ON trajectory_current_records(trace_id, change_seq);
+
+CREATE TABLE IF NOT EXISTS trajectory_changes (
+ change_seq INTEGER PRIMARY KEY AUTOINCREMENT,
+ trace_id TEXT NOT NULL,
+ span_id TEXT NOT NULL,
+ parent_span_id TEXT,
+ session_id TEXT,
+ request_id TEXT,
+ run_id TEXT,
+ agent_mode TEXT,
+ lifecycle TEXT NOT NULL,
+ record_revision INTEGER NOT NULL,
+ operation TEXT NOT NULL,
+ start_time_unix_nano INTEGER NOT NULL,
+ observed_time_unix_nano INTEGER NOT NULL,
+ end_time_unix_nano INTEGER NOT NULL,
+ schema_version TEXT NOT NULL,
+ source TEXT NOT NULL,
+ created_at INTEGER NOT NULL,
+ has_error INTEGER NOT NULL DEFAULT 0,
+ raw_json BLOB NOT NULL,
+ raw_sha256 TEXT NOT NULL,
+ update_kind TEXT NOT NULL
+);
+
+CREATE INDEX IF NOT EXISTS idx_trajectory_changes_session_change
+ ON trajectory_changes(session_id, change_seq);
+CREATE INDEX IF NOT EXISTS idx_trajectory_changes_trace_change
+ ON trajectory_changes(trace_id, change_seq);
+"""
+
+
+class TrajectoryCursorError(ValueError):
+ """Raised when an opaque trajectory cursor is malformed."""
+
+
+class TrajectoryStore:
+ """Single-threaded SQLite writer that preserves raw record bytes unchanged."""
+
+ def __init__(self, database_path: Path, *, retention_days: int = 7) -> None:
+ self.database_path = Path(database_path)
+ self.retention_days = max(1, int(retention_days))
+ self._connection: sqlite3.Connection | None = None
+
+ def initialize(self) -> None:
+ """Open the writer connection and initialize the idempotent schema."""
+ if self._connection is not None:
+ return
+ self.database_path.parent.mkdir(parents=True, exist_ok=True)
+ connection = sqlite3.connect(str(self.database_path), timeout=_BUSY_TIMEOUT_MS / 1000)
+ connection.row_factory = sqlite3.Row
+ try:
+ connection.execute(f"PRAGMA busy_timeout={_BUSY_TIMEOUT_MS}")
+ connection.execute("PRAGMA foreign_keys=ON")
+ connection.execute("PRAGMA journal_mode=WAL")
+ connection.execute("PRAGMA synchronous=NORMAL")
+ connection.executescript(_SCHEMA_SQL)
+ self._ensure_store_state_columns(connection)
+ removed = self._remove_missing_final_current(connection)
+ migrated = self._migrate_final_current(connection)
+ self._abandon_running_current(connection)
+ connection.execute(f"PRAGMA user_version={_SCHEMA_VERSION}")
+ self._initialize_store_state(connection)
+ if migrated or removed:
+ self._rotate_store_epoch(connection)
+ connection.commit()
+ except Exception:
+ connection.close()
+ raise
+ self._connection = connection
+
+ def close(self) -> None:
+ """Commit and close the writer connection if it is open."""
+ connection = self._connection
+ if connection is None:
+ return
+ try:
+ connection.commit()
+ finally:
+ connection.close()
+ self._connection = None
+
+ def write_records(self, records: Sequence[TraceRecordData]) -> WriteBatchResult:
+ """Commit one batch and return coalesced session/trace revisions.
+
+ Args:
+ records: Immutable records copied from Core before queueing.
+
+ Returns:
+ Counts and highest committed revision for each visible trace.
+ """
+ if not records:
+ return WriteBatchResult(inserted=0, conflicts=0, updates=())
+ connection = self._require_connection()
+ inserted = 0
+ conflicts = 0
+ changed_trace_ids: set[str] = set()
+ incoming_trace_ids = sorted({record.trace_id for record in records})
+ try:
+ connection.execute("BEGIN IMMEDIATE")
+ eligibility_before = self._trace_eligibility(connection, incoming_trace_ids)
+ for record in records:
+ if record.lifecycle != "final":
+ if self._upsert_current_record(connection, record):
+ inserted += 1
+ changed_trace_ids.add(record.trace_id)
+ continue
+ cursor = connection.execute(
+ """
+ INSERT INTO otlp_span_records (
+ trace_id,
+ span_id,
+ parent_span_id,
+ session_id,
+ request_id,
+ run_id,
+ agent_mode,
+ start_time_unix_nano,
+ end_time_unix_nano,
+ schema_version,
+ source,
+ created_at,
+ has_error,
+ raw_json,
+ raw_sha256
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(trace_id, span_id) DO NOTHING
+ """,
+ (
+ record.trace_id,
+ record.span_id,
+ record.parent_span_id,
+ record.session_id,
+ record.request_id,
+ record.run_id,
+ record.agent_mode,
+ record.start_time_unix_nano,
+ record.end_time_unix_nano,
+ record.schema_version,
+ record.source,
+ record.created_at,
+ 0,
+ sqlite3.Binary(record.raw_json),
+ record.raw_sha256,
+ ),
+ )
+ if cursor.rowcount == 1:
+ inserted += 1
+ changed_trace_ids.add(record.trace_id)
+ has_error = _record_has_error(record.raw_json)
+ if has_error:
+ connection.execute(
+ """
+ UPDATE otlp_span_records
+ SET has_error = 1
+ WHERE trace_id = ? AND span_id = ?
+ """,
+ (record.trace_id, record.span_id),
+ )
+ self._upsert_current_record(connection, record, has_error=has_error)
+ continue
+ existing = connection.execute(
+ """
+ SELECT raw_sha256
+ FROM otlp_span_records
+ WHERE trace_id = ? AND span_id = ?
+ """,
+ (record.trace_id, record.span_id),
+ ).fetchone()
+ existing_sha256 = str(existing["raw_sha256"]) if existing is not None else ""
+ if existing_sha256 == record.raw_sha256:
+ self._upsert_current_record(connection, record)
+ continue
+ conflicts += 1
+ connection.execute(
+ """
+ INSERT INTO otlp_record_conflicts (
+ trace_id,
+ span_id,
+ existing_sha256,
+ incoming_sha256,
+ source,
+ created_at
+ ) VALUES (?, ?, ?, ?, ?, ?)
+ """,
+ (
+ record.trace_id,
+ record.span_id,
+ existing_sha256,
+ record.raw_sha256,
+ record.source,
+ record.created_at,
+ ),
+ )
+ logger.warning(
+ "Trajectory record conflict preserved the first raw record: trace_id=%s span_id=%s",
+ record.trace_id,
+ record.span_id,
+ )
+
+ changed_trace_ids.update(self._reconcile_orphans(connection, records))
+ eligibility_after = self._trace_eligibility(connection, incoming_trace_ids)
+ eligibility_changed = any(
+ eligibility_before[trace_id][0]
+ and eligibility_before[trace_id][1] != eligibility_after[trace_id][1]
+ for trace_id in incoming_trace_ids
+ )
+ if eligibility_changed:
+ self._rotate_store_epoch(connection)
+ else:
+ self._sync_max_ingest_seq(connection)
+ updates = self._committed_updates(connection, changed_trace_ids)
+ connection.commit()
+ except Exception:
+ connection.rollback()
+ raise
+ return WriteBatchResult(
+ inserted=inserted,
+ conflicts=conflicts,
+ updates=updates,
+ )
+
+ @staticmethod
+ def _upsert_current_record(
+ connection: sqlite3.Connection,
+ record: TraceRecordData,
+ *,
+ has_error: bool | None = None,
+ ) -> bool:
+ current = connection.execute(
+ """
+ SELECT lifecycle, record_revision, raw_sha256
+ FROM trajectory_current_records
+ WHERE trace_id = ? AND span_id = ?
+ """,
+ (record.trace_id, record.span_id),
+ ).fetchone()
+ if current is not None:
+ current_lifecycle = str(current["lifecycle"])
+ current_revision = int(current["record_revision"])
+ if current_lifecycle == "final":
+ return False
+ if record.lifecycle != "final" and record.record_revision <= current_revision:
+ return False
+ resolved_has_error = (
+ _record_has_error(record.raw_json) if has_error is None else has_error
+ )
+ cursor = connection.execute(
+ """
+ INSERT INTO trajectory_changes (
+ trace_id, span_id, parent_span_id, session_id, request_id,
+ run_id, agent_mode, lifecycle, record_revision, operation,
+ start_time_unix_nano, observed_time_unix_nano,
+ end_time_unix_nano, schema_version, source, created_at,
+ has_error, raw_json, raw_sha256, update_kind
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'upsert', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ record.trace_id,
+ record.span_id,
+ record.parent_span_id,
+ record.session_id,
+ record.request_id,
+ record.run_id,
+ record.agent_mode,
+ record.lifecycle,
+ record.record_revision,
+ record.start_time_unix_nano,
+ record.observed_time_unix_nano,
+ record.end_time_unix_nano,
+ record.schema_version,
+ record.source,
+ record.created_at,
+ int(resolved_has_error),
+ sqlite3.Binary(record.raw_json),
+ record.raw_sha256,
+ record.update_kind,
+ ),
+ )
+ change_seq = int(cursor.lastrowid)
+ connection.execute(
+ """
+ INSERT INTO trajectory_current_records (
+ trace_id, span_id, parent_span_id, session_id, request_id,
+ run_id, agent_mode, lifecycle, record_revision, change_seq,
+ start_time_unix_nano, observed_time_unix_nano,
+ end_time_unix_nano, schema_version, source, created_at,
+ has_error, raw_json, raw_sha256, update_kind
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(trace_id, span_id) DO UPDATE SET
+ parent_span_id = excluded.parent_span_id,
+ session_id = COALESCE(excluded.session_id, trajectory_current_records.session_id),
+ request_id = COALESCE(excluded.request_id, trajectory_current_records.request_id),
+ run_id = COALESCE(excluded.run_id, trajectory_current_records.run_id),
+ agent_mode = COALESCE(excluded.agent_mode, trajectory_current_records.agent_mode),
+ lifecycle = excluded.lifecycle,
+ record_revision = excluded.record_revision,
+ change_seq = excluded.change_seq,
+ start_time_unix_nano = excluded.start_time_unix_nano,
+ observed_time_unix_nano = excluded.observed_time_unix_nano,
+ end_time_unix_nano = excluded.end_time_unix_nano,
+ schema_version = excluded.schema_version,
+ source = excluded.source,
+ created_at = excluded.created_at,
+ has_error = excluded.has_error,
+ raw_json = excluded.raw_json,
+ raw_sha256 = excluded.raw_sha256,
+ update_kind = excluded.update_kind
+ """,
+ (
+ record.trace_id,
+ record.span_id,
+ record.parent_span_id,
+ record.session_id,
+ record.request_id,
+ record.run_id,
+ record.agent_mode,
+ record.lifecycle,
+ record.record_revision,
+ change_seq,
+ record.start_time_unix_nano,
+ record.observed_time_unix_nano,
+ record.end_time_unix_nano,
+ record.schema_version,
+ record.source,
+ record.created_at,
+ int(resolved_has_error),
+ sqlite3.Binary(record.raw_json),
+ record.raw_sha256,
+ record.update_kind,
+ ),
+ )
+ return True
+
+ @staticmethod
+ def _migrate_final_current(connection: sqlite3.Connection) -> int:
+ rows = connection.execute(
+ """
+ SELECT records.*
+ FROM otlp_span_records AS records
+ LEFT JOIN trajectory_current_records AS current
+ ON current.trace_id = records.trace_id AND current.span_id = records.span_id
+ WHERE current.trace_id IS NULL
+ ORDER BY records.ingest_seq ASC
+ """
+ ).fetchall()
+ for row in rows:
+ record = TraceRecordData(
+ raw_json=bytes(row["raw_json"]),
+ raw_sha256=str(row["raw_sha256"]),
+ trace_id=str(row["trace_id"]),
+ span_id=str(row["span_id"]),
+ parent_span_id=row["parent_span_id"],
+ start_time_unix_nano=int(row["start_time_unix_nano"]),
+ end_time_unix_nano=int(row["end_time_unix_nano"]),
+ session_id=row["session_id"],
+ request_id=row["request_id"],
+ run_id=row["run_id"],
+ agent_mode=row["agent_mode"],
+ schema_version=str(row["schema_version"]),
+ source=str(row["source"]),
+ created_at=int(row["created_at"]),
+ lifecycle="final",
+ record_revision=1,
+ observed_time_unix_nano=int(row["end_time_unix_nano"]),
+ update_kind="completed",
+ )
+ TrajectoryStore._upsert_current_record(
+ connection,
+ record,
+ has_error=bool(row["has_error"]),
+ )
+ return len(rows)
+
+ @staticmethod
+ def _remove_missing_final_current(connection: sqlite3.Connection) -> int:
+ rows = connection.execute(
+ """
+ SELECT current.trace_id, current.span_id
+ FROM trajectory_current_records AS current
+ LEFT JOIN otlp_span_records AS records
+ ON records.trace_id = current.trace_id AND records.span_id = current.span_id
+ WHERE current.lifecycle = 'final' AND records.trace_id IS NULL
+ """
+ ).fetchall()
+ for row in rows:
+ identity = (str(row["trace_id"]), str(row["span_id"]))
+ connection.execute(
+ "DELETE FROM trajectory_current_records WHERE trace_id = ? AND span_id = ?",
+ identity,
+ )
+ connection.execute(
+ "DELETE FROM trajectory_changes WHERE trace_id = ? AND span_id = ?",
+ identity,
+ )
+ return len(rows)
+
+ @staticmethod
+ def _abandon_running_current(connection: sqlite3.Connection) -> int:
+ rows = connection.execute(
+ """
+ SELECT *
+ FROM trajectory_current_records
+ WHERE lifecycle = 'running'
+ ORDER BY change_seq ASC
+ """
+ ).fetchall()
+ observed_time = time.time_ns()
+ created_at = int(time.time())
+ for row in rows:
+ cursor = connection.execute(
+ """
+ INSERT INTO trajectory_changes (
+ trace_id, span_id, parent_span_id, session_id, request_id,
+ run_id, agent_mode, lifecycle, record_revision, operation,
+ start_time_unix_nano, observed_time_unix_nano,
+ end_time_unix_nano, schema_version, source, created_at,
+ has_error, raw_json, raw_sha256, update_kind
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, 'abandoned', ?, 'upsert', ?, ?, 0, ?, ?, ?, ?, ?, ?, 'recovered')
+ """,
+ (
+ row["trace_id"],
+ row["span_id"],
+ row["parent_span_id"],
+ row["session_id"],
+ row["request_id"],
+ row["run_id"],
+ row["agent_mode"],
+ row["record_revision"],
+ row["start_time_unix_nano"],
+ observed_time,
+ row["schema_version"],
+ row["source"],
+ created_at,
+ row["has_error"],
+ row["raw_json"],
+ row["raw_sha256"],
+ ),
+ )
+ connection.execute(
+ """
+ UPDATE trajectory_current_records
+ SET lifecycle = 'abandoned',
+ change_seq = ?,
+ observed_time_unix_nano = ?,
+ created_at = ?,
+ update_kind = 'recovered'
+ WHERE trace_id = ? AND span_id = ?
+ """,
+ (
+ int(cursor.lastrowid),
+ observed_time,
+ created_at,
+ row["trace_id"],
+ row["span_id"],
+ ),
+ )
+ return len(rows)
+
+ def delete_expired(self, *, now: int | None = None) -> int:
+ """Delete records older than the configured retention window."""
+ connection = self._require_connection()
+ cutoff = int(now if now is not None else time.time()) - self.retention_days * 86400
+ try:
+ connection.execute("BEGIN IMMEDIATE")
+ cursor = connection.execute(
+ "DELETE FROM otlp_span_records WHERE created_at < ?",
+ (cutoff,),
+ )
+ current_cursor = connection.execute(
+ "DELETE FROM trajectory_current_records WHERE created_at < ?",
+ (cutoff,),
+ )
+ connection.execute(
+ "DELETE FROM trajectory_changes WHERE created_at < ?",
+ (cutoff,),
+ )
+ connection.execute(
+ "DELETE FROM otlp_record_conflicts WHERE created_at < ?",
+ (cutoff,),
+ )
+ if cursor.rowcount > 0 or current_cursor.rowcount > 0:
+ self._rotate_store_epoch(connection)
+ connection.commit()
+ except Exception:
+ connection.rollback()
+ raise
+ return max(0, int(cursor.rowcount))
+
+ def fetch_raw(self, trace_id: str, span_id: str) -> bytes | None:
+ """Return exact stored bytes for writer-side diagnostics and tests."""
+ connection = self._require_connection()
+ row = connection.execute(
+ """
+ SELECT raw_json
+ FROM trajectory_current_records
+ WHERE trace_id = ? AND span_id = ?
+ """,
+ (trace_id, span_id),
+ ).fetchone()
+ return bytes(row["raw_json"]) if row is not None else None
+
+ def fetch_raw_sha256(self, trace_id: str, span_id: str) -> str | None:
+ """Return the hash persisted beside one raw record."""
+ connection = self._require_connection()
+ row = connection.execute(
+ """
+ SELECT raw_sha256
+ FROM trajectory_current_records
+ WHERE trace_id = ? AND span_id = ?
+ """,
+ (trace_id, span_id),
+ ).fetchone()
+ return str(row["raw_sha256"]) if row is not None else None
+
+ def count_conflicts(self) -> int:
+ """Return the persisted conflict diagnostic count."""
+ connection = self._require_connection()
+ row = connection.execute("SELECT COUNT(*) AS count FROM otlp_record_conflicts").fetchone()
+ return int(row["count"]) if row is not None else 0
+
+ def fetch_store_epoch(self) -> str:
+ """Return the current persistent epoch for diagnostics and tests."""
+ connection = self._require_connection()
+ row = connection.execute(
+ "SELECT store_epoch FROM trajectory_store_state WHERE singleton = 1"
+ ).fetchone()
+ if row is None:
+ raise RuntimeError("Trajectory store state is missing")
+ return str(row["store_epoch"])
+
+ def _require_connection(self) -> sqlite3.Connection:
+ connection = self._connection
+ if connection is None:
+ raise RuntimeError("TrajectoryStore is not initialized")
+ return connection
+
+ @staticmethod
+ def _initialize_store_state(connection: sqlite3.Connection) -> None:
+ current_max = _current_max_ingest_seq(connection)
+ current_change_max = _current_max_change_seq(connection)
+ row = connection.execute(
+ """
+ SELECT store_epoch, max_ingest_seq, max_change_seq
+ FROM trajectory_store_state
+ WHERE singleton = 1
+ """
+ ).fetchone()
+ if row is None:
+ connection.execute(
+ """
+ INSERT INTO trajectory_store_state (
+ singleton,
+ store_epoch,
+ max_ingest_seq,
+ max_change_seq
+ ) VALUES (1, ?, ?, ?)
+ """,
+ (_new_store_epoch(), current_max, current_change_max),
+ )
+ return
+ try:
+ stored_epoch = str(row["store_epoch"])
+ stored_max = int(row["max_ingest_seq"])
+ stored_change_max = int(row["max_change_seq"])
+ except (TypeError, ValueError, OverflowError):
+ stored_epoch = ""
+ stored_max = -1
+ stored_change_max = -1
+ if (
+ not stored_epoch
+ or stored_max < 0
+ or stored_change_max < 0
+ or current_max < stored_max
+ or current_change_max < stored_change_max
+ ):
+ TrajectoryStore._rotate_store_epoch(connection)
+ return
+ if current_max > stored_max or current_change_max > stored_change_max:
+ connection.execute(
+ """
+ UPDATE trajectory_store_state
+ SET max_ingest_seq = ?, max_change_seq = ?
+ WHERE singleton = 1
+ """,
+ (current_max, current_change_max),
+ )
+
+ @staticmethod
+ def _ensure_store_state_columns(connection: sqlite3.Connection) -> None:
+ columns = {
+ str(row["name"])
+ for row in connection.execute("PRAGMA table_info(trajectory_store_state)").fetchall()
+ }
+ if "max_change_seq" not in columns:
+ connection.execute(
+ "ALTER TABLE trajectory_store_state ADD COLUMN max_change_seq INTEGER NOT NULL DEFAULT 0"
+ )
+
+ @staticmethod
+ def _sync_max_ingest_seq(connection: sqlite3.Connection) -> None:
+ connection.execute(
+ """
+ UPDATE trajectory_store_state
+ SET max_ingest_seq = ?, max_change_seq = ?
+ WHERE singleton = 1
+ """,
+ (_current_max_ingest_seq(connection), _current_max_change_seq(connection)),
+ )
+
+ @staticmethod
+ def _rotate_store_epoch(connection: sqlite3.Connection) -> None:
+ connection.execute(
+ """
+ UPDATE trajectory_store_state
+ SET store_epoch = ?, max_ingest_seq = ?, max_change_seq = ?
+ WHERE singleton = 1
+ """,
+ (
+ _new_store_epoch(),
+ _current_max_ingest_seq(connection),
+ _current_max_change_seq(connection),
+ ),
+ )
+
+ @staticmethod
+ def _trace_eligibility(
+ connection: sqlite3.Connection,
+ trace_ids: Sequence[str],
+ ) -> dict[str, tuple[bool, bool]]:
+ states = {trace_id: (False, False) for trace_id in trace_ids}
+ if not trace_ids:
+ return states
+ placeholders = ",".join("?" for _ in trace_ids)
+ rows = connection.execute(
+ f"""
+ SELECT trace_id,
+ COUNT(*) AS record_count,
+ SUM(
+ CASE
+ WHEN agent_mode IS NOT NULL
+ AND TRIM(agent_mode) <> ''
+ AND LOWER(TRIM(agent_mode)) IN (
+ {_SINGLE_AGENT_MODE_PLACEHOLDERS}
+ )
+ THEN 1 ELSE 0
+ END
+ ) AS known_count,
+ SUM(
+ CASE
+ WHEN agent_mode IS NOT NULL
+ AND TRIM(agent_mode) <> ''
+ AND LOWER(TRIM(agent_mode)) NOT IN (
+ {_SINGLE_AGENT_MODE_PLACEHOLDERS}
+ )
+ THEN 1 ELSE 0
+ END
+ ) AS rejected_count
+ FROM otlp_span_records
+ WHERE trace_id IN ({placeholders})
+ GROUP BY trace_id
+ """,
+ (
+ *_SINGLE_AGENT_MODE_VALUES,
+ *_SINGLE_AGENT_MODE_VALUES,
+ *trace_ids,
+ ),
+ ).fetchall()
+ for row in rows:
+ trace_id = str(row["trace_id"])
+ record_count = int(row["record_count"])
+ known_count = int(row["known_count"] or 0)
+ rejected_count = int(row["rejected_count"] or 0)
+ states[trace_id] = (
+ record_count > 0,
+ known_count > 0 and rejected_count == 0,
+ )
+ return states
+
+ @staticmethod
+ def _reconcile_orphans(
+ connection: sqlite3.Connection,
+ records: Sequence[TraceRecordData],
+ ) -> set[str]:
+ changed_trace_ids: set[str] = set()
+ for trace_id in sorted({record.trace_id for record in records}):
+ rows = connection.execute(
+ """
+ SELECT session_id, request_id, run_id, agent_mode
+ FROM otlp_span_records
+ WHERE trace_id = ? AND session_id IS NOT NULL
+ ORDER BY ingest_seq ASC
+ """,
+ (trace_id,),
+ ).fetchall()
+ session_ids = {str(row["session_id"]) for row in rows}
+ if not session_ids:
+ continue
+ if len(session_ids) != 1:
+ logger.warning(
+ "Trajectory orphan reconciliation skipped ambiguous session hints: trace_id=%s",
+ trace_id,
+ )
+ continue
+ session_id = next(iter(session_ids))
+ request_id = _unique_text_hint(rows, "request_id")
+ run_id = _unique_text_hint(rows, "run_id")
+ agent_mode = _unique_text_hint(rows, "agent_mode")
+ cursor = connection.execute(
+ """
+ UPDATE otlp_span_records
+ SET session_id = COALESCE(session_id, ?),
+ request_id = COALESCE(request_id, ?),
+ run_id = COALESCE(run_id, ?),
+ agent_mode = COALESCE(agent_mode, ?)
+ WHERE trace_id = ?
+ AND (session_id IS NULL OR session_id = ?)
+ AND (
+ session_id IS NULL
+ OR (request_id IS NULL AND ? IS NOT NULL)
+ OR (run_id IS NULL AND ? IS NOT NULL)
+ OR (agent_mode IS NULL AND ? IS NOT NULL)
+ )
+ """,
+ (
+ session_id,
+ request_id,
+ run_id,
+ agent_mode,
+ trace_id,
+ session_id,
+ request_id,
+ run_id,
+ agent_mode,
+ ),
+ )
+ if cursor.rowcount > 0:
+ connection.execute(
+ """
+ UPDATE trajectory_current_records
+ SET session_id = COALESCE(session_id, ?),
+ request_id = COALESCE(request_id, ?),
+ run_id = COALESCE(run_id, ?),
+ agent_mode = COALESCE(agent_mode, ?)
+ WHERE trace_id = ? AND (session_id IS NULL OR session_id = ?)
+ """,
+ (session_id, request_id, run_id, agent_mode, trace_id, session_id),
+ )
+ connection.execute(
+ """
+ UPDATE trajectory_changes
+ SET session_id = COALESCE(session_id, ?),
+ request_id = COALESCE(request_id, ?),
+ run_id = COALESCE(run_id, ?),
+ agent_mode = COALESCE(agent_mode, ?)
+ WHERE trace_id = ? AND (session_id IS NULL OR session_id = ?)
+ """,
+ (session_id, request_id, run_id, agent_mode, trace_id, session_id),
+ )
+ changed_trace_ids.add(trace_id)
+ return changed_trace_ids
+
+ @staticmethod
+ def _committed_updates(
+ connection: sqlite3.Connection,
+ changed_trace_ids: set[str],
+ ) -> tuple[CommittedTraceUpdate, ...]:
+ updates: list[CommittedTraceUpdate] = []
+ epoch_row = connection.execute(
+ "SELECT store_epoch FROM trajectory_store_state WHERE singleton = 1"
+ ).fetchone()
+ store_epoch = str(epoch_row["store_epoch"]) if epoch_row is not None else None
+ for trace_id in sorted(changed_trace_ids):
+ rows = connection.execute(
+ """
+ SELECT session_id, MAX(ingest_seq) AS revision
+ FROM (
+ SELECT trace_id, session_id, change_seq AS ingest_seq
+ FROM trajectory_current_records
+ )
+ WHERE trace_id = ? AND session_id IS NOT NULL
+ GROUP BY session_id
+ """,
+ (trace_id,),
+ ).fetchall()
+ for row in rows:
+ lifecycle_row = connection.execute(
+ """
+ SELECT lifecycle
+ FROM trajectory_current_records
+ WHERE trace_id = ? AND session_id = ?
+ ORDER BY change_seq DESC
+ LIMIT 1
+ """,
+ (trace_id, str(row["session_id"])),
+ ).fetchone()
+ updates.append(
+ CommittedTraceUpdate(
+ session_id=str(row["session_id"]),
+ trace_id=trace_id,
+ revision=int(row["revision"]),
+ store_epoch=store_epoch,
+ lifecycle=(
+ str(lifecycle_row["lifecycle"])
+ if lifecycle_row is not None
+ else "final"
+ ),
+ )
+ )
+ return tuple(updates)
+
+
+class AsyncTrajectoryReader:
+ """Gateway-side read-only view over the shared trajectory database."""
+
+ def __init__(self, database_path: Path) -> None:
+ self.database_path = Path(database_path)
+
+ async def list_traces(
+ self,
+ session_id: str,
+ *,
+ limit: int,
+ cursor: str | None,
+ ) -> tuple[list[dict[str, Any]], str | None]:
+ """List trace summaries in stable newest-first order."""
+ items, next_cursor, _revision_cursor, _store_epoch = (
+ await self.list_traces_with_revision_cursor(
+ session_id,
+ limit=limit,
+ cursor=cursor,
+ )
+ )
+ return items, next_cursor
+
+ async def get_session_archive_records(
+ self,
+ session_id: str,
+ ) -> tuple[list[dict[str, Any]], str, int]:
+ """Read every current record for one session from one SQLite snapshot."""
+ connection = await self._connect()
+ if connection is None:
+ return [], _ABSENT_STORE_EPOCH, 0
+ try:
+ await connection.execute("BEGIN")
+ store_epoch = await _read_store_epoch(connection)
+ revision = await _session_revision_watermark(connection, session_id)
+ query = f"""
+ WITH {_ELIGIBLE_TRACES_CTE}
+ SELECT records.trace_id,
+ records.span_id,
+ records.parent_span_id,
+ records.session_id,
+ records.request_id,
+ records.run_id,
+ records.agent_mode,
+ records.lifecycle,
+ records.record_revision,
+ records.change_seq,
+ records.start_time_unix_nano,
+ records.observed_time_unix_nano,
+ records.end_time_unix_nano,
+ records.schema_version,
+ records.source,
+ records.created_at,
+ records.raw_json,
+ records.raw_sha256,
+ records.update_kind
+ FROM trajectory_current_records AS records
+ INNER JOIN eligible_traces
+ ON eligible_traces.trace_id = records.trace_id
+ WHERE records.session_id = ?
+ ORDER BY records.start_time_unix_nano ASC,
+ records.trace_id ASC,
+ records.span_id ASC
+ """
+ params: tuple[Any, ...] = (
+ *_single_agent_scope_params(),
+ session_id,
+ )
+ async with connection.execute(query, params) as statement:
+ rows = await statement.fetchall()
+ finally:
+ await connection.rollback()
+ await connection.close()
+ return [_archive_record_from_row(row) for row in rows], store_epoch, revision
+
+ async def list_traces_with_revision_cursor(
+ self,
+ session_id: str,
+ *,
+ limit: int,
+ cursor: str | None,
+ ) -> tuple[list[dict[str, Any]], str | None, str, str]:
+ """List summaries and a polling baseline from one SQLite snapshot."""
+ cursor_value = decode_trace_cursor(cursor) if cursor else None
+ connection = await self._connect()
+ if connection is None:
+ store_epoch = _ABSENT_STORE_EPOCH
+ if cursor_value is not None:
+ cursor_session_id, cursor_epoch, cursor_ingest_seq, _trace_id = cursor_value
+ if (
+ cursor_session_id != session_id
+ or cursor_epoch != store_epoch
+ or cursor_ingest_seq > 0
+ ):
+ raise TrajectoryCursorError("trajectory list cursor is out of scope")
+ return (
+ [],
+ None,
+ encode_revision_cursor(session_id, store_epoch, 0),
+ store_epoch,
+ )
+ try:
+ await connection.execute("BEGIN")
+ store_epoch = await _read_store_epoch(connection)
+ revision_ingest_seq = await _session_revision_watermark(connection, session_id)
+ if cursor_value is None:
+ query = f"""
+ WITH {_ELIGIBLE_TRACES_CTE}
+ SELECT records.trace_id,
+ MIN(records.change_seq) AS list_ingest_seq,
+ MAX(records.change_seq) AS revision,
+ MIN(records.start_time_unix_nano) AS start_time_unix_nano,
+ MAX(records.end_time_unix_nano) AS end_time_unix_nano,
+ COUNT(*) AS span_count,
+ MAX(records.request_id) AS request_id,
+ MAX(records.run_id) AS run_id,
+ MAX(records.agent_mode) AS agent_mode,
+ MAX(records.has_error) AS has_error
+ FROM trajectory_current_records AS records
+ INNER JOIN eligible_traces
+ ON eligible_traces.trace_id = records.trace_id
+ WHERE records.session_id = ?
+ GROUP BY records.trace_id
+ ORDER BY MIN(records.change_seq) DESC, records.trace_id DESC
+ LIMIT ?
+ """
+ params: tuple[Any, ...] = (
+ *_single_agent_scope_params(),
+ session_id,
+ limit + 1,
+ )
+ else:
+ (
+ cursor_session_id,
+ cursor_epoch,
+ cursor_ingest_seq,
+ cursor_trace_id,
+ ) = cursor_value
+ if (
+ cursor_session_id != session_id
+ or cursor_epoch != store_epoch
+ or cursor_ingest_seq > revision_ingest_seq
+ ):
+ raise TrajectoryCursorError("trajectory list cursor is out of scope")
+ query = f"""
+ WITH {_ELIGIBLE_TRACES_CTE}
+ SELECT records.trace_id,
+ MIN(records.change_seq) AS list_ingest_seq,
+ MAX(records.change_seq) AS revision,
+ MIN(records.start_time_unix_nano) AS start_time_unix_nano,
+ MAX(records.end_time_unix_nano) AS end_time_unix_nano,
+ COUNT(*) AS span_count,
+ MAX(records.request_id) AS request_id,
+ MAX(records.run_id) AS run_id,
+ MAX(records.agent_mode) AS agent_mode,
+ MAX(records.has_error) AS has_error
+ FROM trajectory_current_records AS records
+ INNER JOIN eligible_traces
+ ON eligible_traces.trace_id = records.trace_id
+ WHERE records.session_id = ?
+ GROUP BY records.trace_id
+ HAVING MIN(records.change_seq) < ?
+ OR (MIN(records.change_seq) = ? AND records.trace_id < ?)
+ ORDER BY MIN(records.change_seq) DESC, records.trace_id DESC
+ LIMIT ?
+ """
+ params = (
+ *_single_agent_scope_params(),
+ session_id,
+ cursor_ingest_seq,
+ cursor_ingest_seq,
+ cursor_trace_id,
+ limit + 1,
+ )
+ async with connection.execute(query, params) as statement:
+ rows = await statement.fetchall()
+ finally:
+ await connection.rollback()
+ await connection.close()
+ has_more = len(rows) > limit
+ visible_rows = rows[:limit]
+ items = [_trace_summary_from_row(row) for row in visible_rows]
+ next_cursor = None
+ if has_more and visible_rows:
+ last = visible_rows[-1]
+ next_cursor = encode_trace_cursor(
+ session_id,
+ store_epoch,
+ int(last["list_ingest_seq"]),
+ str(last["trace_id"]),
+ )
+ return (
+ items,
+ next_cursor,
+ encode_revision_cursor(session_id, store_epoch, revision_ingest_seq),
+ store_epoch,
+ )
+
+ async def list_trace_revisions(
+ self,
+ session_id: str,
+ *,
+ after_revision: str,
+ limit: int,
+ ) -> tuple[list[dict[str, Any]], str, str, bool, bool, str]:
+ """List trace summaries changed after an opaque revision cursor.
+
+ One polling pass is bounded by the watermark captured on its first page.
+ A continuation cursor carries that bound so concurrent commits are left
+ for the next pass instead of extending the current pagination window.
+ """
+ (
+ cursor_session_id,
+ cursor_epoch,
+ after_ingest_seq,
+ through_ingest_seq,
+ ) = decode_revision_cursor(after_revision)
+ connection = await self._connect()
+ if connection is None:
+ store_epoch = _ABSENT_STORE_EPOCH
+ stable_cursor = encode_revision_cursor(session_id, store_epoch, 0)
+ reset = (
+ cursor_session_id != session_id
+ or cursor_epoch != store_epoch
+ or after_ingest_seq > 0
+ or (through_ingest_seq is not None and through_ingest_seq > 0)
+ )
+ return [], stable_cursor, stable_cursor, False, reset, store_epoch
+ try:
+ await connection.execute("BEGIN")
+ store_epoch = await _read_store_epoch(connection)
+ current_watermark = await _session_revision_watermark(connection, session_id)
+ reset = (
+ cursor_session_id != session_id
+ or cursor_epoch != store_epoch
+ or after_ingest_seq > current_watermark
+ or (
+ through_ingest_seq is not None
+ and through_ingest_seq > current_watermark
+ )
+ )
+ if reset:
+ stable_cursor = encode_revision_cursor(
+ session_id,
+ store_epoch,
+ current_watermark,
+ )
+ return (
+ [],
+ stable_cursor,
+ stable_cursor,
+ False,
+ True,
+ store_epoch,
+ )
+ if through_ingest_seq is None:
+ through_ingest_seq = current_watermark
+ query = f"""
+ WITH {_ELIGIBLE_TRACES_CTE}
+ SELECT records.change_seq AS ingest_seq,
+ records.trace_id
+ FROM trajectory_changes AS records
+ INNER JOIN eligible_traces
+ ON eligible_traces.trace_id = records.trace_id
+ WHERE records.session_id = ?
+ AND records.change_seq > ?
+ AND records.change_seq <= ?
+ ORDER BY records.change_seq ASC
+ LIMIT ?
+ """
+ params: tuple[Any, ...] = (
+ *_single_agent_scope_params(),
+ session_id,
+ after_ingest_seq,
+ through_ingest_seq,
+ limit + 1,
+ )
+ async with connection.execute(query, params) as statement:
+ change_rows = await statement.fetchall()
+ has_more = len(change_rows) > limit
+ visible_change_rows = change_rows[:limit]
+ changed_trace_ids = list(
+ dict.fromkeys(str(row["trace_id"]) for row in visible_change_rows)
+ )
+ summaries = await _trace_summaries_by_id(
+ connection,
+ session_id,
+ changed_trace_ids,
+ through_ingest_seq,
+ )
+ finally:
+ await connection.rollback()
+ await connection.close()
+
+ summary_by_trace_id = {str(item["trace_id"]): item for item in summaries}
+ items = [
+ summary_by_trace_id[trace_id]
+ for trace_id in changed_trace_ids
+ if trace_id in summary_by_trace_id
+ ]
+ next_ingest_seq = through_ingest_seq
+ if has_more and visible_change_rows:
+ next_ingest_seq = int(visible_change_rows[-1]["ingest_seq"])
+ watermark = encode_revision_cursor(
+ session_id,
+ store_epoch,
+ through_ingest_seq,
+ )
+ next_cursor = encode_revision_cursor(
+ session_id,
+ store_epoch,
+ next_ingest_seq,
+ through_ingest_seq=through_ingest_seq if has_more else None,
+ )
+ return items, next_cursor, watermark, has_more, False, store_epoch
+
+ async def get_trace_records(
+ self,
+ session_id: str,
+ trace_id: str,
+ *,
+ since_revision: int,
+ limit: int,
+ max_bytes: int = DEFAULT_DETAIL_MAX_BYTES,
+ ) -> dict[str, Any] | None:
+ """Read a complete or incremental page for one trace."""
+ connection = await self._connect()
+ if connection is None:
+ return None
+ try:
+ await connection.execute("BEGIN")
+ aggregate = await _fetch_one(
+ connection,
+ f"""
+ WITH {_ELIGIBLE_TRACES_CTE}
+ SELECT MIN(records.change_seq) AS first_revision,
+ MAX(records.change_seq) AS current_revision
+ FROM trajectory_changes AS records
+ INNER JOIN eligible_traces
+ ON eligible_traces.trace_id = records.trace_id
+ WHERE records.session_id = ? AND records.trace_id = ?
+ """,
+ (
+ *_single_agent_scope_params(),
+ session_id,
+ trace_id,
+ ),
+ )
+ if aggregate is None or aggregate["current_revision"] is None:
+ return None
+ first_revision = int(aggregate["first_revision"])
+ current_revision = int(aggregate["current_revision"])
+ reset = since_revision > current_revision or (
+ since_revision > 0 and since_revision < first_revision
+ )
+ effective_since = 0 if reset else since_revision
+ async with connection.execute(
+ """
+ SELECT change_seq AS ingest_seq,
+ trace_id,
+ span_id,
+ record_revision,
+ lifecycle,
+ operation,
+ observed_time_unix_nano,
+ LENGTH(raw_json) AS raw_size_bytes
+ FROM trajectory_changes
+ WHERE session_id = ?
+ AND trace_id = ?
+ AND change_seq > ?
+ ORDER BY change_seq ASC
+ LIMIT ?
+ """,
+ (session_id, trace_id, effective_since, limit + 1),
+ ) as statement:
+ metadata_rows = await statement.fetchall()
+
+ selected_metadata: list[tuple[aiosqlite.Row, bool]] = []
+ projected_raw_bytes = 0
+ byte_budget = max(1, int(max_bytes))
+ for row in metadata_rows:
+ if len(selected_metadata) >= limit:
+ break
+ raw_size = max(0, int(row["raw_size_bytes"] or 0))
+ if not selected_metadata and raw_size > byte_budget:
+ selected_metadata.append((row, True))
+ break
+ if projected_raw_bytes + raw_size > byte_budget:
+ break
+ selected_metadata.append((row, False))
+ projected_raw_bytes += raw_size
+
+ raw_rows: list[aiosqlite.Row] = []
+ fetchable_metadata = [
+ row for row, projection_omitted in selected_metadata if not projection_omitted
+ ]
+ if fetchable_metadata:
+ last_fetch_revision = int(fetchable_metadata[-1]["ingest_seq"])
+ async with connection.execute(
+ """
+ SELECT change_seq AS ingest_seq,
+ trace_id,
+ span_id,
+ record_revision,
+ lifecycle,
+ operation,
+ observed_time_unix_nano,
+ LENGTH(raw_json) AS raw_size_bytes,
+ raw_json
+ FROM trajectory_changes
+ WHERE session_id = ?
+ AND trace_id = ?
+ AND change_seq > ?
+ AND change_seq <= ?
+ ORDER BY change_seq ASC
+ """,
+ (
+ session_id,
+ trace_id,
+ effective_since,
+ last_fetch_revision,
+ ),
+ ) as statement:
+ raw_rows = await statement.fetchall()
+ finally:
+ await connection.rollback()
+ await connection.close()
+ raw_by_revision = {int(row["ingest_seq"]): row for row in raw_rows}
+ records: list[dict[str, Any]] = []
+ for row, projection_omitted in selected_metadata:
+ ingest_seq = int(row["ingest_seq"])
+ if projection_omitted:
+ records.append(_omitted_detail_record_from_row(row))
+ else:
+ records.append(_detail_record_from_row(raw_by_revision[ingest_seq]))
+ has_more = len(metadata_rows) > len(selected_metadata)
+ next_since_revision = effective_since
+ if selected_metadata:
+ next_since_revision = int(selected_metadata[-1][0]["ingest_seq"])
+ return {
+ "revision": current_revision,
+ "reset": reset,
+ "records": records,
+ "has_more": has_more,
+ "next_since_revision": next_since_revision,
+ "projected_raw_bytes": projected_raw_bytes,
+ "max_projected_raw_bytes": byte_budget,
+ }
+
+ async def get_raw_record(
+ self,
+ session_id: str,
+ trace_id: str,
+ span_id: str,
+ ) -> bytes | None:
+ """Return exact raw bytes when the identity belongs to the session."""
+ connection = await self._connect()
+ if connection is None:
+ return None
+ try:
+ row = await _fetch_one(
+ connection,
+ f"""
+ WITH {_ELIGIBLE_TRACES_CTE}
+ SELECT records.raw_json
+ FROM otlp_span_records AS records
+ INNER JOIN eligible_traces
+ ON eligible_traces.trace_id = records.trace_id
+ WHERE records.session_id = ?
+ AND records.trace_id = ?
+ AND records.span_id = ?
+ """,
+ (
+ *_single_agent_scope_params(),
+ session_id,
+ trace_id,
+ span_id,
+ ),
+ )
+ finally:
+ await connection.close()
+ return bytes(row["raw_json"]) if row is not None else None
+
+ async def _connect(self) -> aiosqlite.Connection | None:
+ if not self.database_path.is_file():
+ return None
+ connection = await aiosqlite.connect(
+ f"{self.database_path.resolve().as_uri()}?mode=ro",
+ timeout=_BUSY_TIMEOUT_MS / 1000,
+ uri=True,
+ )
+ connection.row_factory = aiosqlite.Row
+ await connection.execute(f"PRAGMA busy_timeout={_BUSY_TIMEOUT_MS}")
+ await connection.execute("PRAGMA query_only=ON")
+ return connection
+
+
+async def _fetch_one(
+ connection: aiosqlite.Connection,
+ query: str,
+ params: tuple[Any, ...],
+) -> aiosqlite.Row | None:
+ async with connection.execute(query, params) as statement:
+ return await statement.fetchone()
+
+
+async def _read_store_epoch(connection: aiosqlite.Connection) -> str:
+ table = await _fetch_one(
+ connection,
+ """
+ SELECT name
+ FROM sqlite_master
+ WHERE type = 'table' AND name = 'trajectory_store_state'
+ """,
+ (),
+ )
+ if table is None:
+ return _ABSENT_STORE_EPOCH
+ row = await _fetch_one(
+ connection,
+ """
+ SELECT store_epoch
+ FROM trajectory_store_state
+ WHERE singleton = 1
+ """,
+ (),
+ )
+ if row is None:
+ return _ABSENT_STORE_EPOCH
+ store_epoch = str(row["store_epoch"] or "")
+ return store_epoch if store_epoch else _ABSENT_STORE_EPOCH
+
+
+def _current_max_ingest_seq(connection: sqlite3.Connection) -> int:
+ row = connection.execute(
+ "SELECT COALESCE(MAX(ingest_seq), 0) AS max_ingest_seq FROM otlp_span_records"
+ ).fetchone()
+ return int(row["max_ingest_seq"]) if row is not None else 0
+
+
+def _current_max_change_seq(connection: sqlite3.Connection) -> int:
+ row = connection.execute(
+ "SELECT COALESCE(MAX(change_seq), 0) AS max_change_seq FROM trajectory_changes"
+ ).fetchone()
+ return int(row["max_change_seq"]) if row is not None else 0
+
+
+def _new_store_epoch() -> str:
+ return uuid.uuid4().hex
+
+
+def _unique_text_hint(rows: Sequence[sqlite3.Row], column: str) -> str | None:
+ values = {
+ str(row[column])
+ for row in rows
+ if row[column] is not None and str(row[column]).strip()
+ }
+ if len(values) != 1:
+ return None
+ return next(iter(values))
+
+
+def _single_agent_scope_params() -> tuple[Any, ...]:
+ """Return parameters for the trace-level single-Agent eligibility CTE."""
+ return (
+ *_SINGLE_AGENT_MODE_VALUES,
+ *_SINGLE_AGENT_MODE_VALUES,
+ )
+
+
+async def _session_revision_watermark(
+ connection: aiosqlite.Connection,
+ session_id: str,
+) -> int:
+ row = await _fetch_one(
+ connection,
+ f"""
+ WITH {_ELIGIBLE_TRACES_CTE}
+ SELECT COALESCE(MAX(records.change_seq), 0) AS revision_ingest_seq
+ FROM trajectory_current_records AS records
+ INNER JOIN eligible_traces
+ ON eligible_traces.trace_id = records.trace_id
+ WHERE records.session_id = ?
+ """,
+ (
+ *_single_agent_scope_params(),
+ session_id,
+ ),
+ )
+ return int(row["revision_ingest_seq"]) if row is not None else 0
+
+
+async def _trace_summaries_by_id(
+ connection: aiosqlite.Connection,
+ session_id: str,
+ trace_ids: list[str],
+ through_ingest_seq: int,
+) -> list[dict[str, Any]]:
+ if not trace_ids:
+ return []
+ trace_placeholders = ",".join("?" for _ in trace_ids)
+ query = f"""
+ WITH {_ELIGIBLE_TRACES_CTE},
+ latest_records AS (
+ SELECT records.*
+ FROM trajectory_changes AS records
+ WHERE records.change_seq <= ?
+ AND NOT EXISTS (
+ SELECT 1
+ FROM trajectory_changes AS newer
+ WHERE newer.trace_id = records.trace_id
+ AND newer.span_id = records.span_id
+ AND newer.change_seq <= ?
+ AND newer.change_seq > records.change_seq
+ )
+ )
+ SELECT records.trace_id,
+ MIN(records.change_seq) AS list_ingest_seq,
+ MAX(records.change_seq) AS revision,
+ MIN(records.start_time_unix_nano) AS start_time_unix_nano,
+ MAX(records.end_time_unix_nano) AS end_time_unix_nano,
+ COUNT(*) AS span_count,
+ MAX(records.request_id) AS request_id,
+ MAX(records.run_id) AS run_id,
+ MAX(records.agent_mode) AS agent_mode,
+ MAX(records.has_error) AS has_error
+ FROM latest_records AS records
+ INNER JOIN eligible_traces
+ ON eligible_traces.trace_id = records.trace_id
+ WHERE records.session_id = ?
+ AND records.trace_id IN ({trace_placeholders})
+ GROUP BY records.trace_id
+ """
+ params: tuple[Any, ...] = (
+ *_single_agent_scope_params(),
+ through_ingest_seq,
+ through_ingest_seq,
+ session_id,
+ *trace_ids,
+ )
+ async with connection.execute(query, params) as statement:
+ rows = await statement.fetchall()
+ return [_trace_summary_from_row(row) for row in rows]
+
+
+def encode_revision_cursor(
+ session_id: str,
+ store_epoch: str,
+ after_ingest_seq: int,
+ *,
+ through_ingest_seq: int | None = None,
+) -> str:
+ """Encode a stable polling cursor without exposing the SQLite sequence."""
+ session_value = _cursor_text(session_id)
+ epoch_value = _cursor_text(store_epoch)
+ after_value = _cursor_sequence(after_ingest_seq)
+ payload = {
+ "v": 2,
+ "s": session_value,
+ "e": epoch_value,
+ "a": str(after_value),
+ }
+ if through_ingest_seq is not None:
+ through_value = _cursor_sequence(through_ingest_seq)
+ if through_value < after_value:
+ raise TrajectoryCursorError("invalid trajectory revision cursor")
+ payload["u"] = str(through_value)
+ return _encode_cursor_payload(payload)
+
+
+def decode_revision_cursor(cursor: str) -> tuple[str, str, int, int | None]:
+ """Decode and validate an opaque polling cursor."""
+ try:
+ payload = _decode_cursor_payload(cursor)
+ expected_fields = {"v", "s", "e", "a"}
+ if "u" in payload:
+ expected_fields.add("u")
+ if set(payload) != expected_fields or type(payload.get("v")) is not int:
+ raise TrajectoryCursorError("invalid trajectory revision cursor")
+ if payload["v"] != 2:
+ raise TrajectoryCursorError("invalid trajectory revision cursor")
+ session_id = _cursor_text(payload["s"])
+ store_epoch = _cursor_text(payload["e"])
+ raw_after = payload["a"]
+ raw_through = payload.get("u")
+ after_ingest_seq = _decode_cursor_sequence(raw_after)
+ through_ingest_seq = (
+ _decode_cursor_sequence(raw_through) if raw_through is not None else None
+ )
+ except TrajectoryCursorError:
+ raise
+ except (KeyError, TypeError, ValueError, UnicodeError, OverflowError) as exc:
+ raise TrajectoryCursorError("invalid trajectory revision cursor") from exc
+ if through_ingest_seq is not None and through_ingest_seq < after_ingest_seq:
+ raise TrajectoryCursorError("invalid trajectory revision cursor")
+ return session_id, store_epoch, after_ingest_seq, through_ingest_seq
+
+
+def encode_trace_cursor(
+ session_id: str,
+ store_epoch: str,
+ first_ingest_seq: int,
+ trace_id: str,
+) -> str:
+ """Encode a stable opaque list cursor."""
+ payload = {
+ "v": 3,
+ "s": _cursor_text(session_id),
+ "e": _cursor_text(store_epoch),
+ "i": str(_cursor_sequence(first_ingest_seq)),
+ "t": _cursor_text(trace_id),
+ }
+ return _encode_cursor_payload(payload)
+
+
+def decode_trace_cursor(cursor: str) -> tuple[str, str, int, str]:
+ """Decode and validate a list cursor without exposing SQL details."""
+ try:
+ payload = _decode_cursor_payload(cursor)
+ if set(payload) != {"v", "s", "e", "i", "t"}:
+ raise TrajectoryCursorError("invalid trajectory cursor")
+ if type(payload.get("v")) is not int or payload["v"] != 3:
+ raise TrajectoryCursorError("invalid trajectory cursor")
+ session_id = _cursor_text(payload["s"])
+ store_epoch = _cursor_text(payload["e"])
+ first_ingest_seq = _decode_cursor_sequence(payload["i"])
+ trace_id = _cursor_text(payload["t"])
+ except TrajectoryCursorError:
+ raise
+ except (KeyError, TypeError, ValueError, UnicodeError, OverflowError) as exc:
+ raise TrajectoryCursorError("invalid trajectory cursor") from exc
+ return session_id, store_epoch, first_ingest_seq, trace_id
+
+
+def _encode_cursor_payload(payload: dict[str, Any]) -> str:
+ raw_payload = json.dumps(payload, separators=(",", ":")).encode("utf-8")
+ cursor = base64.urlsafe_b64encode(raw_payload).decode("ascii").rstrip("=")
+ if len(cursor) > 512:
+ raise TrajectoryCursorError("trajectory cursor is too large")
+ return cursor
+
+
+def _decode_cursor_payload(cursor: str) -> dict[str, Any]:
+ if not isinstance(cursor, str) or not cursor or len(cursor) > 512:
+ raise TrajectoryCursorError("invalid trajectory cursor")
+ if cursor != cursor.strip() or len(cursor) % 4 == 1:
+ raise TrajectoryCursorError("invalid trajectory cursor")
+ if any(
+ character not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
+ for character in cursor
+ ):
+ raise TrajectoryCursorError("invalid trajectory cursor")
+ padding = "=" * (-len(cursor) % 4)
+ try:
+ encoded = cursor.encode("ascii")
+ decoded = base64.b64decode(
+ encoded + padding.encode("ascii"),
+ altchars=b"-_",
+ validate=True,
+ )
+ if base64.urlsafe_b64encode(decoded).rstrip(b"=") != encoded:
+ raise TrajectoryCursorError("invalid trajectory cursor")
+ payload = json.loads(decoded, object_pairs_hook=_unique_cursor_object)
+ except TrajectoryCursorError:
+ raise
+ except (
+ binascii.Error,
+ json.JSONDecodeError,
+ RecursionError,
+ TypeError,
+ UnicodeError,
+ ValueError,
+ ) as exc:
+ raise TrajectoryCursorError("invalid trajectory cursor") from exc
+ if not isinstance(payload, dict):
+ raise TrajectoryCursorError("invalid trajectory cursor")
+ return payload
+
+
+def _unique_cursor_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
+ payload: dict[str, Any] = {}
+ for key, value in pairs:
+ if key in payload:
+ raise TrajectoryCursorError("invalid trajectory cursor")
+ payload[key] = value
+ return payload
+
+
+def _cursor_text(value: object) -> str:
+ if not isinstance(value, str) or not value:
+ raise TrajectoryCursorError("invalid trajectory cursor")
+ return value
+
+
+def _cursor_sequence(value: object) -> int:
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise TrajectoryCursorError("invalid trajectory cursor sequence")
+ if value < 0 or value > _MAX_SQLITE_INTEGER:
+ raise TrajectoryCursorError("invalid trajectory cursor sequence")
+ return value
+
+
+def _decode_cursor_sequence(value: object) -> int:
+ if not isinstance(value, str) or not value:
+ raise TrajectoryCursorError("invalid trajectory cursor sequence")
+ try:
+ parsed = int(value)
+ except (TypeError, ValueError, OverflowError) as exc:
+ raise TrajectoryCursorError("invalid trajectory cursor sequence") from exc
+ if value != str(parsed):
+ raise TrajectoryCursorError("invalid trajectory cursor sequence")
+ return _cursor_sequence(parsed)
+
+
+def _record_has_error(raw_json: bytes) -> bool:
+ try:
+ payload = _strict_otlp_payload(raw_json)
+ except Exception:
+ return False
+ resource_spans = payload.get("resourceSpans")
+ for resource_span in resource_spans:
+ if not isinstance(resource_span, dict):
+ continue
+ scope_spans = resource_span.get("scopeSpans")
+ if not isinstance(scope_spans, list):
+ continue
+ for scope_span in scope_spans:
+ if not isinstance(scope_span, dict):
+ continue
+ spans = scope_span.get("spans")
+ if not isinstance(spans, list):
+ continue
+ for span in spans:
+ if not isinstance(span, dict):
+ continue
+ status = span.get("status")
+ if not isinstance(status, dict):
+ continue
+ code = status.get("code")
+ if code == 2 or str(code or "").strip().upper() in {
+ "2",
+ "ERROR",
+ "STATUS_CODE_ERROR",
+ }:
+ return True
+ return False
+
+
+def _trace_summary_from_row(row: aiosqlite.Row) -> dict[str, Any]:
+ return {
+ "trace_id": str(row["trace_id"]),
+ "revision": int(row["revision"]),
+ "start_time_unix_nano": int(row["start_time_unix_nano"]),
+ "end_time_unix_nano": int(row["end_time_unix_nano"]),
+ "span_count": int(row["span_count"]),
+ "request_id": row["request_id"],
+ "run_id": row["run_id"],
+ "agent_mode": row["agent_mode"],
+ "has_error": bool(row["has_error"]),
+ }
+
+
+def _detail_record_from_row(row: aiosqlite.Row) -> dict[str, Any]:
+ raw_json = bytes(row["raw_json"])
+ try:
+ otlp = _strict_otlp_payload(raw_json)
+ except (RecursionError, TypeError, ValueError, UnicodeError, OverflowError):
+ otlp = None
+ return {
+ "ingest_seq": int(row["ingest_seq"]),
+ "change_seq": int(row["ingest_seq"]),
+ "record_id": f'{row["trace_id"]}:{row["span_id"]}',
+ "trace_id": str(row["trace_id"]),
+ "span_id": str(row["span_id"]),
+ "record_revision": int(row["record_revision"]),
+ "lifecycle": str(row["lifecycle"]),
+ "operation": str(row["operation"]),
+ "observed_time_unix_nano": str(row["observed_time_unix_nano"]),
+ "raw_size_bytes": int(row["raw_size_bytes"]),
+ "otlp": otlp,
+ "raw_valid": otlp is not None,
+ }
+
+
+def _omitted_detail_record_from_row(row: aiosqlite.Row) -> dict[str, Any]:
+ """Describe a record that exceeds the projection budget without loading it."""
+ return {
+ "ingest_seq": int(row["ingest_seq"]),
+ "change_seq": int(row["ingest_seq"]),
+ "record_id": f'{row["trace_id"]}:{row["span_id"]}',
+ "trace_id": str(row["trace_id"]),
+ "span_id": str(row["span_id"]),
+ "record_revision": int(row["record_revision"]),
+ "lifecycle": str(row["lifecycle"]),
+ "operation": str(row["operation"]),
+ "observed_time_unix_nano": str(row["observed_time_unix_nano"]),
+ "raw_size_bytes": int(row["raw_size_bytes"]),
+ "otlp": None,
+ "raw_valid": None,
+ "projection_omitted": "record_too_large",
+ }
+
+
+def _archive_record_from_row(row: aiosqlite.Row) -> dict[str, Any]:
+ """Build one lossless, version-independent archive current record."""
+ raw_json = bytes(row["raw_json"])
+ try:
+ otlp = _strict_otlp_payload(raw_json)
+ except (RecursionError, TypeError, ValueError, UnicodeError, OverflowError):
+ otlp = None
+ return {
+ "record_id": f'{row["trace_id"]}:{row["span_id"]}',
+ "trace_id": str(row["trace_id"]),
+ "span_id": str(row["span_id"]),
+ "parent_span_id": row["parent_span_id"],
+ "record_revision": int(row["record_revision"]),
+ "lifecycle": str(row["lifecycle"]),
+ "operation": "upsert",
+ "change_seq": str(row["change_seq"]),
+ "start_time_unix_nano": str(row["start_time_unix_nano"]),
+ "observed_time_unix_nano": str(row["observed_time_unix_nano"]),
+ "end_time_unix_nano": str(row["end_time_unix_nano"]),
+ "session_id": row["session_id"],
+ "request_id": row["request_id"],
+ "run_id": row["run_id"],
+ "agent_mode": row["agent_mode"],
+ "schema_version": str(row["schema_version"]),
+ "source": str(row["source"]),
+ "created_at": int(row["created_at"]),
+ "update_kind": str(row["update_kind"]),
+ "raw_sha256": str(row["raw_sha256"]),
+ "raw_json_base64": base64.b64encode(raw_json).decode("ascii"),
+ "otlp": otlp,
+ "raw_valid": otlp is not None,
+ }
+
+
+def _strict_otlp_payload(raw_json: bytes) -> dict[str, Any]:
+ """Parse strict finite JSON and validate the minimum OTLP envelope shape."""
+
+ _validate_json_nesting(raw_json)
+
+ def _reject_constant(value: str) -> Any:
+ raise ValueError(f"non-finite JSON constant: {value}")
+
+ def _finite_float(value: str) -> float:
+ parsed = float(value)
+ if not math.isfinite(parsed):
+ raise ValueError("non-finite JSON number")
+ return parsed
+
+ payload = json.loads(
+ raw_json,
+ parse_constant=_reject_constant,
+ parse_float=_finite_float,
+ )
+ if not isinstance(payload, dict):
+ raise ValueError("OTLP record must be a JSON object")
+ if not isinstance(payload.get("resourceSpans"), list):
+ raise ValueError("OTLP record resourceSpans must be an array")
+ return payload
+
+
+def _validate_json_nesting(raw_json: bytes) -> None:
+ """Reject excessive JSON nesting without decoding or recursive traversal."""
+ depth = 0
+ in_string = False
+ escaped = False
+ for character in raw_json:
+ if in_string:
+ if escaped:
+ escaped = False
+ elif character == 0x5C:
+ escaped = True
+ elif character == 0x22:
+ in_string = False
+ continue
+ if character == 0x22:
+ in_string = True
+ continue
+ if character in (0x5B, 0x7B):
+ depth += 1
+ if depth > _MAX_JSON_NESTING_DEPTH:
+ raise ValueError("JSON nesting depth exceeds projection limit")
+ elif character in (0x5D, 0x7D):
+ depth -= 1
+
+
+__all__ = [
+ "AsyncTrajectoryReader",
+ "TrajectoryCursorError",
+ "TrajectoryStore",
+ "decode_revision_cursor",
+ "decode_trace_cursor",
+ "encode_revision_cursor",
+ "encode_trace_cursor",
+]
diff --git a/jiuwenswarm/observability/updates.py b/jiuwenswarm/observability/updates.py
new file mode 100644
index 0000000000..a5a3b3bb7f
--- /dev/null
+++ b/jiuwenswarm/observability/updates.py
@@ -0,0 +1,55 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Thread-safe post-commit trajectory update hints."""
+
+from __future__ import annotations
+
+import logging
+import threading
+from collections.abc import Callable
+
+from jiuwenswarm.observability.models import CommittedTraceUpdate
+
+logger = logging.getLogger(__name__)
+
+TrajectoryUpdateListener = Callable[[tuple[CommittedTraceUpdate, ...]], None]
+
+
+class TrajectoryUpdateBroker:
+ """Fan out committed revision hints without carrying raw trace payloads."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._listeners: set[TrajectoryUpdateListener] = set()
+
+ def register(self, listener: TrajectoryUpdateListener) -> None:
+ """Register one listener by callable identity."""
+ with self._lock:
+ self._listeners.add(listener)
+
+ def unregister(self, listener: TrajectoryUpdateListener) -> None:
+ """Unregister one listener by callable identity."""
+ with self._lock:
+ self._listeners.discard(listener)
+
+ def publish(self, updates: tuple[CommittedTraceUpdate, ...]) -> None:
+ """Publish immutable post-commit hints with listener isolation."""
+ if not updates:
+ return
+ with self._lock:
+ listeners = tuple(self._listeners)
+ for listener in listeners:
+ try:
+ listener(updates)
+ except Exception:
+ logger.exception("Trajectory update listener failed")
+
+
+trajectory_update_broker = TrajectoryUpdateBroker()
+
+
+__all__ = [
+ "TrajectoryUpdateBroker",
+ "TrajectoryUpdateListener",
+ "trajectory_update_broker",
+]
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index ddafa2d2b9..2bcb5f4703 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -487,6 +487,24 @@ agent_observability:
traces_dir: "" # file exporter 输出目录,默认 ~/.jiuwenswarm/.trace
file_retention_days: 7 # file exporter 文件保留天数
+# ============================================================
+# 单 Agent 轨迹观测 Web 数据面
+# ============================================================
+# enabled=true 会作为单 Agent OTel provider 的额外 demand,但仍完整复用
+# agent_observability 的 exporter、采样、脱敏、字段长度与 Langfuse 配置。
+# Processor 后的数据由 AgentServer 有界队列写入 SQLite;Gateway 只读查询。
+# Team / auto harness 本期不会向 Web 暴露轨迹。
+# ============================================================
+trajectory_ui:
+ enabled: true # 启用“对话 / 轨迹”数据链路
+ db_path: "" # 空值默认 ~/.jiuwenswarm/.trace/trajectory.sqlite3
+ retention_days: 7 # SQLite 轨迹保留天数
+ queue_size: 4096 # Agent 主线程非阻塞写入队列上限
+ batch_size: 64 # writer 单事务最大记录数
+ flush_interval_ms: 200 # writer 最大合批等待时间
+ poll_interval_ms: 2000 # Web 端兜底轮询间隔
+ detail_max_bytes: 4194304 # 单次详情响应累计 raw 投影预算(超大 Span 仅返回索引)
+
# ============================================================
# Agent / Code 调试链路追踪(Debug Trace)配置
# ============================================================
diff --git a/tests/unit_tests/agentserver/test_trajectory_runtime_wiring.py b/tests/unit_tests/agentserver/test_trajectory_runtime_wiring.py
index 4b14b3ccaa..2500a76597 100644
--- a/tests/unit_tests/agentserver/test_trajectory_runtime_wiring.py
+++ b/tests/unit_tests/agentserver/test_trajectory_runtime_wiring.py
@@ -1,117 +1,44 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Regression tests for process-level trajectory runtime wiring."""
+"""Regression tests for process-level trajectory runtime wiring.
+
+Provider demand coordination itself lives in the SDK
+(``openjiuwen.extensions.observability.demand``) and is covered there. What is
+tested here is this platform's half: the config gate that decides when each
+runtime asks for the provider, and that the shared trajectory processor still
+reaches the exporter pipeline through that path.
+"""
import pytest
-import openjiuwen.agent_teams.observability as observability
+from openjiuwen.agent_teams.observability import setup as team_observability_setup
+from openjiuwen.extensions.observability import demand as observability_demand
+from openjiuwen.extensions.observability import setup as shared_observability_setup
+from openjiuwen.harness.observability import setup as agent_observability_setup
+from openjiuwen.harness.observability import span_context as agent_span_context
from jiuwenswarm.agents.harness import agent_observability
-from jiuwenswarm.agents.harness import observability_runtime
from jiuwenswarm.agents.harness.team import team_manager
+from jiuwenswarm.observability import runtime as trajectory_runtime
@pytest.fixture(autouse=True)
def reset_observability_demands():
- observability_runtime.reset_observability_demands()
- agent_observability._agent_observability_active = False
- agent_observability._force_ever_enabled = False
- agent_observability._runtime_managed_agent_observability = False
- root_spans = getattr(agent_observability, "_ROOT_SPANS", None)
- if root_spans is not None:
- root_spans.clear()
- team_manager._observability_active = False
- team_manager._runtime_managed_observability = False
+ """Isolate the process-wide observability state around each test."""
+ def _reset():
+ trajectory_runtime.shutdown_trajectory_runtime()
+ observability_demand.reset_observability_demands()
+ agent_span_context.reset_run_root_spans()
+ agent_observability._agent_observability_active = False
+ agent_observability._force_ever_enabled = False
+ team_manager._observability_active = False
+
+ _reset()
yield
- observability_runtime.reset_observability_demands()
- agent_observability._agent_observability_active = False
- agent_observability._force_ever_enabled = False
- agent_observability._runtime_managed_agent_observability = False
- root_spans = getattr(agent_observability, "_ROOT_SPANS", None)
- if root_spans is not None:
- root_spans.clear()
- team_manager._observability_active = False
- team_manager._runtime_managed_observability = False
-
-
-def test_trajectory_processor_is_shared_across_runtimes(monkeypatch):
- processor = object()
- monkeypatch.setattr(
- observability_runtime, "_TRAJECTORY_SPAN_PROCESSOR", processor
- )
-
- first = observability_runtime.get_trajectory_span_processor()
- second = observability_runtime.get_trajectory_span_processor()
-
- assert first is processor
- assert second is first
-
-
-def test_trajectory_processor_returns_none_when_sdk_module_missing(monkeypatch):
- import builtins
-
- monkeypatch.setattr(observability_runtime, "_TRAJECTORY_SPAN_PROCESSOR", None)
- monkeypatch.setattr(observability_runtime, "_TRAJECTORY_UNAVAILABLE", False)
- real_import = builtins.__import__
-
- def _import(name, globals=None, locals=None, fromlist=(), level=0):
- if "agent_evolving.trajectory.processor" in name:
- raise ModuleNotFoundError(name)
- return real_import(name, globals, locals, fromlist, level)
-
- monkeypatch.setattr(builtins, "__import__", _import)
-
- assert observability_runtime.get_trajectory_span_processor() is None
- assert observability_runtime.get_trajectory_span_processor() is None
- assert observability_runtime._TRAJECTORY_UNAVAILABLE is True
-
-
-def test_acquire_observability_skips_missing_trajectory_processor(monkeypatch):
- calls = []
- monkeypatch.setattr(observability_runtime, "_TRAJECTORY_SPAN_PROCESSOR", None)
- monkeypatch.setattr(observability_runtime, "_TRAJECTORY_UNAVAILABLE", True)
- state = {"initialized": False}
- monkeypatch.setattr(observability, "is_initialized", lambda: state["initialized"])
- monkeypatch.setattr(
- observability,
- "init_observability",
- lambda _config, **kwargs: (
- calls.append(kwargs),
- state.__setitem__("initialized", True),
- ),
- )
-
- observability_runtime.acquire_observability_demand(
- "agent",
- observability_config=object(),
- )
-
- assert calls[0]["additional_span_processors"] == ()
-
-
-def test_acquire_observability_drops_unsupported_span_processor_kwarg(monkeypatch):
- calls = []
- monkeypatch.setattr(observability_runtime, "_TRAJECTORY_SPAN_PROCESSOR", object())
- monkeypatch.setattr(observability_runtime, "_TRAJECTORY_UNAVAILABLE", False)
- state = {"initialized": False}
- monkeypatch.setattr(observability, "is_initialized", lambda: state["initialized"])
-
- def _init(_config, *, span_exporter_override=None):
- del span_exporter_override
- calls.append(True)
- state["initialized"] = True
-
- monkeypatch.setattr(observability, "init_observability", _init)
-
- observability_runtime.acquire_observability_demand(
- "agent",
- observability_config=object(),
- )
-
- assert calls == [True]
+ _reset()
def test_agent_evolution_enables_observability_without_manual_switch(monkeypatch):
- requests = []
+ acquired = []
monkeypatch.setattr(
agent_observability,
"get_config",
@@ -122,18 +49,18 @@ def test_agent_evolution_enables_observability_without_manual_switch(monkeypatch
)
monkeypatch.setattr(
agent_observability,
- "acquire_observability_demand",
- lambda runtime, **_kwargs: requests.append(runtime),
+ "acquire_observability",
+ lambda config: acquired.append(config) or False,
)
agent_observability.sync_agent_observability()
- assert requests == ["agent"]
+ assert len(acquired) == 1
assert agent_observability._agent_observability_active is True
def test_team_evolution_enables_observability_without_manual_switch(monkeypatch):
- requests = []
+ acquired = []
monkeypatch.setattr(
team_manager,
"get_config",
@@ -143,226 +70,197 @@ def test_team_evolution_enables_observability_without_manual_switch(monkeypatch)
},
)
monkeypatch.setattr(
- team_manager,
- "acquire_observability_demand",
- lambda runtime, **_kwargs: requests.append(runtime),
+ team_manager.team_observability,
+ "acquire_observability",
+ lambda config: acquired.append(config) or False,
)
team_manager.sync_team_observability()
- assert requests == ["team"]
+ assert len(acquired) == 1
assert team_manager._observability_active is True
-def test_agent_observability_init_receives_process_processor(monkeypatch, tmp_path):
- processor = object()
- calls = []
+def test_team_observability_can_be_disabled_without_evolution_demand(monkeypatch):
+ releases = []
+ team_manager._observability_active = True
monkeypatch.setattr(
- observability_runtime, "_TRAJECTORY_SPAN_PROCESSOR", processor
+ team_manager.team_observability,
+ "release_observability",
+ lambda: releases.append("team"),
)
- monkeypatch.setattr(agent_observability, "_agent_observability_active", False)
- monkeypatch.setattr(agent_observability, "get_user_workspace_dir", lambda: tmp_path)
monkeypatch.setattr(
- agent_observability,
+ team_manager,
"get_config",
lambda: {
"react": {"evolution": {"skill_evolution": False}},
- "agent_observability": {"enabled": True},
+ "team_observability": {"enabled": False},
},
)
- state = {"initialized": False}
- monkeypatch.setattr(observability, "is_initialized", lambda: state["initialized"])
- monkeypatch.setattr(
- observability,
- "init_observability",
- lambda config, **kwargs: (
- calls.append((config, kwargs)),
- state.__setitem__("initialized", True),
- ),
- )
- agent_observability.sync_agent_observability()
+ team_manager.sync_team_observability()
- assert calls[0][1]["additional_span_processors"] == (processor,)
+ assert releases == ["team"]
-def test_team_observability_init_receives_process_processor(monkeypatch, tmp_path):
- processor = object()
- calls = []
- monkeypatch.setattr(
- observability_runtime, "_TRAJECTORY_SPAN_PROCESSOR", processor
- )
- monkeypatch.setattr(team_manager, "_observability_active", False)
- monkeypatch.setattr(team_manager, "get_user_workspace_dir", lambda: tmp_path)
+def test_trajectory_ui_is_an_additive_agent_provider_demand(monkeypatch, tmp_path):
+ acquired = []
+ runtime_settings = []
monkeypatch.setattr(
- team_manager,
+ agent_observability,
"get_config",
lambda: {
- "react": {"evolution": {"skill_evolution": False}},
- "team_observability": {"enabled": True},
+ "agent_observability": {"enabled": False, "exporter": "file"},
+ "trajectory_ui": {
+ "enabled": True,
+ "db_path": str(tmp_path / "trajectory.sqlite3"),
+ },
},
)
- state = {"initialized": False}
- monkeypatch.setattr(observability, "is_initialized", lambda: state["initialized"])
monkeypatch.setattr(
- observability,
- "init_observability",
- lambda config, **kwargs: (
- calls.append((config, kwargs)),
- state.__setitem__("initialized", True),
- ),
+ agent_observability,
+ "acquire_observability",
+ lambda config: acquired.append(config) or False,
+ )
+ monkeypatch.setattr(
+ agent_observability,
+ "sync_trajectory_runtime",
+ lambda settings: runtime_settings.append(settings),
)
- team_manager.sync_team_observability()
+ agent_observability.sync_agent_observability()
- assert calls[0][1]["additional_span_processors"] == (processor,)
+ assert len(acquired) == 1
+ assert len(runtime_settings) == 1
+ assert runtime_settings[0].enabled is True
+ assert runtime_settings[0].database_path == tmp_path / "trajectory.sqlite3"
+ assert agent_observability._agent_observability_active is True
-def test_team_observability_can_be_disabled_without_evolution_demand(monkeypatch):
- releases = []
- team_manager._observability_active = True
+def test_disabled_trajectory_runtime_is_stopped_while_exporters_remain_active(
+ monkeypatch,
+):
+ runtime_settings = []
monkeypatch.setattr(
- team_manager,
- "release_observability_demand",
- lambda runtime: releases.append(runtime),
- )
- monkeypatch.setattr(
- team_manager,
+ agent_observability,
"get_config",
lambda: {
- "react": {"evolution": {"skill_evolution": False}},
- "team_observability": {"enabled": False},
+ "agent_observability": {"enabled": True},
+ "trajectory_ui": {"enabled": False},
},
)
- team_manager.sync_team_observability()
-
- assert releases == ["team"]
-
-
-def test_shared_observability_demand_keeps_provider_until_last_runtime_releases(monkeypatch):
- state = {"initialized": False}
- shutdowns = []
-
- monkeypatch.setattr(observability, "is_initialized", lambda: state["initialized"])
-
- def _init(_config, **_kwargs):
- state["initialized"] = True
-
- monkeypatch.setattr(observability, "init_observability", _init)
monkeypatch.setattr(
- observability,
- "shutdown_observability",
- lambda: (shutdowns.append(True), state.__setitem__("initialized", False)),
- )
-
- config = object()
- observability_runtime.acquire_observability_demand(
- "agent",
- observability_config=config,
+ agent_observability,
+ "acquire_observability",
+ lambda _config: False,
)
- observability_runtime.acquire_observability_demand(
- "team",
- observability_config=config,
+ monkeypatch.setattr(
+ agent_observability,
+ "sync_trajectory_runtime",
+ lambda settings: runtime_settings.append(settings),
)
- observability_runtime.release_observability_demand("agent")
- assert state["initialized"] is True
- assert shutdowns == []
- observability_runtime.release_observability_demand("team")
- assert state["initialized"] is False
- assert shutdowns == [True]
-
-
-def test_shared_observability_demand_does_not_shutdown_external_provider(monkeypatch):
- shutdowns = []
- monkeypatch.setattr(observability, "is_initialized", lambda: True)
- monkeypatch.setattr(observability, "init_observability", lambda *_args, **_kwargs: None)
- monkeypatch.setattr(observability, "shutdown_observability", lambda: shutdowns.append(True))
-
- observability_runtime.acquire_observability_demand(
- "agent",
- observability_config=object(),
- )
- observability_runtime.release_observability_demand("agent")
+ agent_observability.sync_agent_observability()
- assert shutdowns == []
+ assert len(runtime_settings) == 1
+ assert runtime_settings[0].enabled is False
+ assert agent_observability._agent_observability_active is True
-def test_unified_agent_path_attaches_trajectory_processor(monkeypatch):
- attaches = []
+def test_agent_shutdown_unregisters_trajectory_before_releasing_provider(monkeypatch):
+ events = []
+ agent_observability._agent_observability_active = True
monkeypatch.setattr(
agent_observability,
- "_get_unified_runtime",
- lambda: type("R", (), {"is_unified_active": staticmethod(lambda: True)})(),
+ "shutdown_trajectory_runtime",
+ lambda: events.append("trajectory.shutdown") or True,
)
monkeypatch.setattr(
- "jiuwenswarm.agents.harness.observability_runtime.ensure_trajectory_span_processor_attached",
- lambda: attaches.append("agent") or True,
+ agent_observability,
+ "release_observability",
+ lambda: events.append("provider.release"),
)
- agent_observability.sync_agent_observability()
+ agent_observability.shutdown_agent_observability()
- assert attaches == ["agent"]
- assert agent_observability._agent_observability_active is True
- assert agent_observability._runtime_managed_agent_observability is True
+ assert events == ["trajectory.shutdown", "provider.release"]
+ assert agent_observability._agent_observability_active is False
-def test_unified_team_path_attaches_trajectory_processor(monkeypatch):
- attaches = []
+def test_agent_observability_init_receives_process_processor(monkeypatch, tmp_path):
+ """Evolution captures trajectories off the spans this processor sees."""
+ processor = object()
+ span_record_processor = object()
+ calls = []
+ state = {"initialized": False}
monkeypatch.setattr(
- team_manager,
- "_get_unified_runtime",
- lambda: type("R", (), {"is_unified_active": staticmethod(lambda: True)})(),
+ observability_demand, "get_trajectory_span_processor", lambda: processor
+ )
+ monkeypatch.setattr(
+ observability_demand,
+ "get_span_record_processor",
+ lambda: span_record_processor,
)
monkeypatch.setattr(
- "jiuwenswarm.agents.harness.observability_runtime.ensure_trajectory_span_processor_attached",
- lambda: attaches.append("team") or True,
+ shared_observability_setup, "is_initialized", lambda: state["initialized"]
+ )
+ monkeypatch.setattr(
+ agent_observability_setup,
+ "init_shared_observability",
+ lambda config, additional_span_processors=(): (
+ calls.append(additional_span_processors),
+ state.__setitem__("initialized", True),
+ ),
+ )
+ monkeypatch.setattr(agent_observability, "get_user_workspace_dir", lambda: tmp_path)
+ monkeypatch.setattr(
+ agent_observability,
+ "get_config",
+ lambda: {
+ "react": {"evolution": {"skill_evolution": False}},
+ "agent_observability": {"enabled": True},
+ },
)
- team_manager.sync_team_observability()
+ agent_observability.sync_agent_observability()
- assert attaches == ["team"]
- assert team_manager._observability_active is True
- assert team_manager._runtime_managed_observability is True
+ assert calls == [(processor, span_record_processor)]
-def test_ensure_trajectory_attaches_via_init_observability(monkeypatch):
+def test_team_observability_init_receives_process_processor(monkeypatch, tmp_path):
processor = object()
+ span_record_processor = object()
calls = []
- config = object()
+ state = {"initialized": False}
monkeypatch.setattr(
- observability_runtime, "_TRAJECTORY_SPAN_PROCESSOR", processor
+ observability_demand, "get_trajectory_span_processor", lambda: processor
+ )
+ monkeypatch.setattr(
+ observability_demand,
+ "get_span_record_processor",
+ lambda: span_record_processor,
+ )
+ monkeypatch.setattr(
+ shared_observability_setup, "is_initialized", lambda: state["initialized"]
)
- monkeypatch.setattr(observability_runtime, "_TRAJECTORY_UNAVAILABLE", False)
-
- import openjiuwen.agent_teams.observability.setup as obs_setup
-
- monkeypatch.setattr(obs_setup, "is_initialized", lambda: True)
- monkeypatch.setattr(obs_setup, "get_config", lambda: config)
monkeypatch.setattr(
- obs_setup,
+ team_observability_setup,
"init_observability",
- lambda cfg, **kwargs: calls.append((cfg, kwargs)),
+ lambda config, additional_span_processors=(): (
+ calls.append(additional_span_processors),
+ state.__setitem__("initialized", True),
+ ),
)
-
- assert observability_runtime.ensure_trajectory_span_processor_attached() is True
- assert calls == [(config, {"additional_span_processors": (processor,)})]
-
-
-def test_acquire_reattaches_trajectory_when_runtime_already_active(monkeypatch):
- attaches = []
- monkeypatch.setattr(observability, "is_initialized", lambda: True)
+ monkeypatch.setattr(team_manager, "get_user_workspace_dir", lambda: tmp_path)
monkeypatch.setattr(
- observability_runtime,
- "ensure_trajectory_span_processor_attached",
- lambda: attaches.append(True) or True,
+ team_manager,
+ "get_config",
+ lambda: {
+ "react": {"evolution": {"skill_evolution": False}},
+ "team_observability": {"enabled": True},
+ },
)
- observability_runtime._ACTIVE_RUNTIMES.add("agent")
- result = observability_runtime.acquire_observability_demand(
- "agent",
- observability_config=object(),
- )
+ team_manager.sync_team_observability()
- assert result is True
- assert attaches == [True]
+ assert calls == [(processor, span_record_processor)]
diff --git a/tests/unit_tests/channel/test_trajectory_frontend_artifacts.py b/tests/unit_tests/channel/test_trajectory_frontend_artifacts.py
new file mode 100644
index 0000000000..a6f92b7522
--- /dev/null
+++ b/tests/unit_tests/channel/test_trajectory_frontend_artifacts.py
@@ -0,0 +1,85 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+import shutil
+import subprocess
+import sys
+import zipfile
+from pathlib import Path
+
+
+_REPOSITORY_ROOT = Path(__file__).resolve().parents[3]
+_FRONTEND_ROOT = _REPOSITORY_ROOT / "jiuwenswarm" / "channels" / "web" / "frontend"
+_NOTICE_ROOT = Path("third-party") / "deepseek-harness"
+_ARTIFACT_FILES = ("LICENSE", "NOTICE.md", "NOTICE.zh.md")
+
+
+def _require_tool(name: str) -> str:
+ executable = shutil.which(name)
+ assert executable is not None, f"Required artifact build tool is unavailable: {name}"
+ return executable
+
+
+def _assert_notice_contents(contents: dict[str, str]) -> None:
+ license_text = contents["LICENSE"]
+ assert "MIT License" in license_text
+ assert "Copyright (c) 2026 DeepSeek" in license_text
+ assert "Permission is hereby granted, free of charge" in license_text
+ assert 'THE SOFTWARE IS PROVIDED "AS IS"' in license_text
+
+ for notice_name in ("NOTICE.md", "NOTICE.zh.md"):
+ notice_text = contents[notice_name]
+ assert "99f6f02fecdb7dff40c3fbc9470f5907c29f74ca" in notice_text
+ assert "packages/client/ui-trajectory" in notice_text
+ assert "packages/client/ui-theme/src/styles" in notice_text
+ assert "packages/client/ui-primitives/src" in notice_text
+
+
+def test_trajectory_license_and_notice_ship_in_vite_dist_and_python_wheel(tmp_path: Path) -> None:
+ npm = _require_tool("npm")
+ subprocess.run(
+ [npm, "exec", "--", "vite", "build", "--target", "chrome107"],
+ cwd=_FRONTEND_ROOT,
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+
+ public_root = _FRONTEND_ROOT / "public" / _NOTICE_ROOT
+ dist_root = _FRONTEND_ROOT / "dist" / _NOTICE_ROOT
+ public_contents = {
+ artifact_name: (public_root / artifact_name).read_text(encoding="utf-8")
+ for artifact_name in _ARTIFACT_FILES
+ }
+ dist_contents = {
+ artifact_name: (dist_root / artifact_name).read_text(encoding="utf-8")
+ for artifact_name in _ARTIFACT_FILES
+ }
+ assert dist_contents == public_contents
+ _assert_notice_contents(dist_contents)
+
+ subprocess.run(
+ [
+ sys.executable,
+ "-m",
+ "build",
+ "--wheel",
+ "--no-isolation",
+ "--outdir",
+ str(tmp_path),
+ ],
+ cwd=_REPOSITORY_ROOT,
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ wheel_paths = list(tmp_path.glob("*.whl"))
+ assert len(wheel_paths) == 1
+
+ wheel_contents: dict[str, str] = {}
+ wheel_prefix = "jiuwenswarm/channels/web/frontend/dist"
+ with zipfile.ZipFile(wheel_paths[0]) as wheel:
+ for artifact_name in _ARTIFACT_FILES:
+ archive_name = f"{wheel_prefix}/{_NOTICE_ROOT.as_posix()}/{artifact_name}"
+ wheel_contents[artifact_name] = wheel.read(archive_name).decode("utf-8")
+ assert wheel_contents == public_contents
+ _assert_notice_contents(wheel_contents)
diff --git a/tests/unit_tests/channel/test_trajectory_http.py b/tests/unit_tests/channel/test_trajectory_http.py
new file mode 100644
index 0000000000..c396d57ecd
--- /dev/null
+++ b/tests/unit_tests/channel/test_trajectory_http.py
@@ -0,0 +1,1217 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tests for the Gateway single-Agent trajectory HTTP API."""
+
+from __future__ import annotations
+
+import base64
+import http.client
+import io
+import json
+import logging
+import socket
+import sqlite3
+import threading
+import time
+from collections.abc import Iterator
+from contextlib import contextmanager
+from functools import partial
+from http.server import ThreadingHTTPServer
+from pathlib import Path
+from types import SimpleNamespace
+from urllib.parse import quote
+
+import httpx
+import pytest
+import uvicorn
+from fastapi import FastAPI
+
+from jiuwenswarm.channels.web.app_web import _SpaStaticHandler
+from jiuwenswarm.gateway.channel_manager.web.trajectory_http import (
+ TRAJECTORY_API_PREFIX,
+ TrajectoryHttpService,
+ attach_trajectory_routes,
+)
+from jiuwenswarm.observability.config import TrajectoryStoreSettings
+from jiuwenswarm.observability.models import TraceRecordData
+from jiuwenswarm.observability.store import AsyncTrajectoryReader, TrajectoryStore
+
+test_logger = logging.getLogger("tests.trajectory_http")
+
+_TRACE_ID = "4" * 32
+_SPAN_ID = "d" * 16
+_LATE_SPAN_ID = "e" * 16
+
+
+def _settings(database_path: Path, *, enabled: bool = True) -> TrajectoryStoreSettings:
+ return TrajectoryStoreSettings(
+ enabled=enabled,
+ database_path=database_path,
+ retention_days=7,
+ queue_size=16,
+ batch_size=8,
+ flush_interval_ms=20,
+ poll_interval_ms=2000,
+ )
+
+
+def _raw_record() -> bytes:
+ return (
+ b'{"resourceSpans":[{"resource":{},"scopeSpans":[{"scope":{},"spans":['
+ b'{"traceId":"44444444444444444444444444444444",'
+ b'"spanId":"dddddddddddddddd","parentSpanId":"","name":"agent.run",'
+ b'"startTimeUnixNano":"100","endTimeUnixNano":"200","status":{}}]}]}]}'
+ )
+
+
+def _seed(database_path: Path, *, session_id: str = "session-1") -> bytes:
+ raw_json = _raw_record()
+ core_record = SimpleNamespace(
+ raw_json=raw_json,
+ trace_id=_TRACE_ID,
+ span_id=_SPAN_ID,
+ parent_span_id=None,
+ start_time_unix_nano=100,
+ end_time_unix_nano=200,
+ session_id=session_id,
+ request_id="request-1",
+ run_id="run-1",
+ agent_mode="agent",
+ schema_version="1",
+ )
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records([TraceRecordData.from_core_record(core_record)])
+ finally:
+ store.close()
+ return raw_json
+
+
+def _append_late_span(database_path: Path, *, session_id: str = "session-1") -> None:
+ raw_json = _raw_record().replace(_SPAN_ID.encode("ascii"), _LATE_SPAN_ID.encode("ascii"))
+ core_record = SimpleNamespace(
+ raw_json=raw_json,
+ trace_id=_TRACE_ID,
+ span_id=_LATE_SPAN_ID,
+ parent_span_id=_SPAN_ID,
+ start_time_unix_nano=210,
+ end_time_unix_nano=300,
+ session_id=session_id,
+ request_id="request-1",
+ run_id="run-1",
+ agent_mode="agent",
+ schema_version="1",
+ )
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records([TraceRecordData.from_core_record(core_record)])
+ finally:
+ store.close()
+
+
+def _metadata_loader(mode: str = "agent"):
+ def _load(session_id: str) -> dict[str, str]:
+ if session_id in {"session-1", "session-2"}:
+ return {"session_id": session_id, "mode": mode, "team_name": ""}
+ return {}
+
+ return _load
+
+
+def _response_json(response) -> dict:
+ return json.loads(bytes(response.body))
+
+
+@contextmanager
+def _serve_asgi(app: FastAPI) -> Iterator[int]:
+ """Serve a FastAPI app on a real loopback socket for proxy tests."""
+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(128)
+ port = int(listener.getsockname()[1])
+ server = uvicorn.Server(
+ uvicorn.Config(
+ app,
+ host="127.0.0.1",
+ port=port,
+ log_level="critical",
+ access_log=False,
+ lifespan="off",
+ )
+ )
+ thread = threading.Thread(
+ target=server.run,
+ kwargs={"sockets": [listener]},
+ daemon=True,
+ )
+ thread.start()
+ deadline = time.monotonic() + 5
+ while not server.started and thread.is_alive() and time.monotonic() < deadline:
+ time.sleep(0.01)
+ if not server.started:
+ server.should_exit = True
+ thread.join(timeout=5)
+ listener.close()
+ raise RuntimeError("trajectory test Gateway did not start")
+ try:
+ yield port
+ finally:
+ server.should_exit = True
+ thread.join(timeout=5)
+ listener.close()
+
+
+@contextmanager
+def _serve_web_proxy(api_port: int, directory: Path) -> Iterator[int]:
+ """Serve the built-in Web UI reverse proxy on a loopback socket."""
+
+ class _TestProxyHandler(_SpaStaticHandler):
+ def log_message(self, message: str, *args) -> None:
+ test_logger.debug(message, *args)
+
+ _TestProxyHandler.api_target = f"http://127.0.0.1:{api_port}"
+ _TestProxyHandler.ws_target = f"ws://127.0.0.1:{api_port}"
+ handler = partial(_TestProxyHandler, directory=str(directory))
+ server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
+ server.daemon_threads = True
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield int(server.server_port)
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+
+def _proxy_get(
+ proxy_port: int,
+ path: str,
+ *,
+ headers: dict[str, str],
+) -> tuple[int, dict[str, str], bytes]:
+ """Issue one browser-facing request through the real Web proxy."""
+ connection = http.client.HTTPConnection("127.0.0.1", proxy_port, timeout=5)
+ try:
+ connection.request("GET", path, headers=headers)
+ response = connection.getresponse()
+ body = response.read()
+ response_headers = {
+ key.lower(): value
+ for key, value in response.getheaders()
+ }
+ return response.status, response_headers, body
+ finally:
+ connection.close()
+
+
+async def test_http_list_detail_and_raw_preserve_contract(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ expected_raw = _seed(database_path)
+ service = TrajectoryHttpService(
+ _settings(database_path),
+ reader=AsyncTrajectoryReader(database_path),
+ metadata_loader=_metadata_loader(),
+ )
+
+ list_response = await service.list_traces("session-1", limit=30, cursor=None)
+ list_payload = _response_json(list_response)
+ detail_response = await service.get_trace(
+ "session-1",
+ _TRACE_ID,
+ since_revision=0,
+ limit=1000,
+ )
+ detail_payload = _response_json(detail_response)
+ raw_response = await service.get_raw_record("session-1", _TRACE_ID, _SPAN_ID)
+
+ assert list_response.status_code == 200
+ assert list_response.headers["cache-control"] == "no-store"
+ assert list_payload["items"][0]["start_time_unix_nano"] == "100"
+ assert list_payload["items"][0]["end_time_unix_nano"] == "200"
+ assert isinstance(list_payload["revision_cursor"], str)
+ assert list_payload["revision_cursor"]
+ assert isinstance(list_payload["store_epoch"], str)
+ assert list_payload["store_epoch"]
+ assert detail_response.status_code == 200
+ assert detail_payload["trace_id"] == _TRACE_ID
+ detail_record = detail_payload["records"][0]
+ assert detail_record["record_id"] == f"{_TRACE_ID}:{_SPAN_ID}"
+ assert detail_record["record_revision"] == 1
+ assert detail_record["lifecycle"] == "final"
+ assert detail_record["operation"] == "upsert"
+ assert detail_record["change_seq"] == detail_payload["revision"]
+ assert detail_record["observed_time_unix_nano"] == "200"
+ assert detail_record["otlp"]["resourceSpans"]
+ assert raw_response.status_code == 200
+ assert raw_response.headers["cache-control"] == "no-store"
+ assert raw_response.headers["content-type"] == "application/json; charset=utf-8"
+ assert bytes(raw_response.body) == expected_raw
+ test_logger.info("HTTP contract returned list, detail, and exact raw bytes")
+
+
+async def test_http_revision_feed_reports_late_trace_change(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ _seed(database_path)
+ service = TrajectoryHttpService(
+ _settings(database_path),
+ reader=AsyncTrajectoryReader(database_path),
+ metadata_loader=_metadata_loader(),
+ )
+ list_response = await service.list_traces("session-1", limit=30, cursor=None)
+ revision_cursor = _response_json(list_response)["revision_cursor"]
+ _append_late_span(database_path)
+
+ revision_response = await service.list_revisions(
+ "session-1",
+ after_revision=revision_cursor,
+ limit=100,
+ )
+ payload = _response_json(revision_response)
+
+ assert revision_response.status_code == 200
+ assert revision_response.headers["cache-control"] == "no-store"
+ assert payload["session_id"] == "session-1"
+ assert payload["items"][0]["trace_id"] == _TRACE_ID
+ assert payload["items"][0]["span_count"] == 2
+ assert payload["items"][0]["start_time_unix_nano"] == "100"
+ assert payload["items"][0]["end_time_unix_nano"] == "300"
+ assert payload["has_more"] is False
+ assert payload["reset"] is False
+ assert payload["store_epoch"] == _response_json(list_response)["store_epoch"]
+ assert payload["next_cursor"] == payload["watermark"]
+ assert payload["next_cursor"] != revision_cursor
+ test_logger.info("HTTP revision feed exposed a late update to an old trace")
+
+
+async def test_http_archive_exports_all_current_records_beyond_list_window(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ records: list[TraceRecordData] = []
+ for index in range(105):
+ trace_id = f"{index + 1:032x}"
+ span_id = f"{index + 1:016x}"
+ raw_json = _raw_record().replace(
+ _TRACE_ID.encode("ascii"),
+ trace_id.encode("ascii"),
+ ).replace(
+ _SPAN_ID.encode("ascii"),
+ span_id.encode("ascii"),
+ )
+ core_record = SimpleNamespace(
+ raw_json=raw_json,
+ trace_id=trace_id,
+ span_id=span_id,
+ parent_span_id=None,
+ start_time_unix_nano=100 + index,
+ end_time_unix_nano=200 + index,
+ session_id="session-1",
+ request_id=f"request-{index + 1}",
+ run_id="run-archive",
+ agent_mode="agent",
+ schema_version="1",
+ record_revision=3,
+ observed_time_unix_nano=200 + index,
+ )
+ records.append(TraceRecordData.from_core_record(core_record))
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ result = store.write_records(records)
+ live_trace_id = f"{1:032x}"
+ live_span_id = "f" * 16
+ live_parent_span_id = f"{1:016x}"
+ live_raw = _raw_record().replace(
+ _TRACE_ID.encode("ascii"),
+ live_trace_id.encode("ascii"),
+ ).replace(
+ _SPAN_ID.encode("ascii"),
+ live_span_id.encode("ascii"),
+ ).replace(
+ b'"parentSpanId":""',
+ f'"parentSpanId":"{live_parent_span_id}"'.encode("ascii"),
+ ).replace(
+ b',"endTimeUnixNano":"200"',
+ b"",
+ )
+ for revision in (1, 2):
+ snapshot = SimpleNamespace(
+ raw_json=live_raw,
+ trace_id=live_trace_id,
+ span_id=live_span_id,
+ parent_span_id=live_parent_span_id,
+ start_time_unix_nano=150,
+ observed_time_unix_nano=150 + revision,
+ record_revision=revision,
+ update_kind="stream_chunk",
+ session_id="session-1",
+ request_id="request-live",
+ run_id="run-archive",
+ agent_mode="agent",
+ schema_version="1",
+ lifecycle="running",
+ )
+ store.write_records([TraceRecordData.from_core_snapshot(snapshot)])
+ finally:
+ store.close()
+ service = TrajectoryHttpService(
+ _settings(database_path),
+ reader=AsyncTrajectoryReader(database_path),
+ metadata_loader=_metadata_loader(),
+ )
+
+ list_payload = _response_json(
+ await service.list_traces("session-1", limit=30, cursor=None)
+ )
+ response = await service.export_archive("session-1")
+ payload = _response_json(response)
+
+ assert result.inserted == 105
+ assert len(list_payload["items"]) == 30
+ assert list_payload["next_cursor"] is not None
+ assert response.status_code == 200
+ assert response.headers["cache-control"] == "no-store"
+ assert response.headers["content-disposition"] == (
+ 'attachment; filename="trajectory-session-1.archive.json"'
+ )
+ assert payload["format"] == "openjiuwen.trajectory.archive"
+ assert payload["archive_version"] == 1
+ assert payload["session_id"] == "session-1"
+ assert payload["exported_at"].endswith("Z")
+ assert isinstance(payload["store_epoch"], str)
+ assert payload["revision"].isdecimal()
+ assert len(payload["records"]) == 106
+ assert len({record["record_id"] for record in payload["records"]}) == 106
+ assert {record["operation"] for record in payload["records"]} == {"upsert"}
+ assert all(
+ isinstance(record["change_seq"], str) and record["change_seq"].isdecimal()
+ for record in payload["records"]
+ )
+ live_records = [
+ record for record in payload["records"] if record["span_id"] == live_span_id
+ ]
+ assert len(live_records) == 1
+ assert live_records[0]["lifecycle"] == "running"
+ assert live_records[0]["record_revision"] == 2
+ final_records = [
+ record for record in payload["records"] if record["span_id"] != live_span_id
+ ]
+ assert {record["lifecycle"] for record in final_records} == {"final"}
+ assert {record["record_revision"] for record in final_records} == {3}
+ assert all(record["otlp"]["resourceSpans"] for record in payload["records"])
+ assert all(record["raw_valid"] is True for record in payload["records"])
+ assert all(record["raw_json_base64"] for record in payload["records"])
+ test_logger.info("archive exported every current record beyond the trace list window")
+
+
+async def test_http_archive_preserves_invalid_otlp_as_raw_base64(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ malformed_raw = b'{"resourceSpans":[invalid-json'
+ core_record = SimpleNamespace(
+ raw_json=malformed_raw,
+ trace_id=_TRACE_ID,
+ span_id=_SPAN_ID,
+ parent_span_id=None,
+ start_time_unix_nano=100,
+ end_time_unix_nano=200,
+ session_id="session-1",
+ request_id="request-invalid",
+ run_id="run-invalid",
+ agent_mode="agent",
+ schema_version="1",
+ )
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records([TraceRecordData.from_core_record(core_record)])
+ finally:
+ store.close()
+ service = TrajectoryHttpService(
+ _settings(database_path),
+ reader=AsyncTrajectoryReader(database_path),
+ metadata_loader=_metadata_loader(),
+ )
+
+ response = await service.export_archive("session-1")
+ payload = _response_json(response)
+ record = payload["records"][0]
+
+ assert response.status_code == 200
+ assert record["operation"] == "upsert"
+ assert record["otlp"] is None
+ assert record["raw_valid"] is False
+ assert base64.b64decode(record["raw_json_base64"], validate=True) == malformed_raw
+ test_logger.info("archive retained malformed OTLP bytes for offline diagnostics")
+
+
+async def test_http_revision_feed_exposes_epoch_reset_after_retention(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ _seed(database_path)
+ service = TrajectoryHttpService(
+ _settings(database_path),
+ reader=AsyncTrajectoryReader(database_path),
+ metadata_loader=_metadata_loader(),
+ )
+ baseline_payload = _response_json(
+ await service.list_traces("session-1", limit=30, cursor=None)
+ )
+
+ store = TrajectoryStore(database_path, retention_days=1)
+ store.initialize()
+ try:
+ assert store.delete_expired(now=int(time.time()) + 2 * 86400) == 1
+ finally:
+ store.close()
+
+ response = await service.list_revisions(
+ "session-1",
+ after_revision=baseline_payload["revision_cursor"],
+ limit=100,
+ )
+ payload = _response_json(response)
+
+ assert response.status_code == 200
+ assert response.headers["cache-control"] == "no-store"
+ assert payload["items"] == []
+ assert payload["reset"] is True
+ assert payload["store_epoch"] != baseline_payload["store_epoch"]
+ assert payload["next_cursor"] == payload["watermark"]
+ test_logger.info("HTTP revision response exposed retention as an epoch reset")
+
+
+async def test_http_revision_feed_rejects_invalid_cursor(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ _seed(database_path)
+ service = TrajectoryHttpService(
+ _settings(database_path),
+ metadata_loader=_metadata_loader(),
+ )
+
+ response = await service.list_revisions(
+ "session-1",
+ after_revision="not-a-cursor",
+ limit=100,
+ )
+
+ assert response.status_code == 400
+ assert response.headers["cache-control"] == "no-store"
+ assert _response_json(response)["code"] == "BAD_REQUEST"
+ test_logger.info("invalid revision cursors failed with the stable error envelope")
+
+
+async def test_http_forbids_team_and_auto_harness_sessions(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ _seed(database_path)
+ team_service = TrajectoryHttpService(
+ _settings(database_path),
+ metadata_loader=_metadata_loader("team.plan.normal"),
+ )
+ harness_service = TrajectoryHttpService(
+ _settings(database_path),
+ metadata_loader=_metadata_loader("auto_harness"),
+ )
+ harness_plan_service = TrajectoryHttpService(
+ _settings(database_path),
+ metadata_loader=_metadata_loader("auto_harness.plan"),
+ )
+
+ team_response = await team_service.list_traces("session-1", limit=30, cursor=None)
+ harness_response = await harness_service.list_traces(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+ harness_plan_response = await harness_plan_service.list_traces(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+
+ assert team_response.status_code == 403
+ assert team_response.headers["cache-control"] == "no-store"
+ assert _response_json(team_response)["code"] == "UNSUPPORTED_SESSION_MODE"
+ assert harness_response.status_code == 403
+ assert harness_response.headers["cache-control"] == "no-store"
+ assert _response_json(harness_response)["code"] == "UNSUPPORTED_SESSION_MODE"
+ assert harness_plan_response.status_code == 403
+ assert harness_plan_response.headers["cache-control"] == "no-store"
+ assert _response_json(harness_plan_response)["code"] == "UNSUPPORTED_SESSION_MODE"
+ test_logger.info("non-single-Agent sessions rejected by the server")
+
+
+async def test_http_fails_closed_for_unknown_or_missing_session_mode(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ _seed(database_path)
+ unknown = TrajectoryHttpService(
+ _settings(database_path),
+ metadata_loader=_metadata_loader("future.mode"),
+ )
+ missing = TrajectoryHttpService(
+ _settings(database_path),
+ metadata_loader=lambda _session_id: {"session_id": "session-1"},
+ )
+
+ unknown_response = await unknown.list_traces("session-1", limit=30, cursor=None)
+ missing_response = await missing.list_traces("session-1", limit=30, cursor=None)
+
+ assert unknown_response.status_code == 403
+ assert missing_response.status_code == 403
+ assert _response_json(unknown_response)["code"] == "UNSUPPORTED_SESSION_MODE"
+ assert _response_json(missing_response)["code"] == "UNSUPPORTED_SESSION_MODE"
+ test_logger.info("unknown session modes failed closed")
+
+
+async def test_http_prevents_cross_session_raw_access(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ _seed(database_path, session_id="session-1")
+ service = TrajectoryHttpService(
+ _settings(database_path),
+ metadata_loader=_metadata_loader(),
+ )
+
+ response = await service.get_raw_record("session-2", _TRACE_ID, _SPAN_ID)
+
+ assert response.status_code == 404
+ assert _response_json(response)["code"] == "NOT_FOUND"
+ test_logger.info("raw identity cannot cross the path session")
+
+
+async def test_http_reports_disabled_and_invalid_session(tmp_path: Path) -> None:
+ disabled = TrajectoryHttpService(
+ _settings(tmp_path / "trajectory.sqlite3", enabled=False),
+ metadata_loader=_metadata_loader(),
+ )
+ enabled = TrajectoryHttpService(
+ _settings(tmp_path / "trajectory.sqlite3"),
+ metadata_loader=_metadata_loader(),
+ )
+
+ disabled_response = await disabled.list_traces("session-1", limit=30, cursor=None)
+ invalid_response = await enabled.list_traces("../session", limit=30, cursor=None)
+
+ assert disabled_response.status_code == 503
+ assert disabled_response.headers["cache-control"] == "no-store"
+ assert _response_json(disabled_response)["code"] == "TRAJECTORY_DISABLED"
+ assert invalid_response.status_code == 400
+ assert invalid_response.headers["cache-control"] == "no-store"
+ assert _response_json(invalid_response)["code"] == "BAD_REQUEST"
+ test_logger.info("disabled and invalid-session states are explicit")
+
+
+async def test_http_empty_database_returns_an_empty_list(tmp_path: Path) -> None:
+ database_path = tmp_path / "not-created" / "trajectory.sqlite3"
+ service = TrajectoryHttpService(
+ _settings(database_path),
+ metadata_loader=_metadata_loader(),
+ )
+
+ response = await service.list_traces("session-1", limit=30, cursor=None)
+ payload = _response_json(response)
+
+ assert response.status_code == 200
+ assert response.headers["cache-control"] == "no-store"
+ assert payload["items"] == []
+ assert payload["next_cursor"] is None
+ assert database_path.exists() is False
+ test_logger.info("missing trajectory database remained a successful empty state")
+
+
+def test_attach_trajectory_routes_registers_all_paths(tmp_path: Path) -> None:
+ app = FastAPI()
+ channel = SimpleNamespace()
+ attach_trajectory_routes(
+ app,
+ channel,
+ settings=_settings(tmp_path / "trajectory.sqlite3"),
+ metadata_loader=_metadata_loader(),
+ )
+ paths = {getattr(route, "path", None) for route in app.router.routes}
+
+ assert f"{TRAJECTORY_API_PREFIX}/sessions/{{session_id}}/traces" in paths
+ assert f"{TRAJECTORY_API_PREFIX}/sessions/{{session_id}}/revisions" in paths
+ assert f"{TRAJECTORY_API_PREFIX}/sessions/{{session_id}}/archive" in paths
+ assert f"{TRAJECTORY_API_PREFIX}/sessions/{{session_id}}/traces/{{trace_id}}" in paths
+ assert (
+ f"{TRAJECTORY_API_PREFIX}/sessions/{{session_id}}/traces/{{trace_id}}/spans/{{span_id}}/raw"
+ in paths
+ )
+ test_logger.info("trajectory routes mounted on the WebChannel FastAPI app")
+
+
+async def test_archive_route_is_export_only_and_cannot_import_into_sqlite(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ _seed(database_path)
+ app = FastAPI()
+ attach_trajectory_routes(
+ app,
+ SimpleNamespace(),
+ settings=_settings(database_path),
+ metadata_loader=_metadata_loader(),
+ )
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ response = await client.post(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/archive",
+ json={
+ "format": "openjiuwen.trajectory.archive",
+ "archive_version": 1,
+ "records": [{"record_id": "attacker:record"}],
+ },
+ )
+
+ with sqlite3.connect(str(database_path)) as connection:
+ current_count = int(
+ connection.execute(
+ "SELECT COUNT(*) FROM trajectory_current_records"
+ ).fetchone()[0]
+ )
+ raw_count = int(
+ connection.execute("SELECT COUNT(*) FROM otlp_span_records").fetchone()[0]
+ )
+ assert response.status_code == 405
+ assert response.headers["cache-control"] == "no-store"
+ assert response.json()["code"] == "METHOD_NOT_ALLOWED"
+ assert current_count == 1
+ assert raw_count == 1
+ test_logger.info("archive API exposed no import mutation path")
+
+
+async def test_route_query_validation_keeps_no_store_header(tmp_path: Path) -> None:
+ app = FastAPI()
+ attach_trajectory_routes(
+ app,
+ SimpleNamespace(),
+ settings=_settings(tmp_path / "trajectory.sqlite3"),
+ metadata_loader=_metadata_loader(),
+ )
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ list_response = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces?limit=invalid",
+ )
+ detail_response = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces/{_TRACE_ID}"
+ "?since_revision=invalid",
+ )
+ huge_limit_response = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces",
+ params={"limit": "9" * 5000},
+ )
+ huge_revision_response = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces/{_TRACE_ID}",
+ params={"since_revision": "9" * 5000},
+ )
+
+ assert list_response.status_code == 400
+ assert list_response.headers["cache-control"] == "no-store"
+ assert detail_response.status_code == 400
+ assert detail_response.headers["cache-control"] == "no-store"
+ assert huge_limit_response.status_code == 400
+ assert huge_limit_response.headers["cache-control"] == "no-store"
+ assert huge_limit_response.json() == {
+ "error": "limit must be an integer",
+ "code": "BAD_REQUEST",
+ }
+ assert huge_revision_response.status_code == 400
+ assert huge_revision_response.headers["cache-control"] == "no-store"
+ assert huge_revision_response.json() == {
+ "error": "since_revision must be an integer",
+ "code": "BAD_REQUEST",
+ }
+ test_logger.info("route-level query errors used the trajectory error envelope")
+
+
+async def test_framework_trajectory_errors_are_json_and_non_cacheable(
+ tmp_path: Path,
+) -> None:
+ app = FastAPI()
+ attach_trajectory_routes(
+ app,
+ SimpleNamespace(),
+ settings=_settings(tmp_path / "trajectory.sqlite3"),
+ metadata_loader=_metadata_loader(),
+ )
+
+ @app.get(f"{TRAJECTORY_API_PREFIX}/validation-probe")
+ async def validation_probe(required: int):
+ return {"required": required}
+
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ not_found = await client.get(f"{TRAJECTORY_API_PREFIX}/missing")
+ method_not_allowed = await client.post(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces"
+ )
+ validation_error = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/validation-probe"
+ )
+ trace_not_found = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces/{_TRACE_ID}"
+ )
+
+ assert not_found.status_code == 404
+ assert not_found.headers["cache-control"] == "no-store"
+ assert not_found.json() == {
+ "error": "trajectory route not found",
+ "code": "NOT_FOUND",
+ }
+ assert method_not_allowed.status_code == 405
+ assert method_not_allowed.headers["cache-control"] == "no-store"
+ assert method_not_allowed.json() == {
+ "error": "trajectory method not allowed",
+ "code": "METHOD_NOT_ALLOWED",
+ }
+ assert validation_error.status_code == 400
+ assert validation_error.headers["cache-control"] == "no-store"
+ assert validation_error.json() == {
+ "error": "invalid trajectory request",
+ "code": "BAD_REQUEST",
+ }
+ assert trace_not_found.status_code == 404
+ assert trace_not_found.headers["cache-control"] == "no-store"
+ assert trace_not_found.json() == {
+ "error": "trace not found",
+ "code": "NOT_FOUND",
+ }
+ test_logger.info("framework 404, 405, and 422 responses used the HTTP envelope")
+
+
+async def test_routes_reuse_webchannel_origin_gate(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("JIUWENSWARM_ENABLE_ORIGIN_CHECK", "1")
+ monkeypatch.setenv("JIUWENSWARM_WS_ALLOWED_ORIGIN_HOSTS", "trusted.example")
+ app = FastAPI()
+ attach_trajectory_routes(
+ app,
+ SimpleNamespace(),
+ settings=_settings(tmp_path / "trajectory.sqlite3"),
+ metadata_loader=_metadata_loader(),
+ )
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
+ rejected = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces",
+ headers={"Origin": "https://evil.example"},
+ )
+ allowed = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces",
+ headers={"Origin": "https://trusted.example"},
+ )
+ same_origin_without_origin = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces",
+ headers={
+ "Host": "trusted.example",
+ "Sec-Fetch-Site": "same-origin",
+ },
+ )
+ spoofed_host_without_origin = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces",
+ headers={
+ "Host": "evil.example",
+ "Sec-Fetch-Site": "same-origin",
+ "X-Forwarded-Host": "trusted.example",
+ },
+ )
+ cross_site_without_origin = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces",
+ headers={
+ "Host": "trusted.example",
+ "Sec-Fetch-Site": "cross-site",
+ },
+ )
+ cross_site_with_allowed_origin = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces",
+ headers={
+ "Host": "trusted.example",
+ "Origin": "https://trusted.example",
+ "Sec-Fetch-Site": "cross-site",
+ },
+ )
+ allowed_referer_without_origin = await client.get(
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces",
+ headers={
+ "Host": "trusted.example",
+ "Referer": "https://trusted.example/app",
+ },
+ )
+
+ assert rejected.status_code == 403
+ assert rejected.json()["code"] == "FORBIDDEN_ORIGIN"
+ assert allowed.status_code == 200
+ assert same_origin_without_origin.status_code == 200
+ assert spoofed_host_without_origin.status_code == 403
+ assert cross_site_without_origin.status_code == 403
+ assert cross_site_with_allowed_origin.status_code == 403
+ assert allowed_referer_without_origin.status_code == 200
+ for response in (
+ rejected,
+ allowed,
+ same_origin_without_origin,
+ spoofed_host_without_origin,
+ cross_site_without_origin,
+ cross_site_with_allowed_origin,
+ allowed_referer_without_origin,
+ ):
+ assert response.headers["cache-control"] == "no-store"
+ test_logger.info("trajectory HTTP applied the configured browser Origin allowlist")
+
+
+async def test_http_internal_failures_return_stable_generic_messages(tmp_path: Path) -> None:
+ class _FailingReader:
+ async def list_traces_with_revision_cursor(self, *args, **kwargs):
+ raise ValueError("secret sqlite path /private/trajectory.sqlite3")
+
+ async def list_trace_revisions(self, *args, **kwargs):
+ raise ValueError("secret revision query text")
+
+ async def get_session_archive_records(self, *args, **kwargs):
+ raise ValueError("secret archive query text")
+
+ async def get_trace_records(self, *args, **kwargs):
+ raise ValueError("secret detail query text")
+
+ async def get_raw_record(self, *args, **kwargs):
+ raise ValueError("secret raw query text")
+
+ query_service = TrajectoryHttpService(
+ _settings(tmp_path / "trajectory.sqlite3"),
+ reader=_FailingReader(),
+ metadata_loader=_metadata_loader(),
+ )
+ metadata_service = TrajectoryHttpService(
+ _settings(tmp_path / "trajectory.sqlite3"),
+ metadata_loader=lambda _session_id: (_ for _ in ()).throw(
+ RuntimeError("secret metadata path")
+ ),
+ )
+
+ query_response = await query_service.list_traces(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+ valid_revision_cursor = _response_json(
+ await TrajectoryHttpService(
+ _settings(tmp_path / "baseline.sqlite3"),
+ metadata_loader=_metadata_loader(),
+ ).list_traces("session-1", limit=30, cursor=None)
+ )["revision_cursor"]
+ revision_response = await query_service.list_revisions(
+ "session-1",
+ after_revision=valid_revision_cursor,
+ limit=100,
+ )
+ archive_response = await query_service.export_archive("session-1")
+ detail_response = await query_service.get_trace(
+ "session-1",
+ _TRACE_ID,
+ since_revision=0,
+ limit=1000,
+ )
+ raw_response = await query_service.get_raw_record(
+ "session-1",
+ _TRACE_ID,
+ _SPAN_ID,
+ )
+ metadata_response = await metadata_service.list_traces(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+
+ for response in (
+ query_response,
+ revision_response,
+ archive_response,
+ detail_response,
+ raw_response,
+ ):
+ assert response.status_code == 500
+ assert response.headers["cache-control"] == "no-store"
+ assert _response_json(response) == {
+ "error": "trajectory query failed",
+ "code": "TRAJECTORY_QUERY_FAILED",
+ }
+ assert metadata_response.status_code == 500
+ assert _response_json(metadata_response) == {
+ "error": "session lookup failed",
+ "code": "SESSION_LOOKUP_FAILED",
+ }
+ test_logger.info("internal exception details remained server-side")
+
+
+async def test_http_rejects_noncanonical_and_oversized_cursors(tmp_path: Path) -> None:
+ service = TrajectoryHttpService(
+ _settings(tmp_path / "trajectory.sqlite3"),
+ metadata_loader=_metadata_loader(),
+ )
+
+ responses = [
+ await service.list_traces("session-1", limit=30, cursor="e30!!!"),
+ await service.list_traces("session-1", limit=30, cursor="e30="),
+ await service.list_traces("session-1", limit=30, cursor="A" * 513),
+ await service.list_traces("session-1", limit=30, cursor="e30"),
+ await service.list_revisions(
+ "session-1",
+ after_revision="e30!!!",
+ limit=100,
+ ),
+ await service.list_revisions(
+ "session-1",
+ after_revision="e30",
+ limit=100,
+ ),
+ ]
+
+ for response in responses:
+ assert response.status_code == 400
+ assert response.headers["cache-control"] == "no-store"
+ assert _response_json(response)["code"] == "BAD_REQUEST"
+ test_logger.info("noncanonical cursor text was rejected before SQLite decoding")
+
+
+def test_web_proxy_preserves_canonical_outer_host_without_loopback(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ captured: dict[str, object] = {}
+
+ class _FakeResponse:
+ status = 200
+ reason = "OK"
+
+ @staticmethod
+ def read() -> bytes:
+ return b'{"ok":true}'
+
+ @staticmethod
+ def getheaders() -> list[tuple[str, str]]:
+ return [("Content-Type", "application/json"), ("Connection", "close")]
+
+ class _FakeConnection:
+ def __init__(self, host: str, port: int, *, timeout: int) -> None:
+ captured["target"] = (host, port, timeout)
+ captured["closed"] = False
+
+ def request(
+ self,
+ method: str,
+ path: str,
+ *,
+ body: bytes,
+ headers: dict[str, str],
+ ) -> None:
+ captured["request"] = (method, path, body, headers)
+
+ @staticmethod
+ def getresponse() -> _FakeResponse:
+ return _FakeResponse()
+
+ @staticmethod
+ def close() -> None:
+ captured["closed"] = True
+
+ monkeypatch.setattr(http.client, "HTTPConnection", _FakeConnection)
+ handler = object.__new__(_SpaStaticHandler)
+ handler.headers = http.client.HTTPMessage()
+ handler.headers.add_header("Host", "Trusted.Example.:8443")
+ handler.headers.add_header("Sec-Fetch-Site", "same-origin")
+ handler.headers.add_header("Forwarded", "host=evil.example")
+ handler.headers.add_header("X-Forwarded-Host", "evil.example")
+ handler.headers.add_header("X-Original-Host", "evil.example")
+ handler.headers.add_header("X-JiuwenSwarm-Original-Host", "evil.example")
+ handler.headers.add_header("Connection", "keep-alive")
+ handler.command = "GET"
+ handler.path = f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces"
+ handler.api_target = "http://127.0.0.1:19090"
+ handler.rfile = io.BytesIO()
+ handler.wfile = io.BytesIO()
+ sent_status: list[tuple[int, str | None]] = []
+ sent_headers: list[tuple[str, str]] = []
+ handler.send_response = lambda status, reason=None: sent_status.append((status, reason))
+ handler.send_header = lambda key, value: sent_headers.append((key, value))
+ handler.end_headers = lambda: None
+ handler.log_error = lambda *_args: None
+
+ handler._proxy_http()
+
+ assert captured["target"][:2] == ("127.0.0.1", 19090)
+ method, path, body, forwarded = captured["request"]
+ assert (method, path, body) == ("GET", handler.path, b"")
+ assert forwarded["Host"] == "trusted.example:8443"
+ assert forwarded["Sec-Fetch-Site"] == "same-origin"
+ for untrusted_header in (
+ "Forwarded",
+ "X-Forwarded-Host",
+ "X-Original-Host",
+ "X-JiuwenSwarm-Original-Host",
+ "Connection",
+ ):
+ assert untrusted_header not in forwarded
+ assert captured["closed"] is True
+ assert sent_status == [(200, "OK")]
+ assert ("Connection", "close") not in sent_headers
+ assert handler.wfile.getvalue() == b'{"ok":true}'
+
+ invalid_handler = object.__new__(_SpaStaticHandler)
+ invalid_handler.headers = http.client.HTTPMessage()
+ invalid_handler.headers.add_header("Host", "trusted.example")
+ invalid_handler.headers.add_header("Host", "evil.example")
+ assert invalid_handler._clean_outer_host() is None
+
+
+def test_real_web_proxy_preserves_outer_host_and_guards_all_trajectory_reads(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("JIUWENSWARM_ENABLE_ORIGIN_CHECK", "1")
+ monkeypatch.setenv("JIUWENSWARM_WS_ALLOWED_ORIGIN_HOSTS", "trusted.example")
+ database_path = tmp_path / "trajectory.sqlite3"
+ expected_raw = _seed(database_path)
+ captured_headers: list[dict[str, str | None]] = []
+ app = FastAPI()
+
+ @app.middleware("http")
+ async def capture_proxy_headers(request, call_next):
+ captured_headers.append(
+ {
+ "host": request.headers.get("host"),
+ "forwarded": request.headers.get("forwarded"),
+ "x-forwarded-host": request.headers.get("x-forwarded-host"),
+ "x-original-host": request.headers.get("x-original-host"),
+ "x-jiuwenswarm-original-host": request.headers.get(
+ "x-jiuwenswarm-original-host"
+ ),
+ }
+ )
+ return await call_next(request)
+
+ attach_trajectory_routes(
+ app,
+ SimpleNamespace(),
+ settings=_settings(database_path),
+ metadata_loader=_metadata_loader(),
+ )
+
+ with _serve_asgi(app) as gateway_port:
+ with _serve_web_proxy(gateway_port, tmp_path) as proxy_port:
+ list_path = f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces"
+ status, headers, body = _proxy_get(
+ proxy_port,
+ list_path,
+ headers={
+ "Host": "trusted.example",
+ "Sec-Fetch-Site": "same-origin",
+ },
+ )
+ assert status == 200
+ assert headers["cache-control"] == "no-store"
+ revision_cursor = json.loads(body)["revision_cursor"]
+ paths = (
+ list_path,
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/revisions"
+ f"?after_revision={quote(revision_cursor, safe='')}",
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces/{_TRACE_ID}",
+ f"{TRAJECTORY_API_PREFIX}/sessions/session-1/traces/{_TRACE_ID}"
+ f"/spans/{_SPAN_ID}/raw",
+ )
+ for path in paths:
+ allowed_status, allowed_headers, allowed_body = _proxy_get(
+ proxy_port,
+ path,
+ headers={
+ "Host": "trusted.example",
+ "Sec-Fetch-Site": "same-origin",
+ },
+ )
+ assert allowed_status == 200
+ assert allowed_headers["cache-control"] == "no-store"
+ if path.endswith("/raw"):
+ assert allowed_body == expected_raw
+
+ denied_host_status, denied_host_headers, _ = _proxy_get(
+ proxy_port,
+ path,
+ headers={
+ "Host": "evil.example",
+ "Sec-Fetch-Site": "same-origin",
+ },
+ )
+ assert denied_host_status == 403
+ assert denied_host_headers["cache-control"] == "no-store"
+
+ denied_origin_status, denied_origin_headers, _ = _proxy_get(
+ proxy_port,
+ path,
+ headers={
+ "Host": "trusted.example",
+ "Origin": "https://evil.example",
+ },
+ )
+ assert denied_origin_status == 403
+ assert denied_origin_headers["cache-control"] == "no-store"
+
+ cross_site_status, cross_site_headers, _ = _proxy_get(
+ proxy_port,
+ path,
+ headers={
+ "Host": "trusted.example",
+ "Origin": "https://trusted.example",
+ "Sec-Fetch-Site": "cross-site",
+ },
+ )
+ assert cross_site_status == 403
+ assert cross_site_headers["cache-control"] == "no-store"
+
+ spoofed_status, spoofed_headers, _ = _proxy_get(
+ proxy_port,
+ list_path,
+ headers={
+ "Host": "evil.example",
+ "Sec-Fetch-Site": "same-origin",
+ "Forwarded": "host=trusted.example",
+ "X-Forwarded-Host": "trusted.example",
+ "X-Original-Host": "trusted.example",
+ "X-JiuwenSwarm-Original-Host": "trusted.example",
+ },
+ )
+
+ assert spoofed_status == 403
+ assert spoofed_headers["cache-control"] == "no-store"
+ assert captured_headers[-1] == {
+ "host": "evil.example",
+ "forwarded": None,
+ "x-forwarded-host": None,
+ "x-original-host": None,
+ "x-jiuwenswarm-original-host": None,
+ }
+ assert any(item["host"] == "trusted.example" for item in captured_headers)
+ test_logger.info("real proxy chain guarded list, revision, detail, and raw reads")
diff --git a/tests/unit_tests/observability/test_core_processor_integration.py b/tests/unit_tests/observability/test_core_processor_integration.py
new file mode 100644
index 0000000000..0b9116b09c
--- /dev/null
+++ b/tests/unit_tests/observability/test_core_processor_integration.py
@@ -0,0 +1,259 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Cross-repository regression for Core processor to Swarm SQLite delivery."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.trace import set_span_in_context
+
+from jiuwenswarm.observability.config import TrajectoryStoreSettings
+from jiuwenswarm.observability.sink import TrajectoryRecordSink
+from jiuwenswarm.observability.store import AsyncTrajectoryReader
+from openjiuwen.extensions.observability.span_record_processor import SpanRecordProcessor
+
+
+def _settings(database_path: Path) -> TrajectoryStoreSettings:
+ return TrajectoryStoreSettings(
+ enabled=True,
+ database_path=database_path,
+ retention_days=7,
+ queue_size=16,
+ batch_size=8,
+ flush_interval_ms=10,
+ poll_interval_ms=2000,
+ )
+
+
+def _span(record: dict[str, Any]) -> dict[str, Any]:
+ return record["otlp"]["resourceSpans"][0]["scopeSpans"][0]["spans"][0]
+
+
+def _attribute(span: dict[str, Any], key: str) -> Any:
+ for attribute in span.get("attributes", []):
+ if attribute.get("key") != key:
+ continue
+ value = attribute.get("value", {})
+ for value_key in (
+ "stringValue",
+ "boolValue",
+ "intValue",
+ "doubleValue",
+ ):
+ if value_key in value:
+ return value[value_key]
+ return None
+
+
+async def _wait_for_record(
+ reader: AsyncTrajectoryReader,
+ session_id: str,
+ trace_id: str,
+ span_id: str,
+ *,
+ lifecycle: str,
+ minimum_revision: int,
+) -> dict[str, Any]:
+ for _attempt in range(100):
+ detail = await reader.get_trace_records(
+ session_id,
+ trace_id,
+ since_revision=0,
+ limit=1000,
+ )
+ if detail is not None:
+ matches = [
+ record
+ for record in detail["records"]
+ if record.get("record_id") == f"{trace_id}:{span_id}"
+ and record.get("lifecycle") == lifecycle
+ and int(record.get("record_revision", 0)) >= minimum_revision
+ ]
+ if matches:
+ return matches[-1]
+ await asyncio.sleep(0.01)
+ raise AssertionError(
+ f"timed out waiting for {span_id} lifecycle={lifecycle} revision>={minimum_revision}"
+ )
+
+
+async def test_core_processor_delivers_child_then_complete_root_without_reencoding(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ sink = TrajectoryRecordSink(_settings(database_path))
+ processor = SpanRecordProcessor()
+ provider = TracerProvider()
+ provider.add_span_processor(processor)
+ tracer = provider.get_tracer("tests.core-swarm-trajectory")
+
+ session_id = "session-core-swarm"
+ request_id = "request-core-swarm"
+ sink.start()
+ processor.register_consumer(sink)
+ try:
+ root = tracer.start_span(
+ "agent.agent.session-core-swarm",
+ attributes={
+ "openjiuwen.trace.root": True,
+ "openjiuwen.trace.schema_version": "1",
+ "openjiuwen.trajectory.record.kind": "turn",
+ "openjiuwen.session.id": session_id,
+ "openjiuwen.request.id": request_id,
+ "openjiuwen.run.id": request_id,
+ "openjiuwen.agent.mode": "agent",
+ },
+ )
+ child = tracer.start_span(
+ "llm.call",
+ context=set_span_in_context(root),
+ attributes={
+ "openjiuwen.trace.schema_version": "1",
+ "openjiuwen.trajectory.record.kind": "inference",
+ "gen_ai.input.messages": json.dumps(
+ [{"role": "user", "parts": [{"type": "text", "content": "hello"}]}]
+ ),
+ "gen_ai.output.messages": json.dumps(
+ [{"role": "assistant", "parts": [{"type": "text", "content": "world"}]}]
+ ),
+ },
+ )
+ trace_id = f"{root.get_span_context().trace_id:032x}"
+ child_span_id = f"{child.get_span_context().span_id:016x}"
+ root_span_id = f"{root.get_span_context().span_id:016x}"
+
+ child.end()
+ root.set_attribute("openjiuwen.trace.complete", True)
+ root.end()
+ finally:
+ processor.unregister_consumer(sink)
+ assert sink.close(timeout=5) is True
+ provider.shutdown()
+
+ reader = AsyncTrajectoryReader(database_path)
+ detail = await reader.get_trace_records(
+ session_id,
+ trace_id,
+ since_revision=0,
+ limit=1000,
+ )
+
+ assert detail is not None
+ assert len(detail["records"]) == 2
+ child_record, root_record = detail["records"]
+ assert _span(child_record)["spanId"] == child_span_id
+ assert _span(root_record)["spanId"] == root_span_id
+ assert _span(child_record)["parentSpanId"] == root_span_id
+ assert _attribute(_span(root_record), "openjiuwen.trace.complete") is True
+
+ raw_root = await reader.get_raw_record(session_id, trace_id, root_span_id)
+ assert raw_root is not None
+ assert json.loads(raw_root) == root_record["otlp"]
+
+
+async def test_core_snapshot_is_visible_before_end_and_finalizes_same_identity(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory-live.sqlite3"
+ sink = TrajectoryRecordSink(_settings(database_path))
+ processor = SpanRecordProcessor()
+ provider = TracerProvider()
+ provider.add_span_processor(processor)
+ tracer = provider.get_tracer("tests.core-swarm-live-trajectory")
+ reader = AsyncTrajectoryReader(database_path)
+
+ session_id = "session-core-swarm-live"
+ root = None
+ child = None
+ sink.start()
+ processor.register_consumer(sink)
+ try:
+ routing = {
+ "openjiuwen.trace.schema_version": "1",
+ "openjiuwen.session.id": session_id,
+ "gen_ai.conversation.id": session_id,
+ "openjiuwen.request.id": "request-live",
+ "openjiuwen.run.id": "run-live",
+ "openjiuwen.agent.mode": "agent",
+ }
+ root = tracer.start_span(
+ "agent.agent.session-core-swarm-live",
+ attributes={
+ **routing,
+ "openjiuwen.trace.root": True,
+ "openjiuwen.trajectory.record.kind": "turn",
+ },
+ )
+ child = tracer.start_span(
+ "llm.call",
+ context=set_span_in_context(root),
+ attributes={
+ **routing,
+ "openjiuwen.trajectory.record.kind": "inference",
+ "gen_ai.input.messages": json.dumps(
+ [{"role": "user", "parts": [{"type": "text", "content": "hello"}]}]
+ ),
+ },
+ )
+ trace_id = f"{root.get_span_context().trace_id:032x}"
+ child_span_id = f"{child.get_span_context().span_id:016x}"
+
+ running = await _wait_for_record(
+ reader,
+ session_id,
+ trace_id,
+ child_span_id,
+ lifecycle="running",
+ minimum_revision=1,
+ )
+ assert "endTimeUnixNano" not in _span(running)
+ assert await reader.get_raw_record(session_id, trace_id, child_span_id) is None
+
+ child.set_attribute(
+ "gen_ai.output.messages",
+ json.dumps(
+ [{"role": "assistant", "parts": [{"type": "text", "content": "partial"}]}]
+ ),
+ )
+ processor.publish_snapshot(child, "stream_chunk")
+ updated = await _wait_for_record(
+ reader,
+ session_id,
+ trace_id,
+ child_span_id,
+ lifecycle="running",
+ minimum_revision=2,
+ )
+ assert _attribute(_span(updated), "gen_ai.output.messages") is not None
+
+ child.end()
+ child = None
+ final = await _wait_for_record(
+ reader,
+ session_id,
+ trace_id,
+ child_span_id,
+ lifecycle="final",
+ minimum_revision=3,
+ )
+ assert _span(final)["endTimeUnixNano"]
+ assert final["record_id"] == running["record_id"] == updated["record_id"]
+ raw_child = await reader.get_raw_record(session_id, trace_id, child_span_id)
+ assert raw_child is not None
+ assert json.loads(raw_child) == final["otlp"]
+ finally:
+ if child is not None:
+ child.end()
+ if root is not None:
+ root.end()
+ processor.unregister_consumer(sink)
+ assert sink.close(timeout=5) is True
+ provider.shutdown()
diff --git a/tests/unit_tests/observability/test_trace_sink.py b/tests/unit_tests/observability/test_trace_sink.py
new file mode 100644
index 0000000000..12143f93f0
--- /dev/null
+++ b/tests/unit_tests/observability/test_trace_sink.py
@@ -0,0 +1,391 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tests for the bounded trajectory consumer and writer lifecycle."""
+
+from __future__ import annotations
+
+import json
+import logging
+import queue
+import sqlite3
+import threading
+import time
+from collections.abc import Sequence
+from pathlib import Path
+from types import SimpleNamespace
+
+from jiuwenswarm.observability.config import TrajectoryStoreSettings
+from jiuwenswarm.observability.models import TraceRecordData, WriteBatchResult
+from jiuwenswarm.observability.sink import TrajectoryRecordSink
+from jiuwenswarm.observability.store import TrajectoryStore
+
+test_logger = logging.getLogger("tests.trajectory_sink")
+
+_TRACE_ID = "3" * 32
+_SPAN_ID = "c" * 16
+
+
+def _settings(
+ database_path: Path,
+ *,
+ queue_size: int = 16,
+ batch_size: int = 8,
+) -> TrajectoryStoreSettings:
+ return TrajectoryStoreSettings(
+ enabled=True,
+ database_path=database_path,
+ retention_days=7,
+ queue_size=queue_size,
+ batch_size=batch_size,
+ flush_interval_ms=10,
+ poll_interval_ms=2000,
+ )
+
+
+def _record(*, span_id: str = _SPAN_ID) -> SimpleNamespace:
+ raw_json = json.dumps(
+ {
+ "resourceSpans": [
+ {
+ "resource": {},
+ "scopeSpans": [
+ {
+ "scope": {},
+ "spans": [
+ {
+ "traceId": _TRACE_ID,
+ "spanId": span_id,
+ "parentSpanId": "",
+ "name": "agent.run",
+ "startTimeUnixNano": "100",
+ "endTimeUnixNano": "200",
+ "status": {},
+ }
+ ],
+ }
+ ],
+ }
+ ]
+ },
+ separators=(",", ":"),
+ ).encode("utf-8")
+ return SimpleNamespace(
+ raw_json=raw_json,
+ trace_id=_TRACE_ID,
+ span_id=span_id,
+ parent_span_id=None,
+ start_time_unix_nano=100,
+ end_time_unix_nano=200,
+ session_id="session-1",
+ request_id="request-1",
+ run_id="run-1",
+ agent_mode="agent",
+ schema_version="1",
+ )
+
+
+def _snapshot(revision: int) -> SimpleNamespace:
+ record = _record()
+ record.record_revision = revision
+ record.observed_time_unix_nano = 100 + revision
+ record.update_kind = "stream_chunk"
+ record.lifecycle = "running"
+ return record
+
+
+class _BlockingStore:
+ def __init__(self) -> None:
+ self.write_started = threading.Event()
+ self.release_write = threading.Event()
+
+ def initialize(self) -> None:
+ return
+
+ def delete_expired(self, *, now: int | None = None) -> int:
+ return 0
+
+ def write_records(self, records: Sequence[TraceRecordData]) -> WriteBatchResult:
+ self.write_started.set()
+ self.release_write.wait(timeout=10)
+ return WriteBatchResult(
+ inserted=len(records),
+ conflicts=0,
+ updates=(),
+ )
+
+ def close(self) -> None:
+ return
+
+
+class _BusyThenSuccessfulStore(_BlockingStore):
+ def __init__(self, failures: int) -> None:
+ super().__init__()
+ self.failures = failures
+ self.attempts = 0
+
+ def write_records(self, records: Sequence[TraceRecordData]) -> WriteBatchResult:
+ self.attempts += 1
+ if self.attempts <= self.failures:
+ raise sqlite3.OperationalError("database is locked")
+ return WriteBatchResult(inserted=len(records), conflicts=0, updates=())
+
+
+class _PausingInitializeStore(_BlockingStore):
+ def __init__(self) -> None:
+ super().__init__()
+ self.initialize_entered = threading.Event()
+ self.release_initialize = threading.Event()
+
+ def initialize(self) -> None:
+ self.initialize_entered.set()
+ self.release_initialize.wait(timeout=10)
+
+
+class _PausingQueue(queue.Queue):
+ def __init__(self, maxsize: int) -> None:
+ super().__init__(maxsize=maxsize)
+ self.put_entered = threading.Event()
+ self.release_put = threading.Event()
+
+ def put_nowait(self, item) -> None:
+ self.put_entered.set()
+ self.release_put.wait(timeout=10)
+ super().put_nowait(item)
+
+
+def test_sink_commits_before_notifying_and_drains_on_close(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ updates = []
+ sink = TrajectoryRecordSink(
+ _settings(database_path),
+ on_commit=lambda committed: updates.extend(committed),
+ )
+ record = _record()
+
+ sink.start()
+ sink.consume(record)
+ assert sink.close(timeout=5) is True
+
+ stats = sink.stats()
+ verifier = TrajectoryStore(database_path)
+ verifier.initialize()
+ try:
+ stored_raw = verifier.fetch_raw(_TRACE_ID, _SPAN_ID)
+ finally:
+ verifier.close()
+
+ assert stats.accepted == 1
+ assert stats.committed == 1
+ assert stats.dropped == 0
+ assert stats.failed == 0
+ assert stored_raw == record.raw_json
+ assert len(updates) == 1
+ assert updates[0].session_id == "session-1"
+ assert updates[0].trace_id == _TRACE_ID
+ assert updates[0].revision >= 1
+ test_logger.info("sink drained one record and emitted committed revision")
+
+
+def test_sink_drops_without_blocking_when_not_started(tmp_path: Path) -> None:
+ sink = TrajectoryRecordSink(_settings(tmp_path / "trajectory.sqlite3"))
+
+ sink.consume(_record())
+
+ stats = sink.stats()
+ assert stats.accepted == 0
+ assert stats.dropped == 1
+ assert stats.queued == 0
+ test_logger.info("inactive sink rejected record without queueing")
+
+
+def test_sink_queue_full_drops_without_blocking(tmp_path: Path) -> None:
+ store = _BlockingStore()
+ sink = TrajectoryRecordSink(
+ _settings(
+ tmp_path / "trajectory.sqlite3",
+ queue_size=1,
+ batch_size=1,
+ ),
+ store=store,
+ )
+ sink.start()
+ try:
+ sink.consume(_record(span_id="1" * 16))
+ assert store.write_started.wait(timeout=5)
+ sink.consume(_record(span_id="2" * 16))
+
+ started_at = time.monotonic()
+ sink.consume(_record(span_id="3" * 16))
+ elapsed = time.monotonic() - started_at
+
+ stats = sink.stats()
+ assert elapsed < 1.0
+ assert stats.accepted == 2
+ assert stats.dropped == 1
+ assert stats.queued == 1
+ finally:
+ store.release_write.set()
+ assert sink.close(timeout=5) is True
+ test_logger.info("full sink queue dropped immediately without blocking the caller")
+
+
+def test_sink_coalesces_pending_live_snapshots_by_identity(tmp_path: Path) -> None:
+ store = _BlockingStore()
+ sink = TrajectoryRecordSink(
+ _settings(tmp_path / "trajectory.sqlite3", queue_size=16, batch_size=1),
+ store=store,
+ )
+ sink.start()
+ try:
+ sink.consume_snapshot(_snapshot(1))
+ assert store.write_started.wait(timeout=5)
+ for revision in range(2, 11):
+ sink.consume_snapshot(_snapshot(revision))
+ stats_while_blocked = sink.stats()
+ assert stats_while_blocked.queued == 1
+ assert stats_while_blocked.coalesced == 8
+ finally:
+ store.release_write.set()
+ assert sink.close(timeout=5) is True
+ assert sink.stats().dropped_final == 0
+ test_logger.info("live snapshot flood retained only the newest pending identity")
+
+
+def test_sink_rejects_invalid_raw_type_without_raising(tmp_path: Path) -> None:
+ sink = TrajectoryRecordSink(_settings(tmp_path / "trajectory.sqlite3"))
+ record = _record()
+ record.raw_json = "not-bytes"
+
+ sink.consume(record)
+
+ stats = sink.stats()
+ assert stats.failed == 1
+ assert stats.dropped == 0
+ test_logger.info("invalid Core record isolated from the caller")
+
+
+def test_sink_close_waits_for_an_accepted_inflight_enqueue(tmp_path: Path) -> None:
+ sink = TrajectoryRecordSink(_settings(tmp_path / "trajectory.sqlite3"))
+ pausing_queue = _PausingQueue(maxsize=16)
+ sink._queue = pausing_queue
+ sink.start()
+
+ producer = threading.Thread(target=sink.consume, args=(_record(),))
+ producer.start()
+ assert pausing_queue.put_entered.wait(timeout=5)
+
+ close_result: list[bool] = []
+ closer = threading.Thread(
+ target=lambda: close_result.append(sink.close(timeout=5)),
+ )
+ closer.start()
+ try:
+ assert closer.is_alive()
+ finally:
+ pausing_queue.release_put.set()
+ producer.join(timeout=5)
+ closer.join(timeout=5)
+
+ stats = sink.stats()
+ assert producer.is_alive() is False
+ assert closer.is_alive() is False
+ assert close_result == [True]
+ assert stats.accepted == 1
+ assert stats.committed == 1
+ assert stats.queued == 0
+ test_logger.info("close could not overtake an accepted in-flight enqueue")
+
+
+def test_sink_retries_transient_sqlite_contention(tmp_path: Path) -> None:
+ store = _BusyThenSuccessfulStore(failures=1)
+ sink = TrajectoryRecordSink(
+ _settings(tmp_path / "trajectory.sqlite3"),
+ store=store,
+ )
+ sink.start()
+ sink.consume(_record())
+
+ assert sink.close(timeout=5) is True
+
+ stats = sink.stats()
+ assert store.attempts == 2
+ assert stats.accepted == 1
+ assert stats.committed == 1
+ assert stats.failed == 0
+ test_logger.info("transient SQLite lock retried within the bounded drain")
+
+
+def test_real_sqlite_busy_retry_finishes_before_default_close_deadline(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ initializer = TrajectoryStore(database_path)
+ initializer.initialize()
+ initializer.close()
+
+ sink = TrajectoryRecordSink(_settings(database_path))
+ sink.start()
+ locker = sqlite3.connect(str(database_path), check_same_thread=False)
+ locker.execute("PRAGMA busy_timeout=1000")
+ locker.execute("BEGIN IMMEDIATE")
+ released = threading.Event()
+
+ def _release_lock() -> None:
+ released.wait(timeout=5.2)
+ locker.commit()
+
+ releaser = threading.Thread(target=_release_lock)
+ releaser.start()
+ started_at = time.monotonic()
+ try:
+ sink.consume(_record())
+ assert sink.close() is True
+ finally:
+ released.set()
+ releaser.join(timeout=10)
+ locker.close()
+ elapsed = time.monotonic() - started_at
+
+ stats = sink.stats()
+ assert elapsed < 15.0
+ assert releaser.is_alive() is False
+ assert stats.accepted == 1
+ assert stats.committed == 1
+ assert stats.failed == 0
+ test_logger.info("real SQLite lock contention drained before the default deadline")
+
+
+def test_sink_close_during_startup_cannot_reopen_acceptance(tmp_path: Path) -> None:
+ store = _PausingInitializeStore()
+ sink = TrajectoryRecordSink(
+ _settings(tmp_path / "trajectory.sqlite3"),
+ store=store,
+ )
+ start_errors: list[BaseException] = []
+ close_results: list[bool] = []
+
+ def _start() -> None:
+ try:
+ sink.start()
+ except BaseException as exc:
+ start_errors.append(exc)
+
+ starter = threading.Thread(target=_start)
+ starter.start()
+ assert store.initialize_entered.wait(timeout=5)
+ closer = threading.Thread(target=lambda: close_results.append(sink.close(timeout=5)))
+ closer.start()
+ assert sink._stop_requested.wait(timeout=5)
+ store.release_initialize.set()
+ starter.join(timeout=5)
+ closer.join(timeout=5)
+
+ sink.consume(_record())
+ stats = sink.stats()
+ assert starter.is_alive() is False
+ assert closer.is_alive() is False
+ assert close_results == [True]
+ assert len(start_errors) == 1
+ assert isinstance(start_errors[0], RuntimeError)
+ assert stats.accepted == 0
+ assert stats.dropped == 1
+ assert stats.queued == 0
+ test_logger.info("startup could not reopen a sink after concurrent close")
diff --git a/tests/unit_tests/observability/test_trace_store.py b/tests/unit_tests/observability/test_trace_store.py
new file mode 100644
index 0000000000..d77d2876cf
--- /dev/null
+++ b/tests/unit_tests/observability/test_trace_store.py
@@ -0,0 +1,1846 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tests for lossless trajectory persistence and asynchronous reads."""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import json
+import logging
+import multiprocessing
+import sqlite3
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jiuwenswarm.observability.models import TraceRecordData
+from jiuwenswarm.observability.store import (
+ AsyncTrajectoryReader,
+ TrajectoryCursorError,
+ TrajectoryStore,
+ decode_revision_cursor,
+ decode_trace_cursor,
+ encode_revision_cursor,
+ encode_trace_cursor,
+)
+
+test_logger = logging.getLogger("tests.trajectory_store")
+
+_TRACE_ID = "1" * 32
+_SECOND_TRACE_ID = "2" * 32
+_ROOT_SPAN_ID = "a" * 16
+_CHILD_SPAN_ID = "b" * 16
+_THIRD_SPAN_ID = "c" * 16
+
+
+def _raw_record(
+ trace_id: str,
+ span_id: str,
+ *,
+ parent_span_id: str = "",
+ name: str = "agent.run",
+ status_code: str = "STATUS_CODE_UNSET",
+) -> bytes:
+ return json.dumps(
+ {
+ "resourceSpans": [
+ {
+ "resource": {"attributes": []},
+ "scopeSpans": [
+ {
+ "scope": {"name": "openjiuwen"},
+ "spans": [
+ {
+ "traceId": trace_id,
+ "spanId": span_id,
+ "parentSpanId": parent_span_id,
+ "name": name,
+ "startTimeUnixNano": "100",
+ "endTimeUnixNano": "200",
+ "status": {"code": status_code},
+ "attributes": [],
+ }
+ ],
+ }
+ ],
+ }
+ ]
+ },
+ ensure_ascii=False,
+ separators=(",", ":"),
+ ).encode("utf-8")
+
+
+def _core_record(
+ *,
+ trace_id: str = _TRACE_ID,
+ span_id: str = _ROOT_SPAN_ID,
+ parent_span_id: str | None = None,
+ session_id: str | None = "session-1",
+ request_id: str | None = "request-1",
+ run_id: str | None = "run-1",
+ agent_mode: str | None = "agent",
+ start_time: int = 100,
+ end_time: int = 200,
+ raw_json: bytes | None = None,
+) -> SimpleNamespace:
+ return SimpleNamespace(
+ raw_json=raw_json
+ if raw_json is not None
+ else _raw_record(
+ trace_id,
+ span_id,
+ parent_span_id=parent_span_id or "",
+ ),
+ trace_id=trace_id,
+ span_id=span_id,
+ parent_span_id=parent_span_id,
+ start_time_unix_nano=start_time,
+ end_time_unix_nano=end_time,
+ session_id=session_id,
+ request_id=request_id,
+ run_id=run_id,
+ agent_mode=agent_mode,
+ schema_version="1",
+ )
+
+
+def _stored_record(**overrides: object) -> TraceRecordData:
+ return TraceRecordData.from_core_record(_core_record(**overrides))
+
+
+def _snapshot_record(revision: int, *, name: str) -> TraceRecordData:
+ raw_json = _raw_record(_TRACE_ID, _ROOT_SPAN_ID, name=name).replace(
+ b',"endTimeUnixNano":"200"',
+ b"",
+ )
+ snapshot = SimpleNamespace(
+ raw_json=raw_json,
+ trace_id=_TRACE_ID,
+ span_id=_ROOT_SPAN_ID,
+ parent_span_id=None,
+ start_time_unix_nano=100,
+ observed_time_unix_nano=100 + revision,
+ record_revision=revision,
+ update_kind="stream_chunk",
+ session_id="session-1",
+ request_id="request-1",
+ run_id="run-1",
+ agent_mode="agent",
+ schema_version="1",
+ lifecycle="running",
+ )
+ return TraceRecordData.from_core_snapshot(snapshot)
+
+
+def _detail_span_id(record: dict[str, Any]) -> str:
+ return str(
+ record["otlp"]["resourceSpans"][0]["scopeSpans"][0]["spans"][0]["spanId"]
+ )
+
+
+def _opaque_cursor(payload: dict[str, Any]) -> str:
+ raw_payload = json.dumps(payload, separators=(",", ":")).encode("utf-8")
+ return base64.urlsafe_b64encode(raw_payload).decode("ascii").rstrip("=")
+
+
+def _write_with_open_wal(database_path: str, ready: Any, release: Any) -> None:
+ store = TrajectoryStore(Path(database_path))
+ store.initialize()
+ try:
+ store.write_records([_stored_record()])
+ ready.set()
+ release.wait(timeout=10)
+ finally:
+ store.close()
+
+
+def test_store_preserves_exact_raw_and_records_hash_conflict(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ store = TrajectoryStore(database_path)
+ original_raw = _raw_record(_TRACE_ID, _ROOT_SPAN_ID, name="first")
+ conflicting_raw = _raw_record(_TRACE_ID, _ROOT_SPAN_ID, name="second")
+ store.initialize()
+ try:
+ first = store.write_records([_stored_record(raw_json=original_raw)])
+ replay = store.write_records([_stored_record(raw_json=original_raw)])
+ conflict = store.write_records([_stored_record(raw_json=conflicting_raw)])
+
+ assert first.inserted == 1
+ assert replay.inserted == 0
+ assert replay.conflicts == 0
+ assert conflict.inserted == 0
+ assert conflict.conflicts == 1
+ assert store.count_conflicts() == 1
+ assert store.fetch_raw(_TRACE_ID, _ROOT_SPAN_ID) == original_raw
+ assert store.fetch_raw_sha256(
+ _TRACE_ID,
+ _ROOT_SPAN_ID,
+ ) == hashlib.sha256(original_raw).hexdigest()
+ finally:
+ store.close()
+ test_logger.info("raw bytes preserved across replay and conflict")
+
+
+async def test_live_revisions_finalize_in_place_and_reject_late_running(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ first = store.write_records([_snapshot_record(1, name="running-1")])
+ newest = store.write_records([_snapshot_record(3, name="running-3")])
+ stale = store.write_records([_snapshot_record(2, name="running-2")])
+ final_record = _stored_record(raw_json=_raw_record(_TRACE_ID, _ROOT_SPAN_ID, name="final"))
+ final = store.write_records([final_record])
+ late = store.write_records([_snapshot_record(4, name="late-running")])
+
+ connection = store._require_connection()
+ current = connection.execute(
+ """
+ SELECT lifecycle, record_revision, raw_json
+ FROM trajectory_current_records
+ WHERE trace_id = ? AND span_id = ?
+ """,
+ (_TRACE_ID, _ROOT_SPAN_ID),
+ ).fetchone()
+ change_count = connection.execute(
+ """
+ SELECT COUNT(*) AS count
+ FROM trajectory_changes
+ WHERE trace_id = ? AND span_id = ?
+ """,
+ (_TRACE_ID, _ROOT_SPAN_ID),
+ ).fetchone()
+ finally:
+ store.close()
+
+ assert first.inserted == 1
+ assert newest.inserted == 1
+ assert stale.inserted == 0
+ assert final.inserted == 1
+ assert late.inserted == 0
+ assert current is not None
+ assert current["lifecycle"] == "final"
+ assert bytes(current["raw_json"]) == final_record.raw_json
+ assert change_count is not None and int(change_count["count"]) == 3
+
+ detail = await AsyncTrajectoryReader(database_path).get_trace_records(
+ "session-1",
+ _TRACE_ID,
+ since_revision=0,
+ limit=100,
+ )
+ assert detail is not None
+ assert [record["lifecycle"] for record in detail["records"]] == [
+ "running",
+ "running",
+ "final",
+ ]
+ assert {record["record_id"] for record in detail["records"]} == {
+ f"{_TRACE_ID}:{_ROOT_SPAN_ID}"
+ }
+ assert await AsyncTrajectoryReader(database_path).get_raw_record(
+ "session-1",
+ _TRACE_ID,
+ _ROOT_SPAN_ID,
+ ) == final_record.raw_json
+ test_logger.info("running revisions atomically converged on one authoritative final identity")
+
+
+async def test_store_preserves_multiple_step_request_spans_and_real_timing(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ step_one_span_id = "d" * 16
+ request_one_span_id = "e" * 16
+ step_two_span_id = "f" * 16
+ request_two_span_id = "9" * 16
+ specifications = (
+ (_ROOT_SPAN_ID, None, "turn-request", 100, 600, "agent.run"),
+ (step_one_span_id, _ROOT_SPAN_ID, "turn-request", 200, 350, "agent.iteration"),
+ (request_one_span_id, step_one_span_id, "model-request-1", 250, 330, "llm.chat"),
+ (step_two_span_id, _ROOT_SPAN_ID, "turn-request", 400, 560, "agent.iteration"),
+ (request_two_span_id, step_two_span_id, "model-request-2", 450, 540, "llm.chat"),
+ )
+ records: list[TraceRecordData] = []
+ for span_id, parent_span_id, request_id, start_time, end_time, name in specifications:
+ raw_payload = json.loads(
+ _raw_record(
+ _TRACE_ID,
+ span_id,
+ parent_span_id=parent_span_id or "",
+ name=name,
+ )
+ )
+ raw_span = raw_payload["resourceSpans"][0]["scopeSpans"][0]["spans"][0]
+ raw_span["startTimeUnixNano"] = str(start_time)
+ raw_span["endTimeUnixNano"] = str(end_time)
+ raw_span["attributes"] = [
+ {
+ "key": "openjiuwen.request.id",
+ "value": {"stringValue": request_id},
+ }
+ ]
+ records.append(
+ _stored_record(
+ span_id=span_id,
+ parent_span_id=parent_span_id,
+ request_id=request_id,
+ start_time=start_time,
+ end_time=end_time,
+ raw_json=json.dumps(
+ raw_payload,
+ separators=(",", ":"),
+ ).encode("utf-8"),
+ )
+ )
+
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ result = store.write_records(records)
+ connection = store._require_connection()
+ current_rows = connection.execute(
+ """
+ SELECT span_id, parent_span_id, request_id, start_time_unix_nano
+ FROM trajectory_current_records
+ WHERE trace_id = ?
+ ORDER BY start_time_unix_nano ASC
+ """,
+ (_TRACE_ID,),
+ ).fetchall()
+ change_rows = connection.execute(
+ """
+ SELECT span_id, parent_span_id, request_id, start_time_unix_nano
+ FROM trajectory_changes
+ WHERE trace_id = ?
+ ORDER BY start_time_unix_nano ASC
+ """,
+ (_TRACE_ID,),
+ ).fetchall()
+ finally:
+ store.close()
+
+ expected = {
+ span_id: (parent_span_id, request_id, start_time)
+ for span_id, parent_span_id, request_id, start_time, _end_time, _name in specifications
+ }
+ assert result.inserted == len(specifications)
+ assert {
+ str(row["span_id"]): (
+ row["parent_span_id"],
+ row["request_id"],
+ int(row["start_time_unix_nano"]),
+ )
+ for row in current_rows
+ } == expected
+ assert {
+ str(row["span_id"]): (
+ row["parent_span_id"],
+ row["request_id"],
+ int(row["start_time_unix_nano"]),
+ )
+ for row in change_rows
+ } == expected
+
+ detail = await AsyncTrajectoryReader(database_path).get_trace_records(
+ "session-1",
+ _TRACE_ID,
+ since_revision=0,
+ limit=100,
+ )
+ assert detail is not None
+ assert len(detail["records"]) == len(specifications)
+ detail_spans = {
+ str(record["span_id"]): record["otlp"]["resourceSpans"][0]["scopeSpans"][0]["spans"][0]
+ for record in detail["records"]
+ }
+ assert set(detail_spans) == set(expected)
+ for span_id, (parent_span_id, request_id, start_time) in expected.items():
+ span = detail_spans[span_id]
+ assert span.get("parentSpanId", "") == (parent_span_id or "")
+ assert int(span["startTimeUnixNano"]) == start_time
+ assert span["attributes"] == [
+ {
+ "key": "openjiuwen.request.id",
+ "value": {"stringValue": request_id},
+ }
+ ]
+ assert detail_spans[request_one_span_id]["parentSpanId"] == step_one_span_id
+ assert detail_spans[request_two_span_id]["parentSpanId"] == step_two_span_id
+ test_logger.info("multiple iteration requests preserved independent identity, parent, and timing")
+
+
+def test_store_restart_marks_unfinished_snapshot_abandoned(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ store.write_records([_snapshot_record(2, name="unfinished")])
+ store.close()
+
+ reopened = TrajectoryStore(database_path)
+ reopened.initialize()
+ try:
+ connection = reopened._require_connection()
+ recovered = connection.execute(
+ """
+ SELECT lifecycle, end_time_unix_nano
+ FROM trajectory_current_records
+ WHERE trace_id = ? AND span_id = ?
+ """,
+ (_TRACE_ID, _ROOT_SPAN_ID),
+ ).fetchone()
+ finalized = reopened.write_records([_stored_record()])
+ terminal = connection.execute(
+ """
+ SELECT lifecycle
+ FROM trajectory_current_records
+ WHERE trace_id = ? AND span_id = ?
+ """,
+ (_TRACE_ID, _ROOT_SPAN_ID),
+ ).fetchone()
+ finally:
+ reopened.close()
+
+ assert recovered is not None
+ assert recovered["lifecycle"] == "abandoned"
+ assert int(recovered["end_time_unix_nano"]) == 0
+ assert finalized.inserted == 1
+ assert terminal is not None and terminal["lifecycle"] == "final"
+ test_logger.info("restart preserved unfinished evidence without inventing an end time")
+
+
+async def test_store_reconciles_orphan_without_rewriting_raw(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ store = TrajectoryStore(database_path)
+ child_raw = _raw_record(
+ _TRACE_ID,
+ _CHILD_SPAN_ID,
+ parent_span_id=_ROOT_SPAN_ID,
+ name="llm.chat",
+ )
+ root_raw = _raw_record(_TRACE_ID, _ROOT_SPAN_ID)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ span_id=_CHILD_SPAN_ID,
+ parent_span_id=_ROOT_SPAN_ID,
+ session_id=None,
+ request_id=None,
+ run_id=None,
+ start_time=110,
+ end_time=150,
+ raw_json=child_raw,
+ )
+ ]
+ )
+ store.write_records([_stored_record(raw_json=root_raw)])
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ items, next_cursor = await reader.list_traces("session-1", limit=30, cursor=None)
+ detail = await reader.get_trace_records(
+ "session-1",
+ _TRACE_ID,
+ since_revision=0,
+ limit=1000,
+ )
+ child_after_reconcile = await reader.get_raw_record(
+ "session-1",
+ _TRACE_ID,
+ _CHILD_SPAN_ID,
+ )
+
+ assert next_cursor is None
+ assert len(items) == 1
+ assert items[0]["span_count"] == 2
+ assert detail is not None
+ assert len(detail["records"]) == 2
+ assert child_after_reconcile == child_raw
+ test_logger.info("orphan reconciled with raw bytes unchanged")
+
+
+async def test_store_reconciles_late_orphan_from_existing_root(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ root_raw = _raw_record(_TRACE_ID, _ROOT_SPAN_ID)
+ child_raw = _raw_record(
+ _TRACE_ID,
+ _CHILD_SPAN_ID,
+ parent_span_id=_ROOT_SPAN_ID,
+ name="llm.chat",
+ )
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records([_stored_record(raw_json=root_raw)])
+ store.write_records(
+ [
+ _stored_record(
+ span_id=_CHILD_SPAN_ID,
+ parent_span_id=_ROOT_SPAN_ID,
+ session_id=None,
+ request_id=None,
+ run_id=None,
+ start_time=110,
+ end_time=150,
+ raw_json=child_raw,
+ )
+ ]
+ )
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ items, _cursor = await reader.list_traces("session-1", limit=30, cursor=None)
+ child_after_reconcile = await reader.get_raw_record(
+ "session-1",
+ _TRACE_ID,
+ _CHILD_SPAN_ID,
+ )
+
+ assert len(items) == 1
+ assert items[0]["span_count"] == 2
+ assert child_after_reconcile == child_raw
+ test_logger.info("late orphan inherited the existing trace session hint")
+
+
+async def test_reader_paginates_traces_and_flags_error_status(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ error_raw = _raw_record(
+ _SECOND_TRACE_ID,
+ _ROOT_SPAN_ID,
+ status_code="STATUS_CODE_ERROR",
+ )
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ trace_id=_TRACE_ID,
+ start_time=100,
+ end_time=200,
+ ),
+ _stored_record(
+ trace_id=_SECOND_TRACE_ID,
+ start_time=300,
+ end_time=400,
+ raw_json=error_raw,
+ ),
+ ]
+ )
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ first_page, cursor = await reader.list_traces("session-1", limit=1, cursor=None)
+ second_page, final_cursor = await reader.list_traces(
+ "session-1",
+ limit=1,
+ cursor=cursor,
+ )
+
+ assert len(first_page) == 1
+ assert first_page[0]["trace_id"] == _SECOND_TRACE_ID
+ assert first_page[0]["has_error"] is True
+ assert cursor is not None
+ assert len(second_page) == 1
+ assert second_page[0]["trace_id"] == _TRACE_ID
+ assert final_cursor is None
+ test_logger.info("cursor pagination preserved newest-first trace ordering")
+
+
+async def test_detail_pagination_never_skips_non_monotonic_span_times(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ span_id=_ROOT_SPAN_ID,
+ start_time=300,
+ raw_json=_raw_record(_TRACE_ID, _ROOT_SPAN_ID),
+ ),
+ _stored_record(
+ span_id=_CHILD_SPAN_ID,
+ start_time=100,
+ raw_json=_raw_record(_TRACE_ID, _CHILD_SPAN_ID),
+ ),
+ _stored_record(
+ span_id=_THIRD_SPAN_ID,
+ start_time=200,
+ raw_json=_raw_record(_TRACE_ID, _THIRD_SPAN_ID),
+ ),
+ ]
+ )
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ first_page = await reader.get_trace_records(
+ "session-1",
+ _TRACE_ID,
+ since_revision=0,
+ limit=2,
+ )
+ assert first_page is not None
+ second_page = await reader.get_trace_records(
+ "session-1",
+ _TRACE_ID,
+ since_revision=first_page["next_since_revision"],
+ limit=2,
+ )
+
+ assert second_page is not None
+ span_ids = [
+ _detail_span_id(record)
+ for record in [*first_page["records"], *second_page["records"]]
+ ]
+ assert span_ids == [_ROOT_SPAN_ID, _CHILD_SPAN_ID, _THIRD_SPAN_ID]
+ assert first_page["has_more"] is True
+ assert second_page["has_more"] is False
+ assert second_page["next_since_revision"] == second_page["revision"]
+ test_logger.info("ingest-sequence continuation returned every record once")
+
+
+async def test_gateway_reader_sees_committed_wal_from_writer_process(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ context = multiprocessing.get_context("spawn")
+ ready = context.Event()
+ release = context.Event()
+ process = context.Process(
+ target=_write_with_open_wal,
+ args=(str(database_path), ready, release),
+ )
+ process.start()
+ try:
+ assert ready.wait(timeout=10)
+ reader = AsyncTrajectoryReader(database_path)
+ items, cursor = await reader.list_traces("session-1", limit=30, cursor=None)
+ raw = await reader.get_raw_record("session-1", _TRACE_ID, _ROOT_SPAN_ID)
+
+ assert cursor is None
+ assert len(items) == 1
+ assert raw == _raw_record(_TRACE_ID, _ROOT_SPAN_ID)
+ finally:
+ release.set()
+ process.join(timeout=10)
+ if process.is_alive():
+ process.terminate()
+ process.join(timeout=5)
+
+ assert process.exitcode == 0
+ test_logger.info("Gateway read committed WAL data while the writer process remained open")
+
+
+async def test_malformed_raw_is_stored_and_exposed_without_projection(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ malformed_raw = b"{not-valid-json"
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records([_stored_record(raw_json=malformed_raw)])
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ detail = await reader.get_trace_records(
+ "session-1",
+ _TRACE_ID,
+ since_revision=0,
+ limit=1000,
+ )
+ raw = await reader.get_raw_record("session-1", _TRACE_ID, _ROOT_SPAN_ID)
+
+ assert detail is not None
+ assert detail["records"][0]["raw_valid"] is False
+ assert detail["records"][0]["otlp"] is None
+ assert raw == malformed_raw
+ test_logger.info("malformed JSON retained for raw diagnostics")
+
+
+async def test_reader_rejects_team_unknown_and_mixed_mode_traces(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ mixed_trace_id = "5" * 32
+ unknown_trace_id = "6" * 32
+ team_trace_id = "7" * 32
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ trace_id=mixed_trace_id,
+ span_id="1" * 16,
+ agent_mode="agent",
+ raw_json=_raw_record(mixed_trace_id, "1" * 16),
+ ),
+ _stored_record(
+ trace_id=mixed_trace_id,
+ span_id="2" * 16,
+ agent_mode="team.plan.normal",
+ raw_json=_raw_record(mixed_trace_id, "2" * 16),
+ ),
+ _stored_record(
+ trace_id=unknown_trace_id,
+ span_id="3" * 16,
+ agent_mode=None,
+ raw_json=_raw_record(unknown_trace_id, "3" * 16),
+ ),
+ _stored_record(
+ trace_id=team_trace_id,
+ span_id="4" * 16,
+ agent_mode="team",
+ raw_json=_raw_record(team_trace_id, "4" * 16),
+ ),
+ _stored_record(),
+ ]
+ )
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ items, _cursor = await reader.list_traces("session-1", limit=30, cursor=None)
+
+ assert [item["trace_id"] for item in items] == [_TRACE_ID]
+ for rejected_trace_id, span_id in (
+ (mixed_trace_id, "1" * 16),
+ (unknown_trace_id, "3" * 16),
+ (team_trace_id, "4" * 16),
+ ):
+ assert await reader.get_trace_records(
+ "session-1",
+ rejected_trace_id,
+ since_revision=0,
+ limit=1000,
+ ) is None
+ assert await reader.get_raw_record(
+ "session-1",
+ rejected_trace_id,
+ span_id,
+ ) is None
+ test_logger.info("trace-level mode allowlist rejected Team, unknown, and mixed scopes")
+
+
+async def test_detail_byte_budget_uses_index_descriptor_and_preserves_raw(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ first_raw = _raw_record(_TRACE_ID, _ROOT_SPAN_ID)
+ large_raw = _raw_record(_TRACE_ID, _CHILD_SPAN_ID).replace(
+ b'"attributes":[]',
+ b'"attributes":[{"key":"padding","value":{"stringValue":"'
+ + b"x" * 2048
+ + b'"}}]',
+ )
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(raw_json=first_raw),
+ _stored_record(
+ span_id=_CHILD_SPAN_ID,
+ parent_span_id=_ROOT_SPAN_ID,
+ raw_json=large_raw,
+ ),
+ ]
+ )
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ first_page = await reader.get_trace_records(
+ "session-1",
+ _TRACE_ID,
+ since_revision=0,
+ limit=1000,
+ max_bytes=len(first_raw) + 16,
+ )
+ assert first_page is not None
+ second_page = await reader.get_trace_records(
+ "session-1",
+ _TRACE_ID,
+ since_revision=first_page["next_since_revision"],
+ limit=1000,
+ max_bytes=len(first_raw) + 16,
+ )
+
+ assert first_page["has_more"] is True
+ assert len(first_page["records"]) == 1
+ assert first_page["projected_raw_bytes"] == len(first_raw)
+ assert second_page is not None
+ assert second_page["has_more"] is False
+ assert second_page["next_since_revision"] == second_page["revision"]
+ assert second_page["records"] == [
+ {
+ "ingest_seq": second_page["revision"],
+ "change_seq": second_page["revision"],
+ "record_id": f"{_TRACE_ID}:{_CHILD_SPAN_ID}",
+ "trace_id": _TRACE_ID,
+ "span_id": _CHILD_SPAN_ID,
+ "record_revision": 1,
+ "lifecycle": "final",
+ "operation": "upsert",
+ "observed_time_unix_nano": "200",
+ "raw_size_bytes": len(large_raw),
+ "otlp": None,
+ "raw_valid": None,
+ "projection_omitted": "record_too_large",
+ }
+ ]
+ assert await reader.get_raw_record(
+ "session-1",
+ _TRACE_ID,
+ _CHILD_SPAN_ID,
+ ) == large_raw
+ test_logger.info("oversize detail advanced by index while raw remained exact")
+
+
+async def test_detail_strict_json_rejects_non_otlp_and_non_finite_values(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ invalid_records = (
+ (_ROOT_SPAN_ID, b"NaN"),
+ (_CHILD_SPAN_ID, b"[]"),
+ (_THIRD_SPAN_ID, b'{"resourceSpans":NaN}'),
+ )
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(span_id=span_id, raw_json=raw_json)
+ for span_id, raw_json in invalid_records
+ ]
+ )
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ detail = await reader.get_trace_records(
+ "session-1",
+ _TRACE_ID,
+ since_revision=0,
+ limit=1000,
+ )
+
+ assert detail is not None
+ assert len(detail["records"]) == 3
+ assert all(record["otlp"] is None for record in detail["records"])
+ assert all(record["raw_valid"] is False for record in detail["records"])
+ test_logger.info("strict detail projection rejected NaN and non-OTLP JSON")
+
+
+async def test_trace_list_cursor_is_stable_when_root_arrives_late(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ oldest_trace_id = "8" * 32
+ middle_trace_id = "9" * 32
+ newest_trace_id = "a" * 32
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ trace_id=oldest_trace_id,
+ span_id="5" * 16,
+ start_time=50,
+ raw_json=_raw_record(oldest_trace_id, "5" * 16),
+ ),
+ _stored_record(
+ trace_id=middle_trace_id,
+ span_id="6" * 16,
+ parent_span_id="7" * 16,
+ start_time=100,
+ raw_json=_raw_record(middle_trace_id, "6" * 16),
+ ),
+ _stored_record(
+ trace_id=newest_trace_id,
+ span_id="8" * 16,
+ start_time=200,
+ raw_json=_raw_record(newest_trace_id, "8" * 16),
+ ),
+ ]
+ )
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ first_page, cursor = await reader.list_traces(
+ "session-1",
+ limit=2,
+ cursor=None,
+ )
+ assert [item["trace_id"] for item in first_page] == [
+ newest_trace_id,
+ middle_trace_id,
+ ]
+ assert cursor is not None
+
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ trace_id=middle_trace_id,
+ span_id="7" * 16,
+ start_time=10,
+ raw_json=_raw_record(middle_trace_id, "7" * 16),
+ )
+ ]
+ )
+ finally:
+ store.close()
+
+ second_page, final_cursor = await reader.list_traces(
+ "session-1",
+ limit=2,
+ cursor=cursor,
+ )
+ assert [item["trace_id"] for item in second_page] == [oldest_trace_id]
+ assert final_cursor is None
+ test_logger.info("late root did not move a trace across the list cursor")
+
+
+ ("new_trace_count", "expected_page_sizes"),
+ [
+ (31, [30, 2]),
+ (61, [30, 30, 2]),
+ ],
+)
+async def test_revision_feed_pages_new_traces_and_late_old_revision(
+ tmp_path: Path,
+ new_trace_count: int,
+ expected_page_sizes: list[int],
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records([_stored_record()])
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ initial_items, _list_cursor, revision_cursor, store_epoch = (
+ await reader.list_traces_with_revision_cursor(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+ )
+ initial_revision = initial_items[0]["revision"]
+
+ new_trace_ids = [f"{1000 + index:032x}" for index in range(new_trace_count)]
+ new_records = [
+ _stored_record(
+ trace_id=trace_id,
+ span_id=f"{1000 + index:016x}",
+ start_time=1000 + index,
+ end_time=2000 + index,
+ raw_json=_raw_record(trace_id, f"{1000 + index:016x}"),
+ )
+ for index, trace_id in enumerate(new_trace_ids)
+ ]
+ late_span_id = "f" * 16
+ new_records.append(
+ _stored_record(
+ span_id=late_span_id,
+ parent_span_id=_ROOT_SPAN_ID,
+ start_time=300,
+ end_time=400,
+ raw_json=_raw_record(
+ _TRACE_ID,
+ late_span_id,
+ parent_span_id=_ROOT_SPAN_ID,
+ ),
+ )
+ )
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(new_records)
+ finally:
+ store.close()
+
+ cursor = revision_cursor
+ page_sizes: list[int] = []
+ watermarks: set[str] = set()
+ summaries_by_trace_id: dict[str, dict[str, Any]] = {}
+ while True:
+ (
+ items,
+ next_cursor,
+ watermark,
+ has_more,
+ reset,
+ revision_epoch,
+ ) = await reader.list_trace_revisions(
+ "session-1", after_revision=cursor, limit=30
+ )
+ page_sizes.append(len(items))
+ watermarks.add(watermark)
+ assert reset is False
+ assert revision_epoch == store_epoch
+ for item in items:
+ summaries_by_trace_id[item["trace_id"]] = item
+ assert next_cursor
+ if not has_more:
+ assert next_cursor == watermark
+ cursor = next_cursor
+ break
+ assert next_cursor != cursor
+ cursor = next_cursor
+
+ assert page_sizes == expected_page_sizes
+ assert len(watermarks) == 1
+ assert set(new_trace_ids).issubset(summaries_by_trace_id)
+ assert summaries_by_trace_id[_TRACE_ID]["span_count"] == 2
+ assert summaries_by_trace_id[_TRACE_ID]["revision"] > initial_revision
+
+ unchanged, stable_cursor, stable_watermark, has_more, reset, revision_epoch = (
+ await reader.list_trace_revisions(
+ "session-1",
+ after_revision=cursor,
+ limit=30,
+ )
+ )
+ assert unchanged == []
+ assert stable_cursor == cursor
+ assert stable_watermark == cursor
+ assert has_more is False
+ assert reset is False
+ assert revision_epoch == store_epoch
+ test_logger.info(
+ "revision feed found %d new traces and one late old-trace revision",
+ new_trace_count,
+ )
+
+
+async def test_revision_feed_continuation_keeps_first_page_watermark(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records([_stored_record()])
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ _items, _list_cursor, baseline, store_epoch = (
+ await reader.list_traces_with_revision_cursor(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+ )
+ first_batch_trace_ids = [f"{2000 + index:032x}" for index in range(2)]
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ trace_id=trace_id,
+ span_id=f"{2000 + index:016x}",
+ raw_json=_raw_record(trace_id, f"{2000 + index:016x}"),
+ )
+ for index, trace_id in enumerate(first_batch_trace_ids)
+ ]
+ )
+ finally:
+ store.close()
+
+ (
+ first_items,
+ continuation,
+ watermark,
+ has_more,
+ reset,
+ revision_epoch,
+ ) = await reader.list_trace_revisions(
+ "session-1", after_revision=baseline, limit=1
+ )
+ assert has_more is True
+ assert reset is False
+ assert revision_epoch == store_epoch
+
+ later_trace_id = "e" * 32
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ trace_id=later_trace_id,
+ span_id="e" * 16,
+ raw_json=_raw_record(later_trace_id, "e" * 16),
+ )
+ ]
+ )
+ finally:
+ store.close()
+
+ (
+ second_items,
+ completed_cursor,
+ repeated_watermark,
+ has_more,
+ reset,
+ revision_epoch,
+ ) = (
+ await reader.list_trace_revisions(
+ "session-1",
+ after_revision=continuation,
+ limit=1,
+ )
+ )
+ assert has_more is False
+ assert reset is False
+ assert revision_epoch == store_epoch
+ assert completed_cursor == watermark
+ assert repeated_watermark == watermark
+ assert {item["trace_id"] for item in [*first_items, *second_items]} == set(
+ first_batch_trace_ids
+ )
+
+ (
+ next_items,
+ next_cursor,
+ next_watermark,
+ has_more,
+ reset,
+ revision_epoch,
+ ) = await reader.list_trace_revisions(
+ "session-1", after_revision=completed_cursor, limit=1
+ )
+ assert [item["trace_id"] for item in next_items] == [later_trace_id]
+ assert next_cursor == next_watermark
+ assert has_more is False
+ assert reset is False
+ assert revision_epoch == store_epoch
+ test_logger.info("revision pagination deferred concurrent commits to the next poll")
+
+
+async def test_store_epoch_persists_and_database_replacement_resets_cursor(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ backup_path = tmp_path / "trajectory-backup.sqlite3"
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ first_epoch = store.fetch_store_epoch()
+ store.write_records([_stored_record()])
+ assert store.fetch_store_epoch() == first_epoch
+ finally:
+ store.close()
+
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ assert store.fetch_store_epoch() == first_epoch
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ _items, _list_cursor, old_cursor, reader_epoch = (
+ await reader.list_traces_with_revision_cursor(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+ )
+ assert reader_epoch == first_epoch
+
+ database_path.replace(backup_path)
+ replacement_store = TrajectoryStore(database_path)
+ replacement_store.initialize()
+ try:
+ replacement_epoch = replacement_store.fetch_store_epoch()
+ finally:
+ replacement_store.close()
+
+ assert replacement_epoch != first_epoch
+ items, cursor, watermark, has_more, reset, current_epoch = (
+ await reader.list_trace_revisions(
+ "session-1",
+ after_revision=old_cursor,
+ limit=30,
+ )
+ )
+ assert items == []
+ assert cursor == watermark
+ assert has_more is False
+ assert reset is True
+ assert current_epoch == replacement_epoch
+ assert decode_revision_cursor(cursor) == (
+ "session-1",
+ replacement_epoch,
+ 0,
+ None,
+ )
+ test_logger.info("database replacement minted a new persistent epoch and reset")
+
+
+async def test_ingest_sequence_rollback_rotates_epoch_and_resets_cursor(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(),
+ _stored_record(
+ span_id=_CHILD_SPAN_ID,
+ raw_json=_raw_record(_TRACE_ID, _CHILD_SPAN_ID),
+ ),
+ ]
+ )
+ old_epoch = store.fetch_store_epoch()
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ _items, _list_cursor, old_cursor, listed_epoch = (
+ await reader.list_traces_with_revision_cursor(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+ )
+ assert listed_epoch == old_epoch
+
+ rollback_connection = sqlite3.connect(str(database_path))
+ try:
+ rollback_connection.execute(
+ "DELETE FROM otlp_span_records WHERE ingest_seq = 2"
+ )
+ rollback_connection.commit()
+ finally:
+ rollback_connection.close()
+
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ new_epoch = store.fetch_store_epoch()
+ finally:
+ store.close()
+
+ assert new_epoch != old_epoch
+ revisions = await reader.list_trace_revisions(
+ "session-1",
+ after_revision=old_cursor,
+ limit=30,
+ )
+ assert revisions[0] == []
+ assert revisions[4] is True
+ assert revisions[5] == new_epoch
+ assert decode_revision_cursor(revisions[1]) == (
+ "session-1",
+ new_epoch,
+ 1,
+ None,
+ )
+ test_logger.info("ingest sequence rollback minted a new epoch and reset")
+
+
+async def test_retention_deletion_rotates_epoch_and_resets_revision_feed(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ expired_record = TraceRecordData.from_core_record(_core_record(), created_at=1)
+ store = TrajectoryStore(database_path, retention_days=1)
+ store.initialize()
+ try:
+ store.write_records([expired_record])
+ old_epoch = store.fetch_store_epoch()
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ _items, _list_cursor, old_cursor, listed_epoch = (
+ await reader.list_traces_with_revision_cursor(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+ )
+ assert listed_epoch == old_epoch
+
+ store = TrajectoryStore(database_path, retention_days=1)
+ store.initialize()
+ try:
+ assert store.delete_expired(now=86402) == 1
+ new_epoch = store.fetch_store_epoch()
+ finally:
+ store.close()
+
+ assert new_epoch != old_epoch
+ items, cursor, watermark, has_more, reset, current_epoch = (
+ await reader.list_trace_revisions(
+ "session-1",
+ after_revision=old_cursor,
+ limit=30,
+ )
+ )
+ assert items == []
+ assert cursor == watermark
+ assert has_more is False
+ assert reset is True
+ assert current_epoch == new_epoch
+ assert decode_revision_cursor(cursor)[2:] == (0, None)
+ test_logger.info("retention deletion rotated epoch before returning an empty view")
+
+
+async def test_partial_retention_rotates_epoch_and_rebuilds_remaining_view(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ expired = TraceRecordData.from_core_record(_core_record(), created_at=1)
+ retained = TraceRecordData.from_core_record(
+ _core_record(
+ span_id=_CHILD_SPAN_ID,
+ raw_json=_raw_record(_TRACE_ID, _CHILD_SPAN_ID),
+ ),
+ created_at=100,
+ )
+ store = TrajectoryStore(database_path, retention_days=1)
+ store.initialize()
+ try:
+ store.write_records([expired, retained])
+ old_epoch = store.fetch_store_epoch()
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ _items, _list_cursor, old_cursor, _listed_epoch = (
+ await reader.list_traces_with_revision_cursor(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+ )
+
+ store = TrajectoryStore(database_path, retention_days=1)
+ store.initialize()
+ try:
+ assert store.delete_expired(now=86402) == 1
+ new_epoch = store.fetch_store_epoch()
+ finally:
+ store.close()
+
+ assert new_epoch != old_epoch
+ revisions = await reader.list_trace_revisions(
+ "session-1",
+ after_revision=old_cursor,
+ limit=30,
+ )
+ assert revisions[0] == []
+ assert revisions[4] is True
+ assert revisions[5] == new_epoch
+ remaining, _cursor = await reader.list_traces(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+ assert len(remaining) == 1
+ assert remaining[0]["span_count"] == 1
+ assert remaining[0]["revision"] == 2
+ test_logger.info("partial retention forced a full rebuild of the remaining view")
+
+
+async def test_global_trace_eligibility_fails_closed_across_sessions(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records([_stored_record()])
+ old_epoch = store.fetch_store_epoch()
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ _items, _list_cursor, old_cursor, _listed_epoch = (
+ await reader.list_traces_with_revision_cursor(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+ )
+
+ team_span_id = "d" * 16
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ span_id=team_span_id,
+ session_id="session-2",
+ agent_mode="team.plan.normal",
+ raw_json=_raw_record(_TRACE_ID, team_span_id),
+ )
+ ]
+ )
+ new_epoch = store.fetch_store_epoch()
+ finally:
+ store.close()
+
+ assert new_epoch != old_epoch
+ session_one_items, _cursor = await reader.list_traces(
+ "session-1", limit=30, cursor=None
+ )
+ session_two_items, _cursor = await reader.list_traces(
+ "session-2", limit=30, cursor=None
+ )
+ assert session_one_items == []
+ assert session_two_items == []
+ assert await reader.get_trace_records(
+ "session-1", _TRACE_ID, since_revision=0, limit=100
+ ) is None
+ assert await reader.get_raw_record(
+ "session-1", _TRACE_ID, _ROOT_SPAN_ID
+ ) is None
+ assert await reader.get_raw_record(
+ "session-2", _TRACE_ID, team_span_id
+ ) is None
+
+ revisions = await reader.list_trace_revisions(
+ "session-1",
+ after_revision=old_cursor,
+ limit=30,
+ )
+ assert revisions[0] == []
+ assert revisions[4] is True
+ assert revisions[5] == new_epoch
+ test_logger.info("one Team span hid a reused trace ID in every session")
+
+
+async def test_global_eligibility_keeps_record_paths_session_isolated(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ shared_trace_id = "3" * 32
+ first_span_id = "3" * 16
+ second_span_id = "4" * 16
+ first_raw = _raw_record(shared_trace_id, first_span_id)
+ second_raw = _raw_record(shared_trace_id, second_span_id)
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ trace_id=shared_trace_id,
+ span_id=first_span_id,
+ session_id="session-1",
+ raw_json=first_raw,
+ ),
+ _stored_record(
+ trace_id=shared_trace_id,
+ span_id=second_span_id,
+ session_id="session-2",
+ raw_json=second_raw,
+ ),
+ ]
+ )
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ first_items, _cursor = await reader.list_traces(
+ "session-1", limit=30, cursor=None
+ )
+ second_items, _cursor = await reader.list_traces(
+ "session-2", limit=30, cursor=None
+ )
+ assert first_items[0]["span_count"] == 1
+ assert second_items[0]["span_count"] == 1
+ assert await reader.get_raw_record(
+ "session-1", shared_trace_id, first_span_id
+ ) == first_raw
+ assert await reader.get_raw_record(
+ "session-1", shared_trace_id, second_span_id
+ ) is None
+ assert await reader.get_raw_record(
+ "session-2", shared_trace_id, first_span_id
+ ) is None
+ assert await reader.get_raw_record(
+ "session-2", shared_trace_id, second_span_id
+ ) == second_raw
+ test_logger.info("global eligibility did not broaden session-scoped record paths")
+
+
+async def test_reverse_eligibility_change_rotates_epoch(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ unknown_span_id = "5" * 16
+ known_span_id = "6" * 16
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ span_id=unknown_span_id,
+ agent_mode=None,
+ raw_json=_raw_record(_TRACE_ID, unknown_span_id),
+ )
+ ]
+ )
+ old_epoch = store.fetch_store_epoch()
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ items, _list_cursor, old_cursor, listed_epoch = (
+ await reader.list_traces_with_revision_cursor(
+ "session-1",
+ limit=30,
+ cursor=None,
+ )
+ )
+ assert items == []
+ assert listed_epoch == old_epoch
+
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ span_id=known_span_id,
+ agent_mode="agent",
+ raw_json=_raw_record(_TRACE_ID, known_span_id),
+ )
+ ]
+ )
+ new_epoch = store.fetch_store_epoch()
+ finally:
+ store.close()
+
+ assert new_epoch != old_epoch
+ visible_items, _cursor = await reader.list_traces(
+ "session-1", limit=30, cursor=None
+ )
+ assert visible_items[0]["span_count"] == 2
+ revisions = await reader.list_trace_revisions(
+ "session-1", after_revision=old_cursor, limit=30
+ )
+ assert revisions[4] is True
+ assert revisions[5] == new_epoch
+ test_logger.info("ineligible-to-eligible reconciliation rotated the store epoch")
+
+
+async def test_raw_first_mixed_batch_preserves_unprojectable_blobs(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ deep_raw = b'{"resourceSpans":' + b"[" * 2000 + b"]" * 2000 + b"}"
+ long_integer_raw = (
+ b'{"resourceSpans":[],"value":' + b"9" * 10000 + b"}"
+ )
+ invalid_utf8_raw = b'{"resourceSpans":[],"value":"\xff"}'
+ valid_raw = _raw_record(_TRACE_ID, _ROOT_SPAN_ID)
+ raw_by_span_id = {
+ _ROOT_SPAN_ID: valid_raw,
+ _CHILD_SPAN_ID: deep_raw,
+ _THIRD_SPAN_ID: long_integer_raw,
+ "d" * 16: invalid_utf8_raw,
+ }
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ result = store.write_records(
+ [
+ _stored_record(span_id=span_id, raw_json=raw_json)
+ for span_id, raw_json in raw_by_span_id.items()
+ ]
+ )
+ assert result.inserted == len(raw_by_span_id)
+ for span_id, raw_json in raw_by_span_id.items():
+ assert store.fetch_raw(_TRACE_ID, span_id) == raw_json
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ detail = await reader.get_trace_records(
+ "session-1",
+ _TRACE_ID,
+ since_revision=0,
+ limit=100,
+ )
+ assert detail is not None
+ projected_by_span_id = {
+ str(record["span_id"]): record for record in detail["records"]
+ }
+ assert projected_by_span_id[_ROOT_SPAN_ID]["raw_valid"] is True
+ for span_id in (_CHILD_SPAN_ID, _THIRD_SPAN_ID, "d" * 16):
+ assert projected_by_span_id[span_id]["raw_valid"] is False
+ assert await reader.get_raw_record(
+ "session-1", _TRACE_ID, span_id
+ ) == raw_by_span_id[span_id]
+ test_logger.info("deep, huge-integer, and invalid-UTF8 blobs survived one batch")
+
+
+async def test_cursor_scope_range_and_canonical_encoding(tmp_path: Path) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(),
+ _stored_record(
+ trace_id=_SECOND_TRACE_ID,
+ span_id=_CHILD_SPAN_ID,
+ raw_json=_raw_record(_SECOND_TRACE_ID, _CHILD_SPAN_ID),
+ ),
+ ]
+ )
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ _items, list_cursor, revision_cursor, store_epoch = (
+ await reader.list_traces_with_revision_cursor(
+ "session-1",
+ limit=1,
+ cursor=None,
+ )
+ )
+ assert list_cursor is not None
+ decoded_list_cursor = decode_trace_cursor(list_cursor)
+ assert decoded_list_cursor[:2] == ("session-1", store_epoch)
+ assert decode_revision_cursor(revision_cursor)[:2] == (
+ "session-1",
+ store_epoch,
+ )
+
+ for invalid_cursor in (
+ f"{revision_cursor}!!!",
+ f"{revision_cursor}=",
+ f" {revision_cursor}",
+ _opaque_cursor(
+ {
+ "v": 2,
+ "s": "session-1",
+ "e": store_epoch,
+ "a": str(1 << 63),
+ }
+ ),
+ _opaque_cursor(
+ {
+ "v": 2,
+ "s": "session-1",
+ "e": store_epoch,
+ "a": "01",
+ }
+ ),
+ ):
+ with pytest.raises(TrajectoryCursorError):
+ decode_revision_cursor(invalid_cursor)
+
+ for invalid_cursor in (
+ f"{list_cursor}!!!",
+ f"{list_cursor}=",
+ f"{list_cursor} ",
+ ):
+ with pytest.raises(TrajectoryCursorError):
+ decode_trace_cursor(invalid_cursor)
+
+ with pytest.raises(TrajectoryCursorError):
+ encode_revision_cursor("session-1", store_epoch, 1 << 63)
+ with pytest.raises(TrajectoryCursorError):
+ encode_trace_cursor("session-1", store_epoch, 1 << 63, _TRACE_ID)
+ with pytest.raises(TrajectoryCursorError):
+ await reader.list_traces(
+ "session-2",
+ limit=1,
+ cursor=list_cursor,
+ )
+ with pytest.raises(TrajectoryCursorError):
+ await reader.list_traces(
+ "session-1",
+ limit=1,
+ cursor=encode_trace_cursor(
+ "session-1",
+ store_epoch,
+ (1 << 63) - 1,
+ _TRACE_ID,
+ ),
+ )
+
+ for stale_cursor in (
+ encode_revision_cursor("session-2", store_epoch, 0),
+ encode_revision_cursor("session-1", "stale-epoch", 0),
+ encode_revision_cursor("session-1", store_epoch, (1 << 63) - 1),
+ ):
+ revisions = await reader.list_trace_revisions(
+ "session-1",
+ after_revision=stale_cursor,
+ limit=30,
+ )
+ assert revisions[0] == []
+ assert revisions[4] is True
+ assert revisions[5] == store_epoch
+ test_logger.info("cursor scope, signed range, and canonical base64url were enforced")
+
+
+async def test_revision_summary_is_frozen_at_first_page_watermark(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "trajectory.sqlite3"
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records([_stored_record()])
+ finally:
+ store.close()
+
+ reader = AsyncTrajectoryReader(database_path)
+ _items, _list_cursor, baseline, store_epoch = (
+ await reader.list_traces_with_revision_cursor(
+ "session-1", limit=30, cursor=None
+ )
+ )
+ first_trace_id = "8" * 32
+ second_trace_id = "9" * 32
+ first_span_id = "8" * 16
+ second_span_id = "9" * 16
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ trace_id=first_trace_id,
+ span_id=first_span_id,
+ start_time=300,
+ end_time=400,
+ raw_json=_raw_record(first_trace_id, first_span_id),
+ ),
+ _stored_record(
+ trace_id=second_trace_id,
+ span_id=second_span_id,
+ start_time=500,
+ end_time=600,
+ raw_json=_raw_record(second_trace_id, second_span_id),
+ ),
+ ]
+ )
+ finally:
+ store.close()
+
+ first_page = await reader.list_trace_revisions(
+ "session-1", after_revision=baseline, limit=1
+ )
+ assert [item["trace_id"] for item in first_page[0]] == [first_trace_id]
+ assert first_page[3] is True
+ assert first_page[4] is False
+
+ late_span_id = "a" * 16
+ error_raw = _raw_record(
+ second_trace_id,
+ late_span_id,
+ status_code="STATUS_CODE_ERROR",
+ )
+ store = TrajectoryStore(database_path)
+ store.initialize()
+ try:
+ store.write_records(
+ [
+ _stored_record(
+ trace_id=second_trace_id,
+ span_id=late_span_id,
+ request_id="zz-request",
+ run_id="zz-run",
+ start_time=900,
+ end_time=1000,
+ raw_json=error_raw,
+ )
+ ]
+ )
+ assert store.fetch_store_epoch() == store_epoch
+ finally:
+ store.close()
+
+ second_page = await reader.list_trace_revisions(
+ "session-1",
+ after_revision=first_page[1],
+ limit=1,
+ )
+ assert second_page[3] is False
+ assert second_page[4] is False
+ assert second_page[2] == first_page[2]
+ frozen_summary = second_page[0][0]
+ assert frozen_summary["trace_id"] == second_trace_id
+ assert frozen_summary["span_count"] == 1
+ assert frozen_summary["end_time_unix_nano"] == 600
+ assert frozen_summary["request_id"] == "request-1"
+ assert frozen_summary["has_error"] is False
+
+ next_poll = await reader.list_trace_revisions(
+ "session-1",
+ after_revision=second_page[1],
+ limit=1,
+ )
+ updated_summary = next_poll[0][0]
+ assert updated_summary["trace_id"] == second_trace_id
+ assert updated_summary["span_count"] == 2
+ assert updated_summary["end_time_unix_nano"] == 1000
+ assert updated_summary["request_id"] == "zz-request"
+ assert updated_summary["run_id"] == "zz-run"
+ assert updated_summary["has_error"] is True
+ test_logger.info("revision summary aggregation stayed below the frozen watermark")
diff --git a/tests/unit_tests/observability/test_trajectory_config.py b/tests/unit_tests/observability/test_trajectory_config.py
new file mode 100644
index 0000000000..7007130b01
--- /dev/null
+++ b/tests/unit_tests/observability/test_trajectory_config.py
@@ -0,0 +1,53 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tests for trajectory store configuration resolution."""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+
+from jiuwenswarm.observability.config import (
+ DEFAULT_QUEUE_SIZE,
+ TrajectoryStoreSettings,
+ load_trajectory_store_settings,
+)
+
+test_logger = logging.getLogger("tests.trajectory_config")
+
+
+def test_config_defaults_keep_legacy_installations_disabled(tmp_path: Path) -> None:
+ settings = load_trajectory_store_settings({}, workspace=tmp_path)
+
+ assert settings == TrajectoryStoreSettings(
+ enabled=False,
+ database_path=tmp_path / ".trace" / "trajectory.sqlite3",
+ retention_days=7,
+ queue_size=4096,
+ batch_size=64,
+ flush_interval_ms=200,
+ poll_interval_ms=2000,
+ )
+ test_logger.info("legacy configs require the packaged explicit trajectory opt-in")
+
+
+def test_config_resolves_relative_path_and_rejects_non_positive_limits(
+ tmp_path: Path,
+) -> None:
+ settings = load_trajectory_store_settings(
+ {
+ "trajectory_ui": {
+ "enabled": "false",
+ "db_path": "custom/trajectory.sqlite3",
+ "queue_size": 0,
+ "batch_size": 12,
+ }
+ },
+ workspace=tmp_path,
+ )
+
+ assert settings.enabled is False
+ assert settings.database_path == tmp_path / "custom" / "trajectory.sqlite3"
+ assert settings.queue_size == DEFAULT_QUEUE_SIZE
+ assert settings.batch_size == 12
+ test_logger.info("trajectory config normalized paths and unsafe limits")
diff --git a/tests/unit_tests/observability/test_trajectory_runtime.py b/tests/unit_tests/observability/test_trajectory_runtime.py
new file mode 100644
index 0000000000..934a227a3a
--- /dev/null
+++ b/tests/unit_tests/observability/test_trajectory_runtime.py
@@ -0,0 +1,207 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tests for the process-wide Core consumer registration lifecycle."""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import replace
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jiuwenswarm.observability.config import TrajectoryStoreSettings
+from jiuwenswarm.observability import runtime
+
+test_logger = logging.getLogger("tests.trajectory_runtime")
+
+
+class _FakeSink:
+ def __init__(self, events: list[str]) -> None:
+ self.events = events
+ self.callback: Any = None
+
+ def start(self) -> None:
+ self.events.append("sink.start")
+
+ def set_commit_callback(self, callback: Any) -> None:
+ self.callback = callback
+
+ def close(self, *, timeout: float = 15.0) -> bool:
+ self.events.append("sink.close")
+ return True
+
+
+class _FakeProcessor:
+ def __init__(self, events: list[str]) -> None:
+ self.events = events
+ self.consumers: list[object] = []
+
+ def register_consumer(self, consumer: object) -> None:
+ self.events.append("processor.register")
+ if all(existing is not consumer for existing in self.consumers):
+ self.consumers.append(consumer)
+
+ def unregister_consumer(self, consumer: object) -> None:
+ self.events.append("processor.unregister")
+ self.consumers = [existing for existing in self.consumers if existing is not consumer]
+
+
+class _FailingOnceProcessor(_FakeProcessor):
+ def __init__(self, events: list[str]) -> None:
+ super().__init__(events)
+ self.fail_unregister = True
+
+ def unregister_consumer(self, consumer: object) -> None:
+ self.events.append("processor.unregister")
+ if self.fail_unregister:
+ raise RuntimeError("injected unregister failure")
+ self.consumers = [existing for existing in self.consumers if existing is not consumer]
+
+
+def _settings(database_path: Path) -> TrajectoryStoreSettings:
+ return TrajectoryStoreSettings(
+ enabled=True,
+ database_path=database_path,
+ retention_days=7,
+ queue_size=16,
+ batch_size=8,
+ flush_interval_ms=20,
+ poll_interval_ms=2000,
+ )
+
+
+def test_runtime_registers_once_and_unregisters_before_drain(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ runtime.shutdown_trajectory_runtime()
+ events: list[str] = []
+ fake_sink = _FakeSink(events)
+ fake_processor = _FakeProcessor(events)
+
+ def _create_sink(
+ settings: TrajectoryStoreSettings,
+ *,
+ on_commit: Any,
+ ) -> _FakeSink:
+ fake_sink.callback = on_commit
+ return fake_sink
+
+ monkeypatch.setattr(runtime, "_create_sink", _create_sink)
+ monkeypatch.setattr(
+ runtime,
+ "_get_core_span_record_processor",
+ lambda: fake_processor,
+ )
+ callback = lambda _updates: None
+
+ try:
+ first = runtime.start_trajectory_runtime(
+ _settings(tmp_path / "trajectory.sqlite3"),
+ on_commit=callback,
+ )
+ second = runtime.start_trajectory_runtime(
+ _settings(tmp_path / "trajectory.sqlite3"),
+ on_commit=callback,
+ )
+
+ assert first is fake_sink
+ assert second is fake_sink
+ assert fake_processor.consumers == [fake_sink]
+ assert events == ["sink.start", "processor.register"]
+ assert runtime.shutdown_trajectory_runtime() is True
+ assert events == [
+ "sink.start",
+ "processor.register",
+ "processor.unregister",
+ "sink.close",
+ ]
+ assert runtime.get_trajectory_runtime_sink() is None
+ finally:
+ runtime.shutdown_trajectory_runtime()
+ test_logger.info("runtime registration was idempotent and shutdown order was safe")
+
+
+def test_disabled_sync_stops_existing_runtime(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ runtime.shutdown_trajectory_runtime()
+ events: list[str] = []
+ fake_sink = _FakeSink(events)
+ fake_processor = _FakeProcessor(events)
+ settings = _settings(tmp_path / "trajectory.sqlite3")
+
+ monkeypatch.setattr(
+ runtime,
+ "_create_sink",
+ lambda _settings, on_commit: fake_sink,
+ )
+ monkeypatch.setattr(
+ runtime,
+ "_get_core_span_record_processor",
+ lambda: fake_processor,
+ )
+
+ try:
+ assert runtime.sync_trajectory_runtime(settings) is fake_sink
+ assert runtime.sync_trajectory_runtime(replace(settings, enabled=False)) is None
+ assert events == [
+ "sink.start",
+ "processor.register",
+ "processor.unregister",
+ "sink.close",
+ ]
+ finally:
+ runtime.shutdown_trajectory_runtime()
+ test_logger.info("disabled configuration stopped and drained the active runtime")
+
+
+def test_unregister_failure_keeps_running_sink_for_later_retry(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ runtime.shutdown_trajectory_runtime()
+ events: list[str] = []
+ fake_sink = _FakeSink(events)
+ fake_processor = _FailingOnceProcessor(events)
+ settings = _settings(tmp_path / "trajectory.sqlite3")
+
+ monkeypatch.setattr(
+ runtime,
+ "_create_sink",
+ lambda _settings, on_commit: fake_sink,
+ )
+ monkeypatch.setattr(
+ runtime,
+ "_get_core_span_record_processor",
+ lambda: fake_processor,
+ )
+
+ try:
+ assert runtime.start_trajectory_runtime(settings) is fake_sink
+ assert runtime.shutdown_trajectory_runtime(timeout=3) is False
+ assert runtime.get_trajectory_runtime_sink() is fake_sink
+ assert fake_processor.consumers == [fake_sink]
+ assert events == [
+ "sink.start",
+ "processor.register",
+ "processor.unregister",
+ ]
+
+ fake_processor.fail_unregister = False
+ assert runtime.shutdown_trajectory_runtime(timeout=3) is True
+ assert runtime.get_trajectory_runtime_sink() is None
+ assert events == [
+ "sink.start",
+ "processor.register",
+ "processor.unregister",
+ "processor.unregister",
+ "sink.close",
+ ]
+ finally:
+ fake_processor.fail_unregister = False
+ runtime.shutdown_trajectory_runtime()
+ test_logger.info("unregister failure left the running singleton available for retry")
diff --git a/tests/unit_tests/observability/test_trajectory_updates.py b/tests/unit_tests/observability/test_trajectory_updates.py
new file mode 100644
index 0000000000..31e5122ce0
--- /dev/null
+++ b/tests/unit_tests/observability/test_trajectory_updates.py
@@ -0,0 +1,91 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Tests for committed trajectory update hint fan-out."""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+
+import pytest
+
+from jiuwenswarm.gateway.channel_manager.web.web_connect import WebChannel
+from jiuwenswarm.observability.models import CommittedTraceUpdate
+from jiuwenswarm.observability.updates import TrajectoryUpdateBroker
+
+test_logger = logging.getLogger("tests.trajectory_updates")
+
+
+@dataclass(frozen=True)
+class _RoutingKey:
+ session_id: str
+
+
+class _WebSocket:
+ closed = False
+
+
+def test_update_broker_isolates_listeners_and_unregisters() -> None:
+ broker = TrajectoryUpdateBroker()
+ received: list[tuple[CommittedTraceUpdate, ...]] = []
+
+ def _failing(_updates: tuple[CommittedTraceUpdate, ...]) -> None:
+ raise RuntimeError("injected listener failure")
+
+ received_listener = received.append
+ broker.register(_failing)
+ broker.register(received_listener)
+ updates = (
+ CommittedTraceUpdate(
+ session_id="session-1",
+ trace_id="1" * 32,
+ revision=7,
+ store_epoch="epoch-1",
+ lifecycle="running",
+ ),
+ )
+
+ broker.publish(updates)
+ broker.unregister(received_listener)
+ broker.publish(updates)
+
+ assert received == [updates]
+ test_logger.info("commit hint listener failures stayed isolated")
+
+
+async def test_webchannel_routes_trace_update_to_matching_session_only() -> None:
+ channel = WebChannel.__new__(WebChannel)
+ first_ws = _WebSocket()
+ other_ws = _WebSocket()
+ channel._clients_by_key = {
+ _RoutingKey(session_id="session-1"): [first_ws],
+ _RoutingKey(session_id="session-2"): [other_ws],
+ }
+ sent: list[tuple[object, str, dict[str, object]]] = []
+
+ async def _send_event(ws, event, payload) -> None:
+ sent.append((ws, event, payload))
+
+ channel.send_event = _send_event
+ update = CommittedTraceUpdate(
+ session_id="session-1",
+ trace_id="2" * 32,
+ revision=9,
+ store_epoch="epoch-2",
+ lifecycle="final",
+ )
+
+ await channel._send_trajectory_updates((update,))
+
+ assert len(sent) == 1
+ assert sent[0][0] is first_ws
+ assert sent[0][1] == "trace.updated"
+ assert sent[0][2] == {
+ "session_id": "session-1",
+ "trace_id": "2" * 32,
+ "revision": 9,
+ "store_epoch": "epoch-2",
+ "lifecycle": "final",
+ }
+ test_logger.info("trace update hint stayed scoped to its session")