message-render-isolation.fixture.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. import { useMemo, useState, useSyncExternalStore } from "react";
  2. import { createRoot } from "react-dom/client";
  3. import { useShallow } from "zustand/react/shallow";
  4. import { shallow } from "zustand/shallow";
  5. import type { ConversationRow, ToolCallRow } from "@zcode/shared/zcode-protocol-v4";
  6. import { TooltipProvider } from "@/components/ui/tooltip.js";
  7. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  8. import { DEFAULT_CODE_PREVIEW_SETTINGS } from "@/lib/codePreviewSettings.js";
  9. import { ConversationTurnGroup } from "@/v4/ConversationTurnGroup.js";
  10. import {
  11. buildConversationTurnRenderUnits,
  12. createConversationTurnRenderUnitsSelector,
  13. } from "@/v4/conversationTurnRenderUnits.js";
  14. import { getConversationRowsPartition } from "@/v4/conversationProjectionStore.js";
  15. import {
  16. selectWorkflowJoinRows,
  17. buildWorkflowGraphByToolCallId,
  18. buildWorkflowFillGraphByRunId,
  19. buildWorkflowSaveCandidatesByRunId,
  20. } from "@/v4/workflowRunCardJoin.js";
  21. import { buildWorkflowDraftByToolCallId } from "@/v4/workflowDraftJoin.js";
  22. import {
  23. createTaskFindNavigationState,
  24. changeTaskFindSelection,
  25. navigateTaskFindSelection,
  26. } from "@/quickpick/taskFindNavigationState.js";
  27. import {
  28. getPluginUiDisclosureSnapshot,
  29. setPluginUiManualPin,
  30. subscribePluginUiDisclosure,
  31. } from "@/plugin-ui/app/pluginUiDisclosureStore.js";
  32. import { deriveLogicalUiInstances } from "@/plugin-ui/index.js";
  33. import { toolCallCreateWorkflowDisplaySchema } from "@zcode/shared/zcode-protocol-v4";
  34. import * as highspeed from "@/highspeed/highspeedTurnStore.js";
  35. import "@/styles.css";
  36. const query = new URLSearchParams(location.search);
  37. const mobile = query.get("mobile") === "true";
  38. const theme = query.get("theme") === "light" ? "light" : "dark";
  39. document.documentElement.className = `${theme} theme-zai-${theme}`;
  40. const start = 1_700_000_000_000;
  41. const context = {
  42. workspacePath: "/fixture",
  43. theme,
  44. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  45. compactForRemoteControl: mobile,
  46. } as const;
  47. const onFeedback = () => undefined;
  48. function turn(turnId: string, index: number, running = false): ConversationRow[] {
  49. const base = { turnId, createdAt: start, createdAtSeq: index * 3 + 1 };
  50. return [
  51. {
  52. ...base,
  53. rowId: index * 3 + 1,
  54. kind: "turnHeader",
  55. origin: "userInput",
  56. sourceCommandId: `${turnId}-command`,
  57. state: running ? "running" : "completedSuccess",
  58. startedAt: start,
  59. ...(!running ? { endedAt: start + 1000, activeMs: 1000 } : {}),
  60. },
  61. {
  62. ...base,
  63. rowId: index * 3 + 2,
  64. kind: "userInput",
  65. origin: "realUser",
  66. text: `input ${turnId}`,
  67. },
  68. {
  69. ...base,
  70. rowId: index * 3 + 3,
  71. kind: "assistantText",
  72. entityId: `text-${turnId}`,
  73. text: running ? "stream 0" : `answer ${turnId}`,
  74. state: running ? "streaming" : "complete",
  75. },
  76. ];
  77. }
  78. const initial = [...turn("history-0", 0), ...turn("history-1", 1), ...turn("active", 2, true)];
  79. function check(condition: unknown, label: string): asserts condition {
  80. if (!condition) throw new Error(label);
  81. }
  82. function equal(a: unknown, b: unknown, label: string) {
  83. const serialize = (value: unknown) =>
  84. JSON.stringify(value, (_key, item) => (item instanceof Map ? [...item] : item));
  85. check(serialize(a) === serialize(b), label);
  86. }
  87. function boundaryChecks() {
  88. const evidence: string[] = [];
  89. // 以原纯构建器为值语义对照,跨行种类、终态、隐藏行与窗口变化;不把引用相等当业务正确。
  90. const select = createConversationTurnRenderUnitsSelector();
  91. const compare = (rows: ConversationRow[], options = {}) => {
  92. // selector 输出按「历史 + 尾轮」分区;拼平后与整窗纯构建器逐项对照。
  93. const partition = select(getConversationRowsPartition(rows), {
  94. nowMs: start + 5000,
  95. ...options,
  96. });
  97. const actual = [...partition.history, ...partition.tail];
  98. equal(
  99. actual,
  100. buildConversationTurnRenderUnits(rows, { nowMs: start + 5000, ...options }),
  101. "turn value parity",
  102. );
  103. return actual;
  104. };
  105. let rows = initial;
  106. const old = compare(rows);
  107. rows = rows.map((r) =>
  108. r.kind === "assistantText" && r.turnId === "active" ? { ...r, text: "changed" } : r,
  109. );
  110. const changed = compare(rows);
  111. check(old[0] === changed[0] && old[2] !== changed[2], "turn identity boundary");
  112. for (const state of ["completedSuccess", "completedInterrupted", "failed"] as const)
  113. compare(
  114. rows.map((r) => (r.kind === "turnHeader" && r.turnId === "active" ? { ...r, state } : r)),
  115. );
  116. compare(
  117. rows.filter((r) => r.kind !== "turnHeader"),
  118. { sessionPhase: "completedInterrupted" },
  119. );
  120. compare([...turn("prepended", 4), ...rows]);
  121. compare(rows.slice(3));
  122. compare([]);
  123. compare(initial);
  124. const plugin = {
  125. ...rows[0],
  126. rowId: 90,
  127. kind: "toolCall",
  128. toolCallId: "plugin",
  129. toolName: "mcp__fixture__view",
  130. status: "success",
  131. display: { kind: "mcp_tool", ui: { resourceUri: "ui://fixture/view" } },
  132. } as ToolCallRow;
  133. const pinned = compare([...rows, plugin], {
  134. pluginUiPinResolver: () => ({ manualPinned: true }),
  135. });
  136. const unpinned = compare([...rows, plugin], {
  137. pluginUiPinResolver: () => ({ manualPinned: false }),
  138. });
  139. check(pinned[0] !== unpinned[0], "pin changes historical unit");
  140. const recent = [...rows, plugin];
  141. const derive = (input: ConversationRow[]) => {
  142. const disposition = deriveLogicalUiInstances(input).byToolCallId;
  143. return compare(input, {
  144. pluginUiPinResolver: (id: string) => ({ disposition: disposition[id] }),
  145. });
  146. };
  147. const recentThree = derive(recent);
  148. const outsideRecentThree = derive([...recent, ...turn("fourth", 4)]);
  149. check(
  150. recentThree[0] !== outsideRecentThree[0],
  151. "recent-three plugin boundary updates historical unit",
  152. );
  153. const cardMeta = {
  154. schemaVersion: 1 as const,
  155. cardId: "persisted",
  156. taskId: "fixture",
  157. provider: "fixture",
  158. model: "fixture",
  159. issuedAt: start,
  160. expiresAt: start + 6000,
  161. outputTokens: 100,
  162. regularTps: 10,
  163. highspeedTps: 50,
  164. };
  165. const cardRows = initial.map((r) => (r.kind === "userInput" ? { ...r, highspeed: cardMeta } : r));
  166. compare(cardRows);
  167. const expired = compare(cardRows, { nowMs: start + 7000 });
  168. check(
  169. expired.filter((u) => u.showHighspeedOutputFooter).length === 1 &&
  170. expired.at(-1)?.showHighspeedOutputFooter,
  171. "one footer at last card turn",
  172. );
  173. compare(cardRows.slice(0, 6), { nowMs: start + 8000 });
  174. evidence.push(
  175. "turn parity, completion, interruption, missing header, prepend, trim, pin, footer expiry and movement",
  176. );
  177. const graph = {
  178. steps: [{ id: "step", kind: "ask", label: "step", lane: "worker" }],
  179. lanes: [{ id: "worker" }],
  180. participants: [],
  181. handoffs: [],
  182. };
  183. const tool = (toolName: string, id: number, extra = {}) =>
  184. ({
  185. turnId: "workflow",
  186. createdAt: start,
  187. createdAtSeq: id,
  188. rowId: id,
  189. kind: "toolCall",
  190. toolCallId: `tool-${id}`,
  191. toolName,
  192. status: "success",
  193. inputText: "{}",
  194. ...extra,
  195. }) as ToolCallRow;
  196. const create = tool("CreateWorkflow", 100, {
  197. display: {
  198. kind: "create_workflow",
  199. ok: false,
  200. errorCount: 0,
  201. diagnostics: [],
  202. causalityGraph: graph,
  203. },
  204. });
  205. const amend = tool("AmendWorkflow", 101, { input: { run_id: "run" } });
  206. const fill = tool("FillWorkflowHole", 102, {
  207. input: { run_id: "run", hole_id: "hole", name: "fill" },
  208. display: {
  209. kind: "create_workflow",
  210. ok: true,
  211. errorCount: 0,
  212. diagnostics: [],
  213. causalityGraph: graph,
  214. },
  215. });
  216. const save = tool("SaveWorkflow", 103, {
  217. input: { run_id: "run", name: "saved", scope: "project" },
  218. });
  219. const launch = {
  220. ...turn("launch", 40)[0],
  221. workflowLaunch: {
  222. toolCallId: "launch",
  223. runId: "launch-run",
  224. display: {
  225. kind: "create_workflow",
  226. ok: true,
  227. errorCount: 0,
  228. diagnostics: [],
  229. causalityGraph: graph,
  230. },
  231. },
  232. } as ConversationRow;
  233. toolCallCreateWorkflowDisplaySchema.parse(create.display);
  234. toolCallCreateWorkflowDisplaySchema.parse(fill.display);
  235. const relevant = [create, amend, fill, save, launch];
  236. const selected = selectWorkflowJoinRows([...initial, ...relevant]);
  237. check(
  238. shallow(selected, selectWorkflowJoinRows([...rows, ...relevant])),
  239. "text must retain workflow dependencies",
  240. );
  241. const builders = [
  242. buildWorkflowGraphByToolCallId,
  243. buildWorkflowFillGraphByRunId,
  244. buildWorkflowDraftByToolCallId,
  245. buildWorkflowSaveCandidatesByRunId,
  246. ];
  247. for (const input of [
  248. relevant,
  249. relevant.slice(1),
  250. relevant.slice(0, 3),
  251. [create, { ...create, rowId: 104, toolCallId: "next" }],
  252. relevant.map((r) => (r.kind === "toolCall" ? { ...r, status: "running" as const } : r)),
  253. ])
  254. for (const build of builders)
  255. equal(
  256. [...build(selectWorkflowJoinRows([...initial, ...input]))],
  257. [...build([...initial, ...input])],
  258. "workflow filtered parity",
  259. );
  260. check(buildWorkflowGraphByToolCallId(selected).size >= 1, "nonempty graph");
  261. check(buildWorkflowFillGraphByRunId(selected).size === 1, "fill reached join");
  262. check(
  263. buildWorkflowSaveCandidatesByRunId(selected).get("run")?.[0]?.name === "saved",
  264. "save reached join",
  265. );
  266. evidence.push("nonempty workflow graph, draft, amend, fill, save, launch and removal");
  267. let find = createTaskFindNavigationState();
  268. find = changeTaskFindSelection(find, "answer", 0);
  269. const next = navigateTaskFindSelection(find, "answer", 0);
  270. check(next.navigationRequestId === find.navigationRequestId + 1, "single result navigation");
  271. check(changeTaskFindSelection(next, "answer", 1).activeIndex === 1, "selection changes");
  272. evidence.push("explicit find navigation; passive callback covered by native App probe");
  273. return evidence;
  274. }
  275. let scopeRenders = 0;
  276. function ScopeConsumer() {
  277. scopeRenders++;
  278. const select = useShallow(highspeed.getHighspeedSessionDependencies);
  279. const data = useSyncExternalStore(highspeed.subscribeHighspeedTurns, () => select("current"));
  280. const pins = useSyncExternalStore(subscribePluginUiDisclosure, () =>
  281. getPluginUiDisclosureSnapshot("current"),
  282. );
  283. return (
  284. <output data-testid="scope">
  285. {data.length}:{pins.size}
  286. </output>
  287. );
  288. }
  289. async function scopeChecks() {
  290. const settle = () =>
  291. new Promise<void>((r) => requestAnimationFrame(() => requestAnimationFrame(() => r())));
  292. const record = (sessionId: string, sourceCommandId: string, cardId: string) =>
  293. highspeed.recordHighspeedTurn({
  294. sessionId,
  295. sourceCommandId,
  296. createdAt: start,
  297. card: {
  298. cardId,
  299. taskId: sessionId,
  300. provider: "fixture",
  301. model: "fixture",
  302. issuedAt: start,
  303. expiresAt: start + 1000,
  304. regularTps: 10,
  305. },
  306. });
  307. const groupCounts = () => ({
  308. ...(window as unknown as { __turnRenders: Record<string, number> }).__turnRenders,
  309. });
  310. const initialGroups = groupCounts();
  311. let before = scopeRenders;
  312. setPluginUiManualPin("other", "tool", true);
  313. record("other", "other", "other-card");
  314. await settle();
  315. check(scopeRenders === before, "unrelated stores skip");
  316. equal(groupCounts(), initialGroups, "unrelated Highspeed update skips real turn groups");
  317. setPluginUiManualPin("current", "tool", true);
  318. await settle();
  319. check(scopeRenders > before, "current pin updates");
  320. record("current", "history-1-command", "shared");
  321. await settle();
  322. before = scopeRenders;
  323. record("other", "shared-other", "shared");
  324. await settle();
  325. check(scopeRenders > before, "same card across sessions updates");
  326. before = scopeRenders;
  327. highspeed.completeHighspeedTurn({
  328. sourceCommandId: "shared-other",
  329. outputTokens: 250,
  330. durationMs: 1000,
  331. });
  332. await settle();
  333. check(
  334. scopeRenders > before && highspeed.aggregateHighspeedCardMetrics("shared").outputTokens === 250,
  335. "same card completion",
  336. );
  337. before = scopeRenders;
  338. highspeed.setHighspeedCardTps("shared", 80);
  339. await settle();
  340. check(
  341. scopeRenders > before && highspeed.aggregateHighspeedCardMetrics("shared").highspeedTps === 80,
  342. "TPS updates",
  343. );
  344. check(
  345. (groupCounts()["history-1"] ?? 0) > (initialGroups["history-1"] ?? 0),
  346. "related real group receives Highspeed changes",
  347. );
  348. before = scopeRenders;
  349. highspeed.hydrateHighspeedTurnsFromTranscript("current", [
  350. {
  351. sourceCommandId: "history-1-command",
  352. createdAt: start,
  353. highspeed: {
  354. schemaVersion: 1,
  355. cardId: "shared",
  356. taskId: "current",
  357. provider: "fixture",
  358. model: "fixture",
  359. issuedAt: start,
  360. expiresAt: start + 1000,
  361. outputTokens: 50,
  362. durationMs: 500,
  363. regularTps: 10,
  364. highspeedTps: 80,
  365. savedDurationMs: 4500,
  366. },
  367. },
  368. ]);
  369. await settle();
  370. check(
  371. scopeRenders > before &&
  372. highspeed.getHighspeedTurnByCommandId("history-1-command")?.metricsPersistedAt !== undefined,
  373. "hydration and persisted metrics update",
  374. );
  375. before = scopeRenders;
  376. highspeed.discardHighspeedTurn("shared-other");
  377. await settle();
  378. check(
  379. scopeRenders > before && highspeed.aggregateHighspeedCardMetrics("shared").outputTokens === 50,
  380. "removal updates",
  381. );
  382. before = scopeRenders;
  383. for (let i = 0; i < 301; i++) record("other", `evict-${i}`, "other-card");
  384. await settle();
  385. check(
  386. scopeRenders > before && !highspeed.getHighspeedTurnByCommandId("history-1-command"),
  387. "bounded store eviction updates",
  388. );
  389. return "scoped subscriptions: unrelated skip, current pin, shared card completion, TPS, hydration, removal, eviction";
  390. }
  391. function Fixture() {
  392. const [rows, setRows] = useState(initial);
  393. const [nowMs, setNow] = useState(start + 2000);
  394. const [checks, setChecks] = useState("pending");
  395. const [evidence, setEvidence] = useState<string[]>([]);
  396. const select = useMemo(() => createConversationTurnRenderUnitsSelector(), []);
  397. const partition = select(getConversationRowsPartition(rows), { nowMs });
  398. const units = [...partition.history, ...partition.tail];
  399. return (
  400. <>
  401. <nav>
  402. <button
  403. data-testid="stream"
  404. onClick={() =>
  405. setRows((previous) =>
  406. previous.map((r) =>
  407. r.kind === "assistantText" && r.turnId === "active"
  408. ? { ...r, text: `stream ${Number(r.text.split(" ")[1]) + 1}` }
  409. : r,
  410. ),
  411. )
  412. }
  413. >
  414. Stream
  415. </button>
  416. <button data-testid="clock" onClick={() => setNow((n) => n + 1000)}>
  417. Clock
  418. </button>
  419. <button
  420. data-testid="complete"
  421. onClick={() =>
  422. setRows((previous) =>
  423. previous.map((r) =>
  424. r.turnId !== "active"
  425. ? r
  426. : r.kind === "turnHeader"
  427. ? { ...r, state: "completedSuccess", endedAt: nowMs }
  428. : r.kind === "assistantText"
  429. ? { ...r, state: "complete" }
  430. : r,
  431. ),
  432. )
  433. }
  434. >
  435. Complete
  436. </button>
  437. <button
  438. data-testid="append"
  439. onClick={() => setRows((previous) => [...previous, ...turn("new", 3, true)])}
  440. >
  441. Append
  442. </button>
  443. <button
  444. data-testid="trim"
  445. onClick={() => setRows((previous) => previous.filter((r) => r.turnId !== "history-0"))}
  446. >
  447. Trim
  448. </button>
  449. <button
  450. data-testid="assert-boundaries"
  451. onClick={async () => {
  452. try {
  453. const result = boundaryChecks();
  454. result.push(await scopeChecks());
  455. setEvidence(result);
  456. setChecks("passed");
  457. } catch (error) {
  458. setChecks(String(error));
  459. }
  460. }}
  461. >
  462. Check boundaries
  463. </button>
  464. <output data-testid="checks">{checks}</output>
  465. <output data-testid="evidence">{JSON.stringify(evidence)}</output>
  466. <ScopeConsumer />
  467. </nav>
  468. <main className="min-h-dvh bg-background text-foreground @container/conversation">
  469. {units.map((unit) => (
  470. <ConversationTurnGroup
  471. key={unit.key}
  472. unit={unit}
  473. nowMs={unit.isRunning ? nowMs : undefined}
  474. context={context}
  475. onFeedbackChange={onFeedback}
  476. />
  477. ))}
  478. </main>
  479. </>
  480. );
  481. }
  482. createRoot(document.getElementById("root")!).render(
  483. <TooltipProvider>
  484. <ZCodeIntlProvider initialLocale={mobile ? "en-US" : "zh-CN"}>
  485. <Fixture />
  486. </ZCodeIntlProvider>
  487. </TooltipProvider>,
  488. );