v4ConversationFileSummaryPanel.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. import { act, createElement } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { renderToStaticMarkup } from "react-dom/server";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import type {
  6. TurnHeaderRow,
  7. V4ConversationFileChangesResult,
  8. } from "@zcode/shared/zcode-protocol-v4";
  9. import { DEFAULT_CODE_PREVIEW_SETTINGS } from "@/lib/codePreviewSettings.js";
  10. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  11. import { ConversationFileSummaryPanel } from "@/v4/ConversationFileSummaryPanel.js";
  12. import type { ConversationRowRenderContext } from "@/v4/conversationRowContext.js";
  13. const { collapsibleOpenChanges, openSplitButtonProps } = vi.hoisted(() => ({
  14. collapsibleOpenChanges: [] as Array<(open: boolean) => void>,
  15. openSplitButtonProps: [] as Array<Record<string, unknown>>,
  16. }));
  17. vi.mock("@/components/ui/collapsible.js", async () => {
  18. const React = await import("react");
  19. return {
  20. Collapsible: ({
  21. children,
  22. className,
  23. onOpenChange,
  24. }: {
  25. children?: React.ReactNode;
  26. className?: string;
  27. onOpenChange?: (open: boolean) => void;
  28. }) => {
  29. if (onOpenChange) collapsibleOpenChanges.push(onOpenChange);
  30. return React.createElement("div", { className, "data-slot": "collapsible" }, children);
  31. },
  32. CollapsibleContent: ({ children }: { children?: React.ReactNode }) =>
  33. React.createElement("div", { "data-slot": "collapsible-content" }, children),
  34. CollapsibleTrigger: ({ children }: { children?: React.ReactNode }) =>
  35. React.createElement(React.Fragment, null, children),
  36. };
  37. });
  38. vi.mock("@/OpenSplitButton.js", async () => {
  39. const React = await import("react");
  40. return {
  41. OpenSplitButton: (props: Record<string, unknown>) => {
  42. openSplitButtonProps.push(props);
  43. return React.createElement("button", { type: "button" }, "打开");
  44. },
  45. };
  46. });
  47. function header(overrides: Partial<TurnHeaderRow> = {}): TurnHeaderRow {
  48. return {
  49. rowId: 1,
  50. entityId: "turn-header-1",
  51. turnId: "turn-1",
  52. createdAt: 1_700_000_000_000,
  53. createdAtSeq: 1,
  54. kind: "turnHeader",
  55. origin: "userInput",
  56. state: "completedSuccess",
  57. startedAt: 1_700_000_000_000,
  58. actions: { canRewindFiles: true },
  59. fileChanges: {
  60. files: 1,
  61. additions: 11,
  62. deletions: 0,
  63. state: "active",
  64. },
  65. ...overrides,
  66. };
  67. }
  68. function renderPanel(contextOverrides: Partial<ConversationRowRenderContext> = {}) {
  69. const context: ConversationRowRenderContext = {
  70. workspacePath: "/workspace",
  71. theme: "system",
  72. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  73. fetchFileChanges: async () => ({
  74. files: 1,
  75. additions: 11,
  76. deletions: 0,
  77. items: [
  78. {
  79. path: "/workspace/input.html",
  80. additions: 11,
  81. deletions: 0,
  82. writeCount: 1,
  83. toolNames: ["Write"],
  84. patches: [
  85. {
  86. oldStart: 1,
  87. oldLines: 0,
  88. newStart: 1,
  89. newLines: 11,
  90. lines: ["+<html>"],
  91. },
  92. ],
  93. },
  94. ],
  95. }),
  96. ...contextOverrides,
  97. };
  98. return renderToStaticMarkup(
  99. createElement(
  100. ZCodeIntlProvider,
  101. { initialLocale: "zh-CN" },
  102. createElement(ConversationFileSummaryPanel, {
  103. header: header(),
  104. context,
  105. }),
  106. ),
  107. );
  108. }
  109. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  110. const element = {
  111. addEventListener: () => {},
  112. appendChild: (child: Node) => {
  113. Object.assign(child, { parentNode: element });
  114. element.childNodes.push(child);
  115. return child;
  116. },
  117. childNodes: [] as Node[],
  118. getAttribute: (name: string) => element.attributes.get(name) ?? null,
  119. insertBefore: (child: Node, beforeChild?: Node | null) => {
  120. Object.assign(child, { parentNode: element });
  121. const beforeIndex = beforeChild ? element.childNodes.indexOf(beforeChild) : -1;
  122. if (beforeIndex >= 0) {
  123. element.childNodes.splice(beforeIndex, 0, child);
  124. } else {
  125. element.childNodes.push(child);
  126. }
  127. return child;
  128. },
  129. attributes: new Map<string, string>(),
  130. nodeName: tagName.toUpperCase(),
  131. nodeType: 1,
  132. ownerDocument,
  133. parentNode: null as Node | null,
  134. removeAttribute: (name: string) => {
  135. element.attributes.delete(name);
  136. },
  137. removeChild: (child: Node) => {
  138. element.childNodes = element.childNodes.filter((item) => item !== child);
  139. Object.assign(child, { parentNode: null });
  140. return child;
  141. },
  142. removeEventListener: () => {},
  143. setAttribute: (name: string, value: string) => {
  144. element.attributes.set(name, String(value));
  145. },
  146. style: {},
  147. tagName: tagName.toUpperCase(),
  148. };
  149. return element as unknown as Element;
  150. }
  151. function installMinimalDom() {
  152. const documentMock = {
  153. addEventListener: () => {},
  154. createComment: (nodeValue: string) => ({
  155. nodeType: 8,
  156. nodeValue,
  157. parentNode: null,
  158. }),
  159. createElement: (tagName: string) =>
  160. createMinimalElement(documentMock as unknown as Document, tagName),
  161. createElementNS: (_namespace: string, tagName: string) =>
  162. createMinimalElement(documentMock as unknown as Document, tagName),
  163. createTextNode: (nodeValue: string) => ({
  164. nodeType: 3,
  165. nodeValue,
  166. parentNode: null,
  167. }),
  168. nodeType: 9,
  169. removeEventListener: () => {},
  170. } as unknown as Document & { defaultView?: unknown };
  171. const windowMock = {
  172. addEventListener: () => {},
  173. document: documentMock,
  174. HTMLIFrameElement: function HTMLIFrameElement() {},
  175. HTMLElement: function HTMLElement() {},
  176. Node: function Node() {},
  177. removeEventListener: () => {},
  178. requestAnimationFrame: (callback: FrameRequestCallback) => {
  179. callback(0);
  180. return 0;
  181. },
  182. };
  183. documentMock.defaultView = windowMock;
  184. Object.defineProperty(globalThis, "document", {
  185. configurable: true,
  186. value: documentMock,
  187. });
  188. Object.defineProperty(globalThis, "window", {
  189. configurable: true,
  190. value: windowMock,
  191. });
  192. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  193. configurable: true,
  194. value: true,
  195. });
  196. return createMinimalElement(documentMock, "div");
  197. }
  198. function collectText(node: unknown): string {
  199. if (!node || typeof node !== "object") return "";
  200. const candidate = node as {
  201. childNodes?: unknown[];
  202. nodeValue?: string;
  203. textContent?: string;
  204. };
  205. if (typeof candidate.nodeValue === "string") return candidate.nodeValue;
  206. if (candidate.childNodes && candidate.childNodes.length > 0) {
  207. return candidate.childNodes.map((child) => collectText(child)).join("");
  208. }
  209. return typeof candidate.textContent === "string" ? candidate.textContent : "";
  210. }
  211. function collectClassNames(node: unknown): string[] {
  212. if (!node || typeof node !== "object") return [];
  213. const candidate = node as {
  214. attributes?: Map<string, string>;
  215. childNodes?: unknown[];
  216. };
  217. const ownClassName = candidate.attributes?.get("class");
  218. return [
  219. ...(ownClassName ? [ownClassName] : []),
  220. ...(candidate.childNodes?.flatMap((child) => collectClassNames(child)) ?? []),
  221. ];
  222. }
  223. afterEach(() => {
  224. collapsibleOpenChanges.length = 0;
  225. openSplitButtonProps.length = 0;
  226. delete (globalThis as { document?: unknown }).document;
  227. delete (globalThis as { window?: unknown }).window;
  228. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  229. });
  230. describe("ConversationFileSummaryPanel", () => {
  231. it.each([false, true])(
  232. "visualize 混合摘要只统计普通文件,compact=%s",
  233. async (compactForRemoteControl) => {
  234. const container = installMinimalDom();
  235. const root = createRoot(container);
  236. const path = "/workspace/visualizations/calendar.html";
  237. const fetchFileChanges = vi.fn(async () => ({
  238. files: 2,
  239. additions: 77,
  240. deletions: 3,
  241. items: [
  242. { path, additions: 70, deletions: 1, patches: [] },
  243. { path: "/workspace/app.ts", additions: 7, deletions: 2, patches: [] },
  244. ],
  245. }));
  246. await act(async () => {
  247. root.render(
  248. createElement(
  249. ZCodeIntlProvider,
  250. { initialLocale: "zh-CN" },
  251. createElement(ConversationFileSummaryPanel, {
  252. header: header({
  253. fileChanges: { files: 2, additions: 77, deletions: 3, state: "active" },
  254. }),
  255. assistantText: `::visualize${JSON.stringify({ path })}`,
  256. context: {
  257. workspacePath: "/workspace",
  258. theme: "system",
  259. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  260. compactForRemoteControl,
  261. fetchFileChanges,
  262. },
  263. }),
  264. ),
  265. );
  266. });
  267. expect(fetchFileChanges).toHaveBeenCalledTimes(1);
  268. expect(collectText(container)).toContain("1 个文件已更改");
  269. expect(collectText(container)).toContain("+7");
  270. expect(collectText(container)).toContain("-2");
  271. expect(collectText(container)).not.toContain("+77");
  272. await act(async () => collapsibleOpenChanges.at(-1)?.(true));
  273. expect(collectText(container)).toContain("app.ts");
  274. expect(collectText(container)).not.toContain("calendar.html");
  275. await act(async () => root.unmount());
  276. },
  277. );
  278. it("仅有 visualize 时,详情到达前后都不显示摘要", async () => {
  279. const container = installMinimalDom();
  280. const root = createRoot(container);
  281. const path = "/workspace/calendar.html";
  282. const pending = Promise.withResolvers<V4ConversationFileChangesResult>();
  283. await act(async () => {
  284. root.render(
  285. createElement(
  286. ZCodeIntlProvider,
  287. { initialLocale: "zh-CN" },
  288. createElement(ConversationFileSummaryPanel, {
  289. header: header(),
  290. assistantText: `::visualize${JSON.stringify({ path })}`,
  291. context: {
  292. workspacePath: "/workspace",
  293. theme: "system",
  294. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  295. fetchFileChanges: () => pending.promise,
  296. },
  297. }),
  298. ),
  299. );
  300. });
  301. expect(collectText(container)).toBe("");
  302. await act(async () =>
  303. pending.resolve({
  304. items: [{ path, additions: 11, deletions: 0, patches: [] }],
  305. }),
  306. );
  307. expect(collectText(container)).toBe("");
  308. await act(async () => root.unmount());
  309. });
  310. it("切换轮次后不接受旧请求晚到的详情", async () => {
  311. const container = installMinimalDom();
  312. const root = createRoot(container);
  313. const path = "/workspace/calendar.html";
  314. const first = Promise.withResolvers<V4ConversationFileChangesResult>();
  315. const second = Promise.withResolvers<V4ConversationFileChangesResult>();
  316. const fetchFileChanges = vi
  317. .fn()
  318. .mockReturnValueOnce(first.promise)
  319. .mockReturnValueOnce(second.promise);
  320. const context: ConversationRowRenderContext = {
  321. workspacePath: "/workspace",
  322. theme: "system",
  323. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  324. fetchFileChanges,
  325. };
  326. const render = (rowId: number) =>
  327. createElement(
  328. ZCodeIntlProvider,
  329. { initialLocale: "zh-CN" },
  330. createElement(ConversationFileSummaryPanel, {
  331. header: header({ rowId, entityId: `header-${rowId}` }),
  332. context,
  333. assistantText: `::visualize${JSON.stringify({ path })}`,
  334. }),
  335. );
  336. await act(async () => root.render(render(1)));
  337. await act(async () => root.render(render(2)));
  338. await act(async () =>
  339. first.resolve({ items: [{ path: "/workspace/old.ts", additions: 999, patches: [] }] }),
  340. );
  341. expect(collectText(container)).toBe("");
  342. await act(async () =>
  343. second.resolve({
  344. items: [
  345. { path, additions: 70, patches: [] },
  346. { path: "/workspace/new.ts", additions: 7, deletions: 2, patches: [] },
  347. ],
  348. }),
  349. );
  350. expect(collectText(container)).toContain("+7");
  351. expect(collectText(container)).not.toContain("999");
  352. await act(async () => root.unmount());
  353. });
  354. it("详情失败时保留原摘要,展开可重试过滤", async () => {
  355. const container = installMinimalDom();
  356. const root = createRoot(container);
  357. const path = "/workspace/calendar.html";
  358. const fetchFileChanges = vi
  359. .fn()
  360. .mockRejectedValueOnce(new Error("fixture read failure"))
  361. .mockResolvedValueOnce({ items: [{ path, additions: 11, deletions: 0, patches: [] }] });
  362. await act(async () =>
  363. root.render(
  364. createElement(
  365. ZCodeIntlProvider,
  366. { initialLocale: "zh-CN" },
  367. createElement(ConversationFileSummaryPanel, {
  368. header: header(),
  369. assistantText: `::visualize${JSON.stringify({ path })}`,
  370. context: {
  371. workspacePath: "/workspace",
  372. theme: "system",
  373. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  374. fetchFileChanges,
  375. },
  376. }),
  377. ),
  378. ),
  379. );
  380. expect(collectText(container)).toContain("1 个文件已更改");
  381. await act(async () => collapsibleOpenChanges.at(-1)?.(true));
  382. expect(fetchFileChanges).toHaveBeenCalledTimes(2);
  383. expect(collectText(container)).toBe("");
  384. await act(async () => root.unmount());
  385. });
  386. it("matches z-code-2 summary card visual shell", () => {
  387. const html = renderPanel();
  388. expect(html).toContain("rounded-xl border border-border bg-card shadow-none");
  389. expect(html).toContain("h-10 items-center justify-between");
  390. expect(html).toContain("transition-colors hover:bg-hover");
  391. expect(html).toContain("grid w-full border-t border-border");
  392. expect(html).not.toContain("FileText");
  393. });
  394. it("renders file rows and Open action after details are loaded", async () => {
  395. const container = installMinimalDom();
  396. const root: Root = createRoot(container);
  397. const context: ConversationRowRenderContext = {
  398. workspacePath: "/workspace",
  399. workspaceIdentity: "remote:ssh:host-a:/workspace",
  400. workspaceRemoteSessionId: "session-a",
  401. theme: "system",
  402. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  403. fetchFileChanges: async () => ({
  404. files: 1,
  405. additions: 11,
  406. deletions: 0,
  407. items: [
  408. {
  409. path: "/workspace/input.html",
  410. additions: 11,
  411. deletions: 0,
  412. writeCount: 2,
  413. toolNames: ["Write"],
  414. patches: [
  415. {
  416. oldStart: 1,
  417. oldLines: 0,
  418. newStart: 1,
  419. newLines: 11,
  420. lines: ["+<html>"],
  421. },
  422. ],
  423. },
  424. ],
  425. }),
  426. };
  427. await act(async () => {
  428. root.render(
  429. createElement(
  430. ZCodeIntlProvider,
  431. { initialLocale: "zh-CN" },
  432. createElement(ConversationFileSummaryPanel, {
  433. header: header(),
  434. context,
  435. }),
  436. ),
  437. );
  438. });
  439. expect(collectText(container)).toContain("1 个文件已更改");
  440. await act(async () => {
  441. collapsibleOpenChanges.at(-1)?.(true);
  442. await Promise.resolve();
  443. });
  444. const text = collectText(container);
  445. expect(text).toContain("input.html");
  446. expect(text).toContain("+11");
  447. expect(text).not.toContain("2 次修改");
  448. expect(text).toContain("审查");
  449. expect(text).toContain("打开");
  450. expect(collectClassNames(container)).toContain("w-full bg-background/50 overflow-hidden");
  451. expect(text).not.toContain("暂时无法预览这份 Diff。");
  452. expect(openSplitButtonProps.at(-1)).toMatchObject({
  453. hideOpenWithMenu: false,
  454. target: {
  455. previewSource: {
  456. workspacePath: "/workspace",
  457. workspaceIdentity: "remote:ssh:host-a:/workspace",
  458. workspaceRemoteSessionId: "session-a",
  459. },
  460. },
  461. });
  462. await act(async () => {
  463. root.unmount();
  464. });
  465. });
  466. it("运行中详情进入终态后丢弃旧 revision 结果并重新读取", async () => {
  467. const container = installMinimalDom();
  468. const root: Root = createRoot(container);
  469. const partialResult = {
  470. files: 1,
  471. additions: 1,
  472. deletions: 0,
  473. items: [
  474. {
  475. path: "/workspace/README.md",
  476. additions: 1,
  477. deletions: 0,
  478. writeCount: 1,
  479. toolNames: ["Write"],
  480. patches: [],
  481. },
  482. ],
  483. };
  484. const finalResult = {
  485. files: 2,
  486. additions: 2,
  487. deletions: 0,
  488. items: [
  489. ...partialResult.items,
  490. {
  491. path: "/workspace/index.html",
  492. additions: 1,
  493. deletions: 0,
  494. writeCount: 1,
  495. toolNames: ["Write"],
  496. patches: [],
  497. },
  498. ],
  499. };
  500. const fetchFileChanges = vi
  501. .fn()
  502. .mockResolvedValueOnce(partialResult)
  503. .mockResolvedValueOnce(finalResult);
  504. const context: ConversationRowRenderContext = {
  505. workspacePath: "/workspace",
  506. theme: "system",
  507. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  508. fetchFileChanges,
  509. };
  510. const renderPanelForState = (state: TurnHeaderRow["state"]) =>
  511. createElement(
  512. ZCodeIntlProvider,
  513. { initialLocale: "zh-CN" },
  514. createElement(ConversationFileSummaryPanel, {
  515. header: header({ state }),
  516. context,
  517. }),
  518. );
  519. await act(async () => {
  520. root.render(renderPanelForState("running"));
  521. });
  522. await act(async () => {
  523. collapsibleOpenChanges.at(-1)?.(true);
  524. await Promise.resolve();
  525. });
  526. expect(collectText(container)).toContain("README.md");
  527. await act(async () => {
  528. root.render(renderPanelForState("completedSuccess"));
  529. await Promise.resolve();
  530. });
  531. expect(fetchFileChanges).toHaveBeenNthCalledWith(
  532. 1,
  533. { rowId: 1, entityId: "turn-header-1" },
  534. { cachePolicy: "in-flight", fileChangesState: "active" },
  535. );
  536. expect(fetchFileChanges).toHaveBeenNthCalledWith(
  537. 2,
  538. { rowId: 1, entityId: "turn-header-1" },
  539. { cachePolicy: "terminal", fileChangesState: "active" },
  540. );
  541. expect(collectText(container)).toContain("index.html");
  542. await act(async () => root.unmount());
  543. });
  544. it("fileChanges 进入 reverted 后清空撤销前详情并按新状态重查", async () => {
  545. const container = installMinimalDom();
  546. const root: Root = createRoot(container);
  547. const activeResult: V4ConversationFileChangesResult = {
  548. files: 1,
  549. additions: 1,
  550. deletions: 0,
  551. state: "active",
  552. items: [{ path: "/workspace/README.md", patches: [] }],
  553. };
  554. let resolveReverted: ((value: V4ConversationFileChangesResult) => void) | undefined;
  555. const revertedResult = new Promise<V4ConversationFileChangesResult>((resolve) => {
  556. resolveReverted = resolve;
  557. });
  558. const fetchFileChanges = vi
  559. .fn()
  560. .mockResolvedValueOnce(activeResult)
  561. .mockReturnValueOnce(revertedResult);
  562. const context: ConversationRowRenderContext = {
  563. workspacePath: "/workspace",
  564. theme: "system",
  565. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  566. fetchFileChanges,
  567. };
  568. const renderPanelForFileState = (state: "active" | "reverted") =>
  569. createElement(
  570. ZCodeIntlProvider,
  571. { initialLocale: "zh-CN" },
  572. createElement(ConversationFileSummaryPanel, {
  573. header: header({
  574. fileChanges: {
  575. files: 1,
  576. additions: 1,
  577. deletions: 0,
  578. state,
  579. },
  580. }),
  581. context,
  582. }),
  583. );
  584. await act(async () => {
  585. root.render(renderPanelForFileState("active"));
  586. });
  587. await act(async () => {
  588. collapsibleOpenChanges.at(-1)?.(true);
  589. await Promise.resolve();
  590. });
  591. expect(collectText(container)).toContain("README.md");
  592. await act(async () => {
  593. root.render(renderPanelForFileState("reverted"));
  594. await Promise.resolve();
  595. });
  596. expect(collectText(container)).not.toContain("README.md");
  597. expect(fetchFileChanges).toHaveBeenNthCalledWith(
  598. 2,
  599. { rowId: 1, entityId: "turn-header-1" },
  600. { cachePolicy: "terminal", fileChangesState: "reverted" },
  601. );
  602. resolveReverted?.({ ...activeResult, state: "reverted", items: [] });
  603. await act(async () => {
  604. await revertedResult;
  605. });
  606. await act(async () => root.unmount());
  607. });
  608. });