v4ConversationFileSummaryPanel.test.ts 18 KB

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