ModelTrajectoryTimeline.tsx 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import { useVirtualizer } from "@tanstack/react-virtual";
  2. import { useEffect, type RefObject } from "react";
  3. import type { ZCodeModelTrajectoryRecord } from "@zcode/services";
  4. import {
  5. type TrajectorySearchMatch,
  6. type TrajectorySearchTimelineItem,
  7. } from "@/ModelTrajectorySearch.js";
  8. import {
  9. applyTrajectorySearchHighlights,
  10. clearTrajectorySearchHighlights,
  11. isTrajectorySearchTargetMounted,
  12. scrollTrajectorySearchRangeIntoView,
  13. } from "@/ModelTrajectorySearchHighlight.js";
  14. import { CallCard, type IntlShape } from "@/ModelTrajectoryPaneParts.js";
  15. export function ModelTrajectoryTimeline({
  16. items,
  17. searchQuery,
  18. searchMatches,
  19. activeSearchMatch,
  20. intl,
  21. scrollContainerRef,
  22. }: {
  23. items: TrajectorySearchTimelineItem[];
  24. searchQuery: string;
  25. searchMatches: TrajectorySearchMatch[];
  26. activeSearchMatch: TrajectorySearchMatch | null;
  27. intl: IntlShape;
  28. scrollContainerRef: RefObject<HTMLDivElement | null>;
  29. }) {
  30. const virtualizer = useVirtualizer({
  31. count: items.length,
  32. getScrollElement: () => scrollContainerRef.current,
  33. getItemKey: (index) => items[index]?.key ?? index,
  34. estimateSize: () => 240,
  35. overscan: 3,
  36. });
  37. // 搜索切换会同时收起旧命中并展开新命中;此时禁止 virtualizer 根据每次测高回调连续
  38. // 修正滚动锚点,由下方文本级定位在布局稳定后一次完成滚动。
  39. virtualizer.shouldAdjustScrollPositionOnItemSizeChange = () => !searchQuery;
  40. const roleWidthLabels = ["system", "user", "assistant", "tool"].map((role) =>
  41. intl.formatMessage({ id: `modelTrajectory.role.${role}` }),
  42. );
  43. const virtualItems = virtualizer.getVirtualItems();
  44. const firstVirtualItem = virtualItems[0];
  45. const lastVirtualItem = virtualItems.at(-1);
  46. const topSpacerHeight = firstVirtualItem?.start ?? 0;
  47. const bottomSpacerHeight = lastVirtualItem ? virtualizer.getTotalSize() - lastVirtualItem.end : 0;
  48. // 只跟踪挂载集合。把 start 放进依赖会让每次动态测高都重新安排一次精确滚动。
  49. const mountedRowsKey = virtualItems.map((item) => item.key).join("|");
  50. useEffect(() => () => clearTrajectorySearchHighlights(), []);
  51. useEffect(() => {
  52. const root = scrollContainerRef.current;
  53. if (
  54. !activeSearchMatch ||
  55. !root ||
  56. isTrajectorySearchTargetMounted(root, activeSearchMatch.expansionKey)
  57. ) {
  58. return;
  59. }
  60. // 目标已经挂载时跳过 Call 级预滚动,否则随后文本级定位会造成连续两次跳动。
  61. virtualizer.scrollToIndex(activeSearchMatch.callIndex, { align: "center" });
  62. }, [activeSearchMatch, scrollContainerRef, virtualizer]);
  63. useEffect(() => {
  64. const root = scrollContainerRef.current;
  65. if (!root || !searchQuery) {
  66. clearTrajectorySearchHighlights();
  67. return;
  68. }
  69. let secondFrame = 0;
  70. const firstFrame = window.requestAnimationFrame(() => {
  71. virtualizer.measure();
  72. secondFrame = window.requestAnimationFrame(() => {
  73. const activeRange = applyTrajectorySearchHighlights({
  74. root,
  75. query: searchQuery,
  76. matches: searchMatches,
  77. activeMatch: activeSearchMatch,
  78. });
  79. if (activeRange) scrollTrajectorySearchRangeIntoView(activeRange, root);
  80. });
  81. });
  82. return () => {
  83. window.cancelAnimationFrame(firstFrame);
  84. window.cancelAnimationFrame(secondFrame);
  85. };
  86. }, [
  87. activeSearchMatch,
  88. mountedRowsKey,
  89. scrollContainerRef,
  90. searchMatches,
  91. searchQuery,
  92. virtualizer,
  93. ]);
  94. return (
  95. <ol
  96. data-trajectory-timeline=""
  97. className="grid grid-cols-[max-content_minmax(0,1fr)_auto] gap-x-2"
  98. >
  99. {roleWidthLabels.map((label) => (
  100. <li
  101. key={label}
  102. aria-hidden="true"
  103. className="invisible col-start-1 row-start-1 h-0 overflow-hidden whitespace-nowrap font-mono text-ui-sm"
  104. >
  105. {label}
  106. </li>
  107. ))}
  108. {topSpacerHeight > 0 ? (
  109. <li aria-hidden="true" className="col-span-full" style={{ height: topSpacerHeight }} />
  110. ) : null}
  111. {virtualItems.map((virtualItem) => {
  112. const item = items[virtualItem.index];
  113. if (!item) return null;
  114. return (
  115. <li
  116. key={item.key}
  117. ref={virtualizer.measureElement}
  118. data-index={virtualItem.index}
  119. data-trajectory-virtual-row=""
  120. className="col-span-full grid w-full grid-cols-subgrid"
  121. >
  122. <CallCard
  123. record={item.record}
  124. index={virtualItem.index}
  125. inputMessages={item.inputMessages}
  126. expansionKeyPrefix={item.key}
  127. intl={intl}
  128. />
  129. </li>
  130. );
  131. })}
  132. {bottomSpacerHeight > 0 ? (
  133. <li aria-hidden="true" className="col-span-full" style={{ height: bottomSpacerHeight }} />
  134. ) : null}
  135. </ol>
  136. );
  137. }
  138. export function resolveTrajectoryTimelineItems(records: ZCodeModelTrajectoryRecord[]) {
  139. let previousConversationMessageCount = 0;
  140. return records.map((record, index) => {
  141. const resolvedInput = resolveTrajectoryInputMessages({
  142. index,
  143. previousConversationMessageCount,
  144. record,
  145. });
  146. previousConversationMessageCount = resolvedInput.nextConversationMessageCount;
  147. return {
  148. key: `${record.requestId}:${index}`,
  149. record,
  150. inputMessages: resolvedInput.inputMessages,
  151. };
  152. });
  153. }
  154. export function resolveTrajectoryInputMessages({
  155. record,
  156. index,
  157. previousConversationMessageCount,
  158. }: {
  159. record: ZCodeModelTrajectoryRecord;
  160. index: number;
  161. previousConversationMessageCount: number;
  162. }): {
  163. inputMessages: ZCodeModelTrajectoryRecord["request"]["messages"];
  164. nextConversationMessageCount: number;
  165. } {
  166. const messages = record.request.messages;
  167. const usesConversationDelta = shouldUseConversationDelta(record);
  168. const deltaMessages = usesConversationDelta
  169. ? computeDeltaMessages(messages, previousConversationMessageCount, index)
  170. : messages;
  171. return {
  172. // 首条展示完整起始上下文;后续主会话只展示非 assistant 的新增(assistant 由上一条 Output 呈现)。
  173. // sidecar/compact 等辅助请求有独立 prompt,不能套用主会话的消息数 delta,否则会隐藏标题生成 prompt。
  174. inputMessages: usesConversationDelta
  175. ? index === 0
  176. ? deltaMessages
  177. : deltaMessages.filter((message) => message.role !== "assistant")
  178. : deltaMessages,
  179. nextConversationMessageCount: usesConversationDelta
  180. ? messages.length
  181. : previousConversationMessageCount,
  182. };
  183. }
  184. function shouldUseConversationDelta(record: ZCodeModelTrajectoryRecord): boolean {
  185. const kind = record.callSource?.kind;
  186. return kind === undefined || kind === "main" || kind === "subagent";
  187. }
  188. function computeDeltaMessages(
  189. messages: ZCodeModelTrajectoryRecord["request"]["messages"],
  190. previousMessageCount: number,
  191. index: number,
  192. ): ZCodeModelTrajectoryRecord["request"]["messages"] {
  193. if (index === 0) return messages;
  194. if (messages.length > previousMessageCount) return messages.slice(previousMessageCount);
  195. if (messages.length < previousMessageCount) return messages;
  196. return [];
  197. }