render-boundaries.fixture.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. import { useCallback, useMemo, useRef, useState } from "react";
  2. import { createRoot } from "react-dom/client";
  3. import { useVirtualizer } from "@tanstack/react-virtual";
  4. import { Streamdown } from "streamdown";
  5. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  6. import { TooltipProvider } from "@/components/ui/tooltip.js";
  7. import { ConversationTurnNavigator } from "@/v4/ConversationTurnNavigator.js";
  8. import { createConversationTurnRenderUnitsSelector } from "@/v4/conversationTurnRenderUnits.js";
  9. import { getConversationRowsPartition } from "@/v4/conversationProjectionStore.js";
  10. import { useDraftConfigControl } from "@/v4/composer/useDraftConfigControl.js";
  11. import {
  12. clearV4ComposerDraftTaskGroup,
  13. persistV4ComposerDraft,
  14. readV4ComposerDraft,
  15. resolveComposerScope,
  16. V4_DRAFT_SCOPE_ROOT,
  17. } from "@/v4/composer/composerDraftStore.js";
  18. import { useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  19. import { AssistantCodeCommentFeatureProvider } from "@/AssistantCodeCommentFeatureProvider.js";
  20. import { projectAssistantCodeComments } from "@/lib/assistantCodeComment.js";
  21. import { useConversationTimelineFind } from "@/v4/useConversationTimelineFind.js";
  22. import type { ConversationRow } from "@zcode/shared/zcode-protocol-v4";
  23. import type { ConversationFindMatchState } from "@/v4/legacyChatViewTypes.js";
  24. import "@/styles.css";
  25. const params = new URLSearchParams(location.search);
  26. const theme = params.get("theme") === "light" ? "light" : "dark";
  27. document.documentElement.className = `${theme} theme-zai-${theme}`;
  28. const workspace = "/render-boundary";
  29. if (params.get("group") === "1")
  30. useZCodeSessionStore
  31. .getState()
  32. .startDraft(workspace, undefined, undefined, { taskGroupId: "group-a" });
  33. persistV4ComposerDraft(
  34. workspace,
  35. undefined,
  36. V4_DRAFT_SCOPE_ROOT,
  37. { text: "", mode: "build", updatedAt: 0 },
  38. resolveComposerScope(null),
  39. );
  40. let ownerRenders = 0;
  41. function DraftOwner() {
  42. const [sessionId, setSessionId] = useState<string | null>(null);
  43. const owner = useDraftConfigControl({
  44. workspacePath: workspace,
  45. provider: "zcode",
  46. sessionId,
  47. sessionConfig: null,
  48. agentStartupAllowed: false,
  49. modelSelectionService: null,
  50. });
  51. ownerRenders++;
  52. Object.assign(window, {
  53. __draftBoundary: {
  54. renders: () => ownerRenders,
  55. type: (text: string) => {
  56. owner.stageComposerContent({ text });
  57. // 修复前落入旧保存路径,先保留真实失败基线。
  58. const persist =
  59. "persistComposerContent" in owner
  60. ? owner.persistComposerContent
  61. : owner.updateComposerContent;
  62. (persist as (content: { text: string }) => void)({ text });
  63. },
  64. mode: () => owner.handleDraftSwitchMode("yolo"),
  65. switch: () => setSessionId((value) => (value ? null : "another")),
  66. read: () =>
  67. readV4ComposerDraft(workspace, undefined, V4_DRAFT_SCOPE_ROOT, resolveComposerScope(null)),
  68. owner: () => owner.composerDraft,
  69. capture: (text: string) => owner.captureComposerSubmissionDraftTransaction({ text }),
  70. promote: () => owner.promoteComposerDraft("created"),
  71. lifecycle: () => owner.captureComposerContentLifecycleCommit(),
  72. clearGroup: () => {
  73. clearV4ComposerDraftTaskGroup(workspace, undefined, resolveComposerScope(null));
  74. useZCodeSessionStore.getState().clearDraftTaskGroup(workspace);
  75. },
  76. },
  77. });
  78. return <output data-testid="draft-ready">{sessionId ?? "draft"}</output>;
  79. }
  80. const rows: ConversationRow[] = Array.from({ length: 1000 }, (_, index) => {
  81. const base = { turnId: `turn-${index}`, createdAt: 1, createdAtSeq: index * 3 + 1 };
  82. return [
  83. {
  84. ...base,
  85. rowId: index * 3 + 1,
  86. kind: "turnHeader",
  87. origin: "userInput",
  88. state: index === 999 ? "running" : "completedSuccess",
  89. startedAt: 1,
  90. endedAt: index === 999 ? undefined : 2,
  91. },
  92. {
  93. ...base,
  94. rowId: index * 3 + 2,
  95. kind: "userInput",
  96. origin: "realUser",
  97. text: `question ${index}`,
  98. },
  99. {
  100. ...base,
  101. rowId: index * 3 + 3,
  102. kind: "assistantText",
  103. text: `answer ${index}`,
  104. state: index === 999 ? "streaming" : "complete",
  105. },
  106. ] as ConversationRow[];
  107. }).flat();
  108. const virtualItems = [{ index: 0, start: 0, size: 100 }];
  109. function Navigation() {
  110. const [source, setSource] = useState(rows);
  111. const select = useMemo(() => createConversationTurnRenderUnitsSelector(), []);
  112. const units = select(getConversationRowsPartition(source), { nowMs: 5000 });
  113. const [jump, setJump] = useState("");
  114. Object.assign(window, {
  115. __navBoundary: {
  116. stream: () =>
  117. setSource((old) =>
  118. old.map((row) =>
  119. row.kind === "assistantText" && row.turnId === "turn-999"
  120. ? { ...row, text: row.text + " next" }
  121. : row,
  122. ),
  123. ),
  124. revise: () =>
  125. setSource((old) =>
  126. old.map((row) =>
  127. row.kind === "assistantText" && row.turnId === "turn-0"
  128. ? { ...row, text: "revised answer" }
  129. : row,
  130. ),
  131. ),
  132. trim: () => setSource((old) => old.filter((row) => row.turnId !== "turn-0")),
  133. },
  134. });
  135. return (
  136. <main className="relative h-screen w-full @container/conversation">
  137. <output data-testid="jump">{jump}</output>
  138. <ConversationTurnNavigator
  139. renderUnits={units}
  140. scrollOffsetPx={0}
  141. viewportHeightPx={700}
  142. virtualItems={virtualItems}
  143. onJumpToQuery={useMemo(
  144. () => (target: { unitIndex: number; rowId: number }) => setJump(JSON.stringify(target)),
  145. [],
  146. )}
  147. />
  148. </main>
  149. );
  150. }
  151. function Search() {
  152. const [source, setSource] = useState(() =>
  153. rows.slice(0, 9).map((row) =>
  154. row.kind !== "assistantText"
  155. ? row
  156. : {
  157. ...row,
  158. text:
  159. row.turnId === "turn-0"
  160. ? 'Visible alpha\n::code-comment{title="Hidden" body="hidden-value" file="/repo/a.ts"}\nTail'
  161. : row.turnId === "turn-1"
  162. ? '`::code-comment{title="Literal" body="protected-value" file="/repo/b.ts"}`'
  163. : `普通文本 ${"alpha ".repeat(300)}没有指令。`,
  164. },
  165. ),
  166. );
  167. const select = useMemo(() => createConversationTurnRenderUnitsSelector(), []);
  168. const units = useMemo(() => select(getConversationRowsPartition(source), {}), [select, source]);
  169. const rootRef = useRef<HTMLDivElement>(null);
  170. const [query, setQuery] = useState("");
  171. const [matches, setMatches] = useState({ query: "", activeIndex: 0, matchCount: 0 });
  172. const scrollToUnit = useMemo(() => () => undefined, []);
  173. useConversationTimelineFind({
  174. rootRef,
  175. renderUnits: units,
  176. rows: source,
  177. mountedRowsKey: "all",
  178. isMountedLayoutMeasured: useMemo(() => () => true, []),
  179. canLoadOlder: false,
  180. loadingOlder: false,
  181. conversationFindQuery: query,
  182. conversationFindActiveIndex: 0,
  183. conversationFindNavigationRequestId: 0,
  184. onConversationFindMatchStateChange: useMemo(
  185. () => (next: typeof matches) =>
  186. setMatches((old) =>
  187. old.query === next.query &&
  188. old.activeIndex === next.activeIndex &&
  189. old.matchCount === next.matchCount
  190. ? old
  191. : next,
  192. ),
  193. [],
  194. ),
  195. scrollToUnit,
  196. });
  197. return (
  198. <div ref={rootRef}>
  199. <input aria-label="Find" value={query} onChange={(event) => setQuery(event.target.value)} />
  200. <output data-testid="find-count">{matches.matchCount}</output>
  201. <button
  202. onClick={() =>
  203. setSource((old) =>
  204. old.map((row) =>
  205. row.kind === "assistantText" && row.turnId === "turn-0"
  206. ? { ...row, text: "revised alpha alpha" }
  207. : row,
  208. ),
  209. )
  210. }
  211. >
  212. Revise history
  213. </button>
  214. {source.flatMap((row) =>
  215. row.kind === "assistantText"
  216. ? [
  217. <p key={row.rowId} data-row-id={row.rowId}>
  218. {
  219. projectAssistantCodeComments(row.text, { streaming: row.state === "streaming" })
  220. .visibleText
  221. }
  222. </p>,
  223. ]
  224. : [],
  225. )}
  226. </div>
  227. );
  228. }
  229. function SearchNavigation() {
  230. const source = useMemo(
  231. () =>
  232. rows
  233. .slice(0, 72)
  234. .map((row) =>
  235. row.kind === "assistantText" && row.turnId === "turn-0"
  236. ? { ...row, text: "**needle**\n\n[needle link](https://example.com/hidden-target)" }
  237. : row,
  238. ),
  239. [],
  240. );
  241. const select = useMemo(() => createConversationTurnRenderUnitsSelector(), []);
  242. const units = useMemo(() => select(getConversationRowsPartition(source), {}), [select, source]);
  243. const unitCount = units.history.length + units.tail.length;
  244. const rootRef = useRef<HTMLDivElement>(null);
  245. const [query, setQuery] = useState("");
  246. const [requestId, setRequestId] = useState(1);
  247. const [mountTarget, setMountTarget] = useState(params.get("hold") !== "1");
  248. const [matchCount, setMatchCount] = useState(0);
  249. const scrollCalls = useRef<number[]>([]);
  250. const doneRequests = useRef<number[]>([]);
  251. const virtualizer = useVirtualizer({
  252. count: unitCount,
  253. getScrollElement: () => rootRef.current,
  254. estimateSize: () => 300,
  255. overscan: 1,
  256. });
  257. const items = virtualizer.getVirtualItems();
  258. const external = params.get("entry") === "result";
  259. const request = useMemo(
  260. () =>
  261. external && query
  262. ? {
  263. requestId,
  264. query,
  265. taskId: "find-regression",
  266. workspacePath: workspace,
  267. }
  268. : null,
  269. [external, query, requestId],
  270. );
  271. const scrollToUnit = useCallback(
  272. (index: number) => {
  273. scrollCalls.current.push(index);
  274. const offset = virtualizer.getOffsetForIndex(index, "start")?.[0];
  275. if (offset !== undefined) rootRef.current?.scrollTo({ top: offset });
  276. },
  277. [virtualizer],
  278. );
  279. useConversationTimelineFind({
  280. rootRef,
  281. renderUnits: units,
  282. rows: source,
  283. mountedRowsKey: `${mountTarget}:${items.map((item) => `${item.index}:${item.size}`).join(":")}`,
  284. isMountedLayoutMeasured: useCallback(
  285. () =>
  286. virtualizer.getVirtualItems().every((item) => {
  287. const node = virtualizer.elementsCache.get(item.key);
  288. return node?.isConnected && node.getBoundingClientRect().height === item.size;
  289. }),
  290. [virtualizer],
  291. ),
  292. canLoadOlder: false,
  293. loadingOlder: false,
  294. conversationFindQuery: external ? "" : query,
  295. conversationFindActiveIndex: 0,
  296. conversationFindNavigationRequestId: requestId,
  297. onConversationFindMatchStateChange: useCallback(
  298. (state: ConversationFindMatchState) => setMatchCount(state.matchCount),
  299. [],
  300. ),
  301. searchResultHighlightRequest: request,
  302. onSearchResultHighlightDone: useCallback((id: number) => {
  303. doneRequests.current.push(id);
  304. }, []),
  305. scrollToUnit,
  306. });
  307. Object.assign(window, {
  308. __findNavigation: {
  309. snapshot: () => ({
  310. calls: [...scrollCalls.current],
  311. done: [...doneRequests.current],
  312. requestId,
  313. }),
  314. },
  315. });
  316. return (
  317. <main>
  318. <input aria-label="Find" value={query} onChange={(event) => setQuery(event.target.value)} />
  319. <button onClick={() => setRequestId((id) => id + 1)}>Navigate again</button>
  320. <button onClick={() => setMountTarget(true)}>Mount target</button>
  321. <output data-testid="find-count">{matchCount}</output>
  322. <div ref={rootRef} data-testid="find-scroll" style={{ height: 400, overflow: "auto" }}>
  323. <div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
  324. {items.map((item) => (
  325. <div
  326. key={item.key}
  327. data-index={item.index}
  328. ref={virtualizer.measureElement}
  329. style={{
  330. position: "absolute",
  331. top: 0,
  332. width: "100%",
  333. height: 300,
  334. transform: `translateY(${item.start}px)`,
  335. }}
  336. >
  337. {(item.index !== 0 || mountTarget) && (
  338. <div data-row-id={item.index * 3 + 3}>
  339. <Streamdown mode="static">
  340. {
  341. (
  342. source[item.index * 3 + 2] as Extract<
  343. ConversationRow,
  344. { kind: "assistantText" }
  345. >
  346. ).text
  347. }
  348. </Streamdown>
  349. </div>
  350. )}
  351. </div>
  352. ))}
  353. </div>
  354. </div>
  355. </main>
  356. );
  357. }
  358. createRoot(document.getElementById("root")!).render(
  359. <ZCodeIntlProvider initialLocale="en-US">
  360. <TooltipProvider>
  361. {params.get("mode") === "draft" ? (
  362. <DraftOwner />
  363. ) : params.get("mode") === "find-navigation" ? (
  364. <AssistantCodeCommentFeatureProvider enabled>
  365. <SearchNavigation />
  366. </AssistantCodeCommentFeatureProvider>
  367. ) : params.get("mode") === "find" ? (
  368. <AssistantCodeCommentFeatureProvider enabled>
  369. <Search />
  370. </AssistantCodeCommentFeatureProvider>
  371. ) : (
  372. <Navigation />
  373. )}
  374. </TooltipProvider>
  375. </ZCodeIntlProvider>,
  376. );