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(trajectory): add token-cost timeline view
alan_chengcacd24d0e3ef
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex a2fb75b032..d90876b424 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -40,6 +40,8 @@"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-timeline": "esbuild src/features/trajectory/trajectory/timeline.ts --bundle --packages=external --platform=node --format=esm --outfile=node_modules/.cache/trajectory-timeline/timeline.mjs && node --test tests/trajectoryTimeline.test.mjs",+ "test:trajectory-preview": "esbuild src/features/trajectory/trajectory/preview.ts --bundle --packages=external --platform=node --format=esm --outfile=node_modules/.cache/trajectory-preview/preview.mjs && node --test tests/trajectoryPreview.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",diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.tsxindex c969d24ee5..7840b4801c 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/TrajectoryPanel.tsx@@ -255,6 +255,8 @@ export const TrajectoryPanel = memo(function TrajectoryPanel({'toolbar.useActualDuration': '使用实际时长','toolbar.useEqualWidth': '使用等宽操作','toolbar.actualTime': '实际时间',+ 'toolbar.tokens': 'Tokens',+ 'toolbar.useTokenCost': '按 token 开销显示','toolbar.turns': '轮次','toolbar.expandTurns': '展开所有轮次','toolbar.collapseTurns': '折叠所有轮次',diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.tsxindex d5f140b8ed..a53923689b 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryExplorer.tsx@@ -10,6 +10,7 @@ import type {} from '../trajectory/model.ts'import { trajectoryRecordId } from '../trajectory/record.ts'import {+ resolveTimelineMode,trajectoryTimelineFocusIndexes,type TrajectoryTimelineMode,type TrajectoryTimeRange,@@ -140,6 +141,7 @@ export const TrajectoryExplorer = memo(function TrajectoryExplorer({}, [active, hasRunningCells])const [actualDuration, setActualDuration] = useState(false)const [actualTime, setActualTime] = useState(false)+ const [tokenView, setTokenView] = useState(false)const [collapsedTurns, setCollapsedTurns] = useState<ReadonlySet<number>>(EMPTY_TURN_IDS)const [collapsedAssistants, setCollapsedAssistants] =useState<ReadonlySet<string>>(EMPTY_RECORD_IDS)@@ -164,9 +166,11 @@ export const TrajectoryExplorer = memo(function TrajectoryExplorer({() => translate ?? trajectoryTranslator(messages),[messages, translate],)- const timelineMode: TrajectoryTimelineMode = actualDuration- ? actualTime ? 'actual' : 'duration'- : actualTime ? 'time' : 'sequence'+ const timelineMode: TrajectoryTimelineMode = resolveTimelineMode({+ tokenView,+ actualDuration,+ actualTime,+ })const searchMatchIndexes = useMemo(() => searchIndexes(searchIndex, turns, searchQuery),[searchIndex, searchQuery, turns],@@ -259,9 +263,15 @@ export const TrajectoryExplorer = memo(function TrajectoryExplorer({><TrajectoryToolbaractualDuration={actualDuration}- onActualDurationChange={(value) => { setActualDuration(value); setTimelineRange(null) }}+ onActualDurationChange={(value) => {+ setActualDuration(value)+ setTokenView(false)+ setTimelineRange(null)+ }}actualTime={actualTime}onActualTimeChange={(value) => { setActualTime(value); setTimelineRange(null) }}+ tokenView={tokenView}+ onTokenViewChange={(value) => { setTokenView(value); setTimelineRange(null) }}allTurnsCollapsed={allTurnsCollapsed}onToggleAllTurns={toggleAllTurns}allAssistantsCollapsed={allAssistantsCollapsed}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.cssindex add96709e1..9b71bc95bc 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTimeline.module.css+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTimeline.module.css@@ -185,38 +185,67 @@);}+/* Two-tone block: the leading share is TTFT under recorded time, reasoning on an+ Output block, and cache-written tokens on an Input block; the trailing share is+ decoding, content, respectively recomputed input. */.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);+ --trajectory-span-trail-color: var(--dsw-alias-brand-primary-new-colorprimary-new-color);+ --trajectory-span-lead-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(+ --trajectory-span-trail-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(+ --trajectory-span-lead-color: color-mix(in srgb,- var(--trajectory-assistant-decoding-color) 54%,+ var(--trajectory-span-trail-color) 54%,var(--dsw-alias-bg-layer-2));}}.span[data-timeline-span='message'] {- background: var(--trajectory-assistant-decoding-color);+ background: var(--trajectory-span-trail-color);opacity: 1;}-.span[data-timeline-span='message'][data-assistant-timing='true'] {+/* Token cost of everything one request read: prompts, context, and tool results.+ Its leading share is what this request wrote into the cache, which in an agent+ loop is mostly the previous turn's output being paid for a second time. */+.span[data-timeline-segment='input'] {+ --trajectory-span-trail-color: var(--dsw-alias-state-success-primary);+ --trajectory-span-lead-color: var(--dsw-alias-state-success-primary);++ background: var(--trajectory-span-trail-color);+ opacity: 0.78;+}++@supports (color: color-mix(in srgb, currentColor, transparent)) {+ .span[data-timeline-segment='input'] {+ --trajectory-span-trail-color: color-mix(+ in srgb,+ var(--dsw-alias-state-success-primary) 68%,+ var(--dsw-alias-label-secondary)+ );+ --trajectory-span-lead-color: color-mix(+ in srgb,+ var(--trajectory-span-trail-color) 54%,+ var(--dsw-alias-bg-layer-2)+ );+ }+}++.span[data-span-split='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%+ var(--trajectory-span-lead-color) 0,+ var(--trajectory-span-lead-color) var(--trajectory-span-split),+ var(--trajectory-span-trail-color) var(--trajectory-span-split),+ var(--trajectory-span-trail-color) 100%);}diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTimeline.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTimeline.tsxindex e029e7f77b..b578193ccc 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTimeline.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryTimeline.tsx@@ -13,17 +13,21 @@ import {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 { formatTokenCount, liveElapsedSeconds } from '../trajectory/record.ts'import {deriveTrajectoryTimeline,formatTimelineOffset,type TrajectoryTimelineMode,+ type TrajectoryTimelineSegment,+ type TrajectoryTimelineSpan,type TrajectoryTimeRange,} from '../trajectory/timeline.ts'import css from './TrajectoryTimeline.module.css'const MINIMUM_DRAG_PX = 3const MINIMUM_ZOOM_OPERATIONS = 4+const MINIMUM_ZOOM_TOKENS = 256+const MINIMUM_ZOOM_MILLIS = 20const EDGE_PAN_ZONE_FRACTION = 0.08const EDGE_PAN_STEP_FRACTION = 0.025const MAXIMUM_EDGE_PAN_PX = 32@@ -34,6 +38,11 @@ interface TimelineRecordDetail {durationMs?: numberstartedAt?: numberttftMs?: number+ cachedInput?: number+ cacheWriteInput?: number+ processedInput?: number+ outputTokens?: number+ reasoningTokens?: number}interface FractionRange {@@ -74,6 +83,25 @@ function assistantTimingDetail(return { ttftMs: first - start, decodingMs: completed - first }}+function tokenUsageDetail(+ cell: TrajectoryCellProps,+): Pick<+ TimelineRecordDetail,+ 'cachedInput' | 'cacheWriteInput' | 'processedInput' | 'outputTokens' | 'reasoningTokens'+> {+ const cachedInput = cell.cacheRead+ const processedInput = cell.input === undefined+ ? undefined+ : Math.max(0, cell.input - (cell.cacheRead ?? 0))+ return {+ ...(cachedInput === undefined ? {} : { cachedInput }),+ ...(cell.cacheWrite === undefined ? {} : { cacheWriteInput: cell.cacheWrite }),+ ...(processedInput === undefined ? {} : { processedInput }),+ ...(cell.output === undefined ? {} : { outputTokens: cell.output }),+ ...(cell.think === undefined ? {} : { reasoningTokens: cell.think }),+ }+}+function timelineRecordDetail(cell: TrajectoryCellProps,nowMilliseconds: number,@@ -89,6 +117,7 @@ function timelineRecordDetail(...(durationMs === undefined ? {} : { durationMs }),...(startedAt === undefined ? {} : { startedAt }),...assistantTimingDetail(cell.assistantMetrics),+ ...tokenUsageDetail(cell),}}@@ -113,10 +142,48 @@ function formatRecordedTime(timestamp: number): string {})}+function tokenTooltipLabel(+ segment: TrajectoryTimelineSegment,+ detail: TimelineRecordDetail | undefined,+): string {+ if (segment === 'input') {+ const processed = detail?.processedInput+ const cacheWrite = detail?.cacheWriteInput+ const cached = detail?.cachedInput+ const uncached = processed === undefined || cacheWrite === undefined+ ? null+ : `Uncached ${formatTokenCount(Math.max(0, processed - cacheWrite))}`+ return [+ 'INPUT',+ [+ `Processed ${formatTokenCount(processed)}`,+ uncached,+ cacheWrite === undefined ? null : `Cache write ${formatTokenCount(cacheWrite)}`,+ cached === undefined ? null : `Cached ${formatTokenCount(cached)}`,+ ].filter(value => value !== null).join(' · '),+ ].join('\n')+ }+ const output = detail?.outputTokens+ const reasoning = detail?.reasoningTokens+ const content = output === undefined || reasoning === undefined+ ? null+ : `Content ${formatTokenCount(Math.max(0, output - reasoning))}`+ return [+ 'OUTPUT',+ [+ `Total ${formatTokenCount(output)}`,+ reasoning === undefined ? null : `Reasoning ${formatTokenCount(reasoning)}`,+ content,+ ].filter(value => value !== null).join(' · '),+ ].join('\n')+}+function timelineTooltipLabel(kind: TrajectoryCellKind,detail: TimelineRecordDetail | undefined,+ segment: TrajectoryTimelineSegment | undefined,): string {+ if (segment !== undefined) return tokenTooltipLabel(segment, detail)const heading = timelineKindLabel(kind)if (detail === undefined) return headingconst duration = detail.durationMs === undefined@@ -161,6 +228,23 @@ export interface TrajectoryTimelineProps {nowMilliseconds?: number}+function minimumZoomDomain(mode: TrajectoryTimelineMode): number {+ if (mode === 'sequence') return MINIMUM_ZOOM_OPERATIONS+ if (mode === 'tokens') return MINIMUM_ZOOM_TOKENS+ return MINIMUM_ZOOM_MILLIS+}++function spanKey(span: TrajectoryTimelineSpan): string {+ return `${span.lane}:${span.index}`+}++function spanCovers(span: TrajectoryTimelineSpan, index: number | null): boolean {+ if (index === null) return false+ return span.coveredIndexes === undefined+ ? span.index === index+ : span.index === index || span.coveredIndexes.includes(index)+}+function orderedRange(left: number, right: number): FractionRange {return left <= right ? { start: left, end: right } : { start: right, end: left }}@@ -200,7 +284,15 @@ function rangeFraction(}}-function LaneLabels() {+function LaneLabels({ mode }: { mode: TrajectoryTimelineMode }) {+ if (mode === 'tokens') {+ return (+ <div className={css.labels} aria-hidden="true">+ <span>Input</span>+ <span>Output</span>+ </div>+ )+ }return (<div className={css.labels} aria-hidden="true"><span>Input</span>@@ -279,6 +371,7 @@ export const TrajectoryTimeline = memo(function TrajectoryTimeline({anchorTime: numberanchorClientX: numberrecordIndex: number | null+ spanKey: string | null} | null>(null)const panRef = useRef<PanGesture | null>(null)const rootRef = useRef<HTMLElement | null>(null)@@ -313,7 +406,7 @@ export const TrajectoryTimeline = memo(function TrajectoryTimeline({}, [model])useEffect(() => {if (model === null || selectedIndex === null) return- const selectedSpan = model.spans.find(span => span.index === selectedIndex)+ const selectedSpan = model.spans.find(span => spanCovers(span, selectedIndex))if (selectedSpan === undefined) returnsetAnimateViewport(true)setViewport((current) => {@@ -393,7 +486,7 @@ export const TrajectoryTimeline = memo(function TrajectoryTimeline({const nextDuration = Math.min(fullDuration,Math.max(- Math.min(mode === 'sequence' ? MINIMUM_ZOOM_OPERATIONS : 20, fullDuration),+ Math.min(minimumZoomDomain(mode), fullDuration),domainDuration * Math.exp(event.deltaY * 0.0015),),)@@ -416,7 +509,7 @@ export const TrajectoryTimeline = memo(function TrajectoryTimeline({return (<section ref={rootRef} className={css.root} aria-label="Trajectory timeline"><div className={css.plot}>- <LaneLabels />+ <LaneLabels mode={mode} /><div className={css.track}><span className={css.empty}>No timing data</span>{hasEarlierRecords && (@@ -451,6 +544,12 @@ export const TrajectoryTimeline = memo(function TrajectoryTimeline({return Number.isFinite(index) ? index : null}+ const spanKeyAt = (event: PointerEvent<HTMLDivElement>): string | null => {+ const target = event.target instanceof HTMLElement ? event.target : null+ return target?.closest<HTMLElement>('[data-timeline-span-key]')+ ?.dataset.timelineSpanKey ?? null+ }+const commit = (nextRange: TrajectoryTimeRange) => {onRangeChange(nextRange)}@@ -481,6 +580,7 @@ export const TrajectoryTimeline = memo(function TrajectoryTimeline({anchorTime,anchorClientX: event.clientX,recordIndex,+ spanKey: spanKeyAt(event),}if (typeof event.currentTarget.setPointerCapture === 'function') {event.currentTarget.setPointerCapture(event.pointerId)@@ -562,10 +662,17 @@ export const TrajectoryTimeline = memo(function TrajectoryTimeline({dragRef.current = nullsetDraft(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)+ const clickedSpan = click && drag.spanKey !== null+ ? model.spans.find(span => spanKey(span) === drag.spanKey): undefinedif (clickedSpan !== undefined) {+ // An Input block stands for the records its request consumed, so clicking it+ // focuses that whole stretch of the ledger instead of the request row itself.+ if (clickedSpan.segment === 'input') {+ onRangeChange({ start: clickedSpan.start, end: clickedSpan.end })+ onRecordFocus?.(clickedSpan.coveredIndexes?.[0] ?? clickedSpan.index)+ return+ }onRangeChange(null)onRecordSelect?.(clickedSpan.index)return@@ -611,7 +718,7 @@ export const TrajectoryTimeline = memo(function TrajectoryTimeline({return (<section ref={rootRef} className={css.root} aria-label="Trajectory timeline"><div className={css.plot}>- <LaneLabels />+ <LaneLabels mode={mode} /><divref={trackRef}className={css.track}@@ -704,7 +811,7 @@ export const TrajectoryTimeline = memo(function TrajectoryTimeline({>{model.spans.filter(span =>- span.index === selectedIndex+ spanCovers(span, selectedIndex)|| (span.end >= domainStart && span.start <= domainStart + domainDuration)).map((span) => {const left = (span.start - model.start) / fullDuration@@ -718,10 +825,13 @@ export const TrajectoryTimeline = memo(function TrajectoryTimeline({|| ttftMs + decodingMs <= 0? null: ttftMs / (ttftMs + decodingMs)+ const splitFraction = mode === 'tokens'+ ? span.splitFraction ?? null+ : ttftFractionreturn (<Tooltip- key={span.index}- label={() => timelineTooltipLabel(span.kind, detail)}+ key={spanKey(span)}+ label={() => timelineTooltipLabel(span.kind, detail, span.segment)}side="bottom"delayMs={TIMELINE_TOOLTIP_DELAY_MS}>@@ -730,10 +840,12 @@ export const TrajectoryTimeline = memo(function TrajectoryTimeline({className={css.span}data-timeline-span={span.kind}data-timeline-record-index={span.index}- data-assistant-timing={ttftFraction === null ? undefined : 'true'}+ data-timeline-span-key={spanKey(span)}+ data-timeline-segment={span.segment}+ data-span-split={splitFraction === null ? undefined : 'true'}data-error={span.isError || undefined}data-equal-duration={mode === 'time' || undefined}- data-current={span.index === selectedIndex || undefined}+ data-current={spanCovers(span, selectedIndex) || undefined}data-hovered={hover?.recordIndex === span.index || undefined}data-search-match={searchMatchIndexes === null? undefined@@ -748,9 +860,9 @@ export const TrajectoryTimeline = memo(function TrajectoryTimeline({'--trajectory-span-width': `${widthPercent}%`,'--trajectory-span-gap': `min(${widthPercent * 0.08}%, 1px)`,'--trajectory-span-lane': span.lane,- ...(ttftFraction === null+ ...(splitFraction === null? {}- : { '--trajectory-assistant-ttft': `${ttftFraction * 100}%` }),+ : { '--trajectory-span-split': `${splitFraction * 100}%` }),} as CSSProperties}/></Tooltip>diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryToolbar.tsx b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryToolbar.tsxindex a3d68167a6..7b524fa311 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryToolbar.tsx+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/TrajectoryToolbar.tsx@@ -19,6 +19,10 @@ export interface TrajectoryToolbarProps {actualTime: boolean/** Select complete wall-clock timing or idle-compressed timing. */onActualTimeChange: (actualTime: boolean) => void+ /** Whether timeline blocks are sized by recorded token spend. */+ tokenView: boolean+ /** Select token-cost or timing blocks. */+ onTokenViewChange: (tokenView: boolean) => void/** Whether every collapsible turn is currently folded. */allTurnsCollapsed: boolean/** Fold or expand every collapsible turn. */@@ -45,6 +49,8 @@ export function TrajectoryToolbar({onActualDurationChange,actualTime,onActualTimeChange,+ tokenView,+ onTokenViewChange,allTurnsCollapsed,onToggleAllTurns,allAssistantsCollapsed,@@ -76,6 +82,24 @@ export function TrajectoryToolbar({</svg>{t('toolbar.duration')}</button>+ <button+ type="button"+ className={css.toggle}+ aria-label={t('toolbar.useTokenCost')}+ aria-pressed={tokenView}+ title={tokenView ? t('toolbar.useEqualWidth') : t('toolbar.useTokenCost')}+ onClick={() => { onTokenViewChange(!tokenView) }}+ >+ <svg+ className={css.toggleIcon}+ viewBox="0 0 16 16"+ fill="none"+ aria-hidden="true"+ >+ <path d="M2.75 5.5h10.5M2.75 10.5h5.5" />+ </svg>+ {t('toolbar.tokens')}+ </button><buttontype="button"className={css.control}diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/i18n.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/i18n.tsindex 5c72ab76b1..ac71cc7c9a 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/i18n.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/client/i18n.ts@@ -8,6 +8,8 @@ export type TrajectoryKey =| 'toolbar.useActualDuration'| 'toolbar.useEqualWidth'| 'toolbar.actualTime'+ | 'toolbar.tokens'+ | 'toolbar.useTokenCost'| 'toolbar.turns'| 'toolbar.expandTurns'| 'toolbar.collapseTurns'@@ -25,6 +27,8 @@ export const en: Readonly<Record<TrajectoryKey, string>> = {'toolbar.useActualDuration': 'Use actual duration','toolbar.useEqualWidth': 'Use equal-width operations','toolbar.actualTime': 'Actual time',+ 'toolbar.tokens': 'Tokens',+ 'toolbar.useTokenCost': 'Use token cost','toolbar.turns': 'Turns','toolbar.expandTurns': 'Expand turns','toolbar.collapseTurns': 'Collapse turns',@@ -39,6 +43,7 @@ export const zh: Readonly<Record<TrajectoryKey, string>> = {...en,'toolbar.aria': '轨迹工具栏','toolbar.actualTime': '实际时间',+ 'toolbar.useTokenCost': '按 token 开销显示','toolbar.search': '搜索轨迹','toolbar.searchPlaceholder': '搜索',}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.tsindex c3c12faa19..f668c0f818 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/attribute-resolver.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/projector/attribute-resolver.ts@@ -157,10 +157,6 @@ const LEGACY = {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',@@ -300,18 +296,6 @@ function object(value: unknown): Record<string, unknown> | undefined {: 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@@ -330,20 +314,6 @@ function langfuseFinishReasons(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 valuereturn JSON.stringify(value, null, 2) ?? String(value)@@ -796,65 +766,30 @@ export function normalizeTrajectoryAttributes(}}+ // Token usage is read only in the standard shape, where every cache and+ // reasoning count is a breakdown of the input respectively output total.+ // Legacy and Langfuse spellings carve the cache out of the input instead, so+ // mixing them would silently double-subtract cached tokens.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,]))+ // Totals have no standard attribute of their own.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,]))diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/record.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/record.tsindex 04dfeeefe0..c3d00cd2f8 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/record.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/record.ts@@ -109,6 +109,13 @@ export function formatDurationMillis(milliseconds: number | null): string {return `${integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',')} ms`}+/** Format a token count with thousands separators, or an em dash when unknown. */+export function formatTokenCount(tokens: number | null | undefined): string {+ if (tokens === null || tokens === undefined || !Number.isFinite(tokens)) return '—'+ const integer = String(Math.round(tokens))+ return `${integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',')} tok`+}+/** Format elapsed seconds as an integer-millisecond label. */export function formatElapsedSeconds(seconds: number | null): string {return formatDurationMillis(seconds === null ? null : seconds * 1_000)diff --git a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/timeline.ts b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/timeline.tsindex 5967842d7d..7f654c77c8 100644--- a/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/timeline.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/trajectory/trajectory/timeline.ts@@ -11,7 +11,10 @@ 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'+export type TrajectoryTimelineMode = 'sequence' | 'duration' | 'time' | 'actual' | 'tokens'++/** Which half of one request's token spend a block represents. */+export type TrajectoryTimelineSegment = 'input' | 'output'/** Inclusive selection in the active timeline projection's domain. */export interface TrajectoryTimeRange {@@ -26,6 +29,19 @@ export interface TrajectoryTimelineSpan extends TrajectoryTimeRange {kind: TrajectoryCellKindlabel: stringlane: number+ /** Token-spend half represented by this block; absent outside the token projection. */+ segment?: TrajectoryTimelineSegment+ /**+ * Leading-segment share in `[0, 1]` used by the two-tone block gradient:+ * cache-written tokens for an Input block, reasoning for an Output block.+ */+ splitFraction?: number+ /**+ * Ledger records this block accounts for, which for an Input block are the+ * records consumed by request `index` rather than the request itself.+ * Absent when the block accounts for `index` alone.+ */+ coveredIndexes?: readonly number[]}/** One turn boundary in the active timeline domain. */@@ -55,6 +71,25 @@ function laneFor(kind: TrajectoryCellKind): number {return 0}+function isModelCell(kind: TrajectoryCellKind): boolean {+ return kind === 'message' || kind === 'compacted'+}++/**+ * Resolve the active projection from the toolbar's independent switches.+ * @param options - Token view flag plus the recorded-duration and complete-time switches.+ * @returns Projection selected by the toolbar, token cost taking precedence.+ */+export function resolveTimelineMode(options: {+ tokenView: boolean+ actualDuration: boolean+ actualTime: boolean+}): TrajectoryTimelineMode {+ if (options.tokenView) return 'tokens'+ if (options.actualDuration) return options.actualTime ? 'actual' : 'duration'+ return options.actualTime ? 'time' : 'sequence'+}+function finite(value: number | null | undefined): value is number {return value !== null && value !== undefined && Number.isFinite(value)}@@ -76,7 +111,7 @@ function cellRange(/*** 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.+ * @param mode - Equal/recorded duration, compressed/complete time, or token-cost projection.* @returns Timeline model, or `null` when no record is visible.*/export function deriveTrajectoryTimeline(@@ -84,6 +119,7 @@ export function deriveTrajectoryTimeline(mode: TrajectoryTimelineMode = 'sequence',nowMilliseconds?: number,): TrajectoryTimelineModel | null {+ if (mode === 'tokens') return deriveTokenTimeline(turns)if (mode !== 'sequence') {return deriveTimedTimeline(turns,@@ -126,6 +162,96 @@ export function deriveTrajectoryTimeline(}}+function tokenCount(value: number | undefined): number {+ return value === undefined || !Number.isFinite(value) ? 0 : Math.max(0, value)+}++/**+ * Project recorded token spend into a cumulative two-lane timeline.+ *+ * Every model request contributes an Input block sized by its cache-missed input+ * and an Output block sized by its produced tokens, laid head to tail so the full+ * domain equals the session's total token spend. Tool, prompt, and context records+ * do not own a block; their cost surfaces inside the Input block of the request+ * that consumed them.+ *+ * @param turns - Unfiltered trajectory layout.+ * @returns Timeline model, or `null` when no record reported usage.+ */+function deriveTokenTimeline(+ turns: readonly TrajectoryTurnModel[],+): TrajectoryTimelineModel | null {+ const spans: TrajectoryTimelineSpan[] = []+ const turnBoundaries: TrajectoryTimelineTurnBoundary[] = []+ let cursor = 0+ let pendingIndexes: number[] = []++ for (const turn of turns) {+ const spansBeforeTurn = spans.length+ const turnStart = cursor+ for (const cell of turn.groups.flatMap(group => group.cells)) {+ if (cell.requestOnly === true) continue+ if (!isModelCell(cell.kind)) {+ pendingIndexes.push(cell.index)+ continue+ }+ const uncachedInput = Math.max(0, tokenCount(cell.input) - tokenCount(cell.cacheRead))+ const output = tokenCount(cell.output)+ const covered = pendingIndexes+ pendingIndexes = []+ if (uncachedInput > 0) {+ // A request whose new input went entirely into the cache reports no+ // plain miss at all, so a full leading share is a real reading.+ const cacheWrite = tokenCount(cell.cacheWrite)+ const splitFraction = cacheWrite > 0+ ? Math.min(1, cacheWrite / uncachedInput)+ : null+ spans.push({+ start: cursor,+ end: cursor + uncachedInput,+ index: cell.index,+ isError: false,+ kind: cell.kind,+ label: cell.text,+ lane: 0,+ segment: 'input',+ coveredIndexes: covered.length === 0 ? [cell.index] : covered,+ ...(splitFraction === null ? {} : { splitFraction }),+ })+ cursor += uncachedInput+ }+ if (output > 0) {+ const think = tokenCount(cell.think)+ const splitFraction = think > 0 ? Math.min(1, think / output) : null+ spans.push({+ start: cursor,+ end: cursor + output,+ index: cell.index,+ isError: cell.isError === true,+ kind: cell.kind,+ label: cell.text,+ lane: 1,+ segment: 'output',+ coveredIndexes: [cell.index],+ ...(splitFraction === null ? {} : { splitFraction }),+ })+ cursor += output+ }+ }+ if (turn.turn !== null && spans.length > spansBeforeTurn) {+ turnBoundaries.push({ turn: turn.turn, time: turnStart })+ }+ }++ if (spans.length === 0) return null+ return {+ start: 0,+ end: cursor,+ spans,+ turnBoundaries,+ }+}+function deriveTimedTimeline(turns: readonly TrajectoryTurnModel[],actualDuration: boolean,@@ -198,7 +324,7 @@ function deriveTimedTimeline(* 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.+ * @param mode - Equal/recorded duration, compressed/complete time, or token-cost projection.* @returns Record indexes inside the focus interval.*/export function trajectoryTimelineFocusIndexes(@@ -211,6 +337,6 @@ export function trajectoryTimelineFocusIndexes(return new Set(model?.spans.filter(span => span.start <= range.end && span.end >= range.start)- .map(span => span.index),+ .flatMap(span => span.coveredIndexes ?? [span.index]),)}diff --git a/jiuwenswarm/channels/web/frontend/tests/trajectoryTimeline.test.mjs b/jiuwenswarm/channels/web/frontend/tests/trajectoryTimeline.test.mjsnew file mode 100644index 0000000000..4e9b98d941--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/trajectoryTimeline.test.mjs@@ -0,0 +1,206 @@+// Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++import assert from 'node:assert/strict';+import test from 'node:test';++import {+ deriveTrajectoryTimeline,+ resolveTimelineMode,+ trajectoryTimelineFocusIndexes,+} from '../node_modules/.cache/trajectory-timeline/timeline.mjs';++function cell(index, kind, extra = {}) {+ return { index, kind, text: `${kind}-${index}`, timeSeconds: null, ...extra };+}++function turn(number, cells) {+ return { turn: number, groups: [{ cells }] };+}++function tokenTimeline(turns) {+ return deriveTrajectoryTimeline(turns, 'tokens');+}++test('token blocks lay input and output head to tail across the full spend', () => {+ const model = tokenTimeline([+ turn(1, [+ cell(0, 'user'),+ cell(1, 'message', { input: 1_000, cacheRead: 400, output: 200 }),+ cell(2, 'tool'),+ cell(3, 'message', { input: 2_000, cacheRead: 1_500, output: 100 }),+ ]),+ ]);++ assert.deepEqual(+ model.spans.map(span => [span.segment, span.lane, span.start, span.end]),+ [+ ['input', 0, 0, 600],+ ['output', 1, 600, 800],+ ['input', 0, 800, 1_300],+ ['output', 1, 1_300, 1_400],+ ],+ );+ assert.equal(model.start, 0);+ assert.equal(model.end, 1_400);+});++test('input blocks measure cache-missed input and keep cache writes billed', () => {+ const model = tokenTimeline([+ turn(1, [cell(0, 'message', { input: 900, cacheRead: 300, cacheWrite: 200, output: 50 })]),+ ]);++ const input = model.spans.find(span => span.segment === 'input');+ assert.equal(input.end - input.start, 600);+});++test('input blocks split on the share written into the cache', () => {+ const model = tokenTimeline([+ turn(1, [+ cell(0, 'message', { input: 900, cacheRead: 300, cacheWrite: 150, output: 10 }),+ cell(1, 'message', { input: 900, cacheRead: 300, output: 10 }),+ // Everything new went into the cache, so the provider reports no plain miss.+ cell(2, 'message', { input: 900, cacheRead: 300, cacheWrite: 600, output: 10 }),+ ]),+ ]);++ assert.deepEqual(+ model.spans.filter(span => span.segment === 'input').map(span => span.splitFraction),+ [0.25, undefined, 1],+ );+});++test('an input block covers the records its request consumed, not the request row', () => {+ const model = tokenTimeline([+ turn(1, [+ cell(0, 'system'),+ cell(1, 'user'),+ cell(2, 'message', { input: 500, output: 40 }),+ cell(3, 'tool'),+ cell(4, 'subtool'),+ cell(5, 'message', { input: 800, output: 60 }),+ ]),+ ]);++ const inputs = model.spans.filter(span => span.segment === 'input');+ assert.deepEqual(inputs.map(span => span.coveredIndexes), [[0, 1], [3, 4]]);+ assert.deepEqual(inputs.map(span => span.index), [2, 5]);+ const outputs = model.spans.filter(span => span.segment === 'output');+ assert.deepEqual(outputs.map(span => span.coveredIndexes), [[2], [5]]);+});++test('an input block without preceding records falls back to its own request', () => {+ const model = tokenTimeline([+ turn(1, [cell(0, 'message', { input: 400, output: 10 })]),+ ]);++ assert.deepEqual(model.spans[0].coveredIndexes, [0]);+});++test('requests without usage take no room and hand their records to the next request', () => {+ const model = tokenTimeline([+ turn(1, [+ cell(0, 'user'),+ cell(1, 'message'),+ cell(2, 'tool'),+ cell(3, 'message', { input: 300, output: 20 }),+ ]),+ ]);++ assert.equal(model.spans.length, 2);+ assert.deepEqual(model.spans[0].coveredIndexes, [2]);+});++test('request-only records and trailing tool results never own a block', () => {+ const model = tokenTimeline([+ turn(1, [+ cell(0, 'context', { requestOnly: true }),+ cell(1, 'message', { input: 100, output: 10 }),+ cell(2, 'tool'),+ ]),+ ]);++ assert.deepEqual(model.spans.map(span => span.coveredIndexes), [[1], [1]]);+ assert.equal(model.end, 110);+});++test('the token projection is empty without reported usage', () => {+ assert.equal(+ tokenTimeline([turn(1, [cell(0, 'user'), cell(1, 'message'), cell(2, 'tool')])]),+ null,+ );+});++test('output blocks split on the reasoning share, up to an all-reasoning block', () => {+ const model = tokenTimeline([+ turn(1, [+ cell(0, 'message', { input: 10, output: 400, think: 100 }),+ cell(1, 'message', { input: 10, output: 400, think: 0 }),+ cell(2, 'message', { input: 10, output: 400, think: 400 }),+ ]),+ ]);++ assert.deepEqual(+ model.spans.filter(span => span.segment === 'output').map(span => span.splitFraction),+ [0.25, undefined, 1],+ );+});++test('turn boundaries land on the cumulative spend where each turn opens', () => {+ const model = tokenTimeline([+ turn(1, [cell(0, 'message', { input: 500, output: 100 })]),+ turn(2, [cell(1, 'message', { input: 200, output: 50 })]),+ turn(3, [cell(2, 'user')]),+ ]);++ assert.deepEqual(model.turnBoundaries, [+ { turn: 1, time: 0 },+ { turn: 2, time: 600 },+ ]);+});++test('focusing an input block selects every record that request consumed', () => {+ const turns = [+ turn(1, [+ cell(0, 'user'),+ cell(1, 'message', { input: 500, output: 100 }),+ cell(2, 'tool'),+ cell(3, 'message', { input: 200, output: 50 }),+ ]),+ ];++ assert.deepEqual(+ [...trajectoryTimelineFocusIndexes(turns, { start: 10, end: 490 }, 'tokens')],+ [0],+ );+ assert.deepEqual(+ [...trajectoryTimelineFocusIndexes(turns, { start: 520, end: 580 }, 'tokens')],+ [1],+ );+ assert.deepEqual(+ [...trajectoryTimelineFocusIndexes(turns, { start: 610, end: 790 }, 'tokens')],+ [2],+ );+});++test('token cost wins over the recorded-duration and complete-time switches', () => {+ assert.equal(+ resolveTimelineMode({ tokenView: true, actualDuration: true, actualTime: true }),+ 'tokens',+ );+ assert.equal(+ resolveTimelineMode({ tokenView: false, actualDuration: false, actualTime: false }),+ 'sequence',+ );+ assert.equal(+ resolveTimelineMode({ tokenView: false, actualDuration: true, actualTime: false }),+ 'duration',+ );+ assert.equal(+ resolveTimelineMode({ tokenView: false, actualDuration: true, actualTime: true }),+ 'actual',+ );+ assert.equal(+ resolveTimelineMode({ tokenView: false, actualDuration: false, actualTime: true }),+ 'time',+ );+});