taskListItemHoverActions.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. import { act, createElement, type ReactElement, type ReactNode } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import type { ZCodeTaskMeta } from "@zcode/shared";
  5. type TestEvent = {
  6. bubbles?: boolean;
  7. currentTarget?: TestElement;
  8. relatedTarget?: unknown;
  9. target?: TestElement;
  10. type: string;
  11. };
  12. type TestEventHandler = (event: TestEvent) => void;
  13. type TestElement = Element & {
  14. __attrs: Map<string, string>;
  15. __listeners: Map<string, TestEventHandler[]>;
  16. childNodes: TestElement[];
  17. dispatchEvent: (event: TestEvent) => boolean;
  18. parentNode: TestElement | null;
  19. };
  20. const {
  21. contextMenuMounts,
  22. contextMenuOpenChangeHandlers,
  23. contextActionsCalls,
  24. leadingIndicatorState,
  25. formatRelativeTimeCalls,
  26. tooltipCalls,
  27. triggerChildren,
  28. stableIntl,
  29. } = vi.hoisted(() => ({
  30. contextMenuMounts: [] as Array<Record<string, unknown>>,
  31. contextMenuOpenChangeHandlers: [] as Array<(open: boolean) => void>,
  32. contextActionsCalls: [] as Array<Record<string, unknown>>,
  33. leadingIndicatorState: { value: "none" },
  34. formatRelativeTimeCalls: [] as number[],
  35. tooltipCalls: [] as Array<Record<string, unknown>>,
  36. triggerChildren: [] as ReactElement[],
  37. stableIntl: {
  38. formatMessage: ({ id }: { id: string }) => id,
  39. },
  40. }));
  41. vi.mock("lucide-react", () => {
  42. const createIcon = (name: string) => (props: Record<string, unknown>) =>
  43. createElement("svg", { "data-icon": name, ...props });
  44. return {
  45. Archive: createIcon("archive"),
  46. CloudUpload: createIcon("cloud-upload"),
  47. Clock: createIcon("clock"),
  48. LoaderIcon: createIcon("loader"),
  49. Pin: createIcon("pin"),
  50. Smartphone: createIcon("smartphone"),
  51. };
  52. });
  53. vi.mock("@/components/ui/badge.js", () => ({
  54. Badge: ({ children }: { children?: ReactNode }) =>
  55. createElement("span", null, children),
  56. }));
  57. vi.mock("@/components/ui/button.js", () => ({
  58. Button: ({ children, ...props }: { children?: ReactNode }) =>
  59. createElement("button", props, children),
  60. }));
  61. vi.mock("@/components/ui/context-menu.js", () => ({
  62. ContextMenu: ({
  63. children,
  64. onOpenChange,
  65. }: {
  66. children?: ReactNode;
  67. onOpenChange?: (open: boolean) => void;
  68. }) => {
  69. if (onOpenChange) {
  70. contextMenuOpenChangeHandlers.push(onOpenChange);
  71. }
  72. return createElement("div", null, children);
  73. },
  74. ContextMenuTrigger: ({ children }: { children: ReactElement }) => {
  75. triggerChildren.push(children);
  76. return children;
  77. },
  78. }));
  79. vi.mock("@/lib/taskListItemPresentation.js", () => ({
  80. deriveTaskLeadingIndicator: () => leadingIndicatorState.value,
  81. formatTaskRelativeTime: (updatedAt: number) => {
  82. formatRelativeTimeCalls.push(updatedAt);
  83. return "now";
  84. },
  85. }));
  86. vi.mock("@/ControlHintTooltip.js", () => ({
  87. ControlHintTooltip: ({ children, ...props }: { children?: ReactNode }) => {
  88. tooltipCalls.push(props);
  89. return createElement("span", null, children);
  90. },
  91. }));
  92. vi.mock("@/TaskListItemContextMenu.js", () => ({
  93. TaskListItemContextMenu: (props: Record<string, unknown>) => {
  94. contextMenuMounts.push(props);
  95. return createElement("div", { "data-testid": "task-context-menu" });
  96. },
  97. }));
  98. vi.mock("@/useTaskListItemContextActions.js", () => ({
  99. useTaskListItemContextActions: (params: Record<string, unknown>) => {
  100. contextActionsCalls.push(params);
  101. return {
  102. fileManagerLabel: "Finder",
  103. handleCopyText: vi.fn(),
  104. handleOpenProviderConfig: vi.fn(),
  105. handleOpenTaskPathInFileManager: vi.fn(),
  106. providerConfigFile: { exists: false, loading: false, path: null },
  107. taskNativeSessionLogFile: { exists: false, loading: false, path: null },
  108. taskSessionFile: { exists: false, loading: false, path: null },
  109. };
  110. },
  111. }));
  112. vi.mock("@/hooks/usePlatform.js", () => ({
  113. useOptionalPlatform: () => null,
  114. }));
  115. vi.mock("@/feedback/feedbackStore.js", () => ({
  116. useFeedbackStore: (
  117. selector: (state: { openSubmit: () => void }) => unknown,
  118. ) => selector({ openSubmit: vi.fn() }),
  119. }));
  120. vi.mock("@/store/modelTrajectoryStore.js", () => ({
  121. useModelTrajectoryStore: {
  122. getState: () => ({
  123. requestOpen: vi.fn(),
  124. }),
  125. },
  126. }));
  127. vi.mock("@/components/ui/toast.js", () => ({
  128. toast: () => {},
  129. }));
  130. vi.mock("@/store/zcodeSessionStore.js", async () => {
  131. const actual = await vi.importActual<
  132. typeof import("@/store/zcodeSessionStore.js")
  133. >("@/store/zcodeSessionStore.js");
  134. return {
  135. ...actual,
  136. getTaskRuntimeState: () => "idle",
  137. getTaskUnreadIndicator: () => false,
  138. hasTaskPendingHumanInterventionRequest: () => false,
  139. hasTaskPendingPermissionRequest: () => false,
  140. selectWorkspaceZCodeState: () => ({}),
  141. useZCodeSessionStore: (
  142. selector: (state: Record<string, unknown>) => unknown,
  143. ) => selector({}),
  144. };
  145. });
  146. function createTask(): ZCodeTaskMeta {
  147. return {
  148. createdAt: 1,
  149. mode: "default",
  150. provider: "codex",
  151. taskId: "task-1",
  152. title: "Task 1",
  153. traceId: "trace-1",
  154. updatedAt: 2,
  155. workspacePath: "/workspace",
  156. };
  157. }
  158. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  159. const element = {
  160. __attrs: new Map<string, string>(),
  161. __listeners: new Map<string, TestEventHandler[]>(),
  162. addEventListener: (type: string, handler: TestEventHandler) => {
  163. const handlers = element.__listeners.get(type) ?? [];
  164. handlers.push(handler);
  165. element.__listeners.set(type, handlers);
  166. },
  167. appendChild: (child: TestElement) => {
  168. child.parentNode = element as unknown as TestElement;
  169. element.childNodes.push(child);
  170. return child;
  171. },
  172. childNodes: [] as TestElement[],
  173. dispatchEvent: (event: TestEvent) => {
  174. event.target ??= element as unknown as TestElement;
  175. let current: TestElement | null = element as unknown as TestElement;
  176. while (current) {
  177. event.currentTarget = current;
  178. for (const handler of current.__listeners.get(event.type) ?? []) {
  179. handler(event);
  180. }
  181. if (!event.bubbles) {
  182. break;
  183. }
  184. current = current.parentNode;
  185. }
  186. return true;
  187. },
  188. getAttribute: (name: string) => element.__attrs.get(name) ?? null,
  189. insertBefore: (child: TestElement, beforeChild?: TestElement | null) => {
  190. child.parentNode = element as unknown as TestElement;
  191. const beforeIndex = beforeChild
  192. ? element.childNodes.indexOf(beforeChild)
  193. : -1;
  194. if (beforeIndex >= 0) {
  195. element.childNodes.splice(beforeIndex, 0, child);
  196. } else {
  197. element.childNodes.push(child);
  198. }
  199. return child;
  200. },
  201. nodeName: tagName.toUpperCase(),
  202. nodeType: 1,
  203. ownerDocument,
  204. parentNode: null as TestElement | null,
  205. querySelector: (selector: string) => {
  206. const attributeMatch = /^\[([^=\]]+)(?:=[^\]]+)?\]$/u.exec(selector);
  207. if (!attributeMatch) {
  208. return null;
  209. }
  210. return findByAttribute(
  211. element as unknown as TestElement,
  212. attributeMatch[1],
  213. );
  214. },
  215. removeAttribute: (name: string) => {
  216. element.__attrs.delete(name);
  217. },
  218. removeChild: (child: TestElement) => {
  219. element.childNodes = element.childNodes.filter((item) => item !== child);
  220. child.parentNode = null;
  221. return child;
  222. },
  223. removeEventListener: (type: string, handler: TestEventHandler) => {
  224. element.__listeners.set(
  225. type,
  226. (element.__listeners.get(type) ?? []).filter((item) => item !== handler),
  227. );
  228. },
  229. setAttribute: (name: string, value: string) => {
  230. element.__attrs.set(name, String(value));
  231. },
  232. style: {},
  233. tagName: tagName.toUpperCase(),
  234. };
  235. return element as unknown as TestElement;
  236. }
  237. function findByAttribute(node: TestElement, attributeName: string) {
  238. if (node.__attrs?.has(attributeName)) {
  239. return node;
  240. }
  241. for (const child of node.childNodes ?? []) {
  242. const match = findByAttribute(child, attributeName);
  243. if (match) {
  244. return match;
  245. }
  246. }
  247. return null;
  248. }
  249. function findByAttributeValue(
  250. node: TestElement,
  251. attributeName: string,
  252. attributeValue: string,
  253. ) {
  254. if (node.__attrs?.get(attributeName) === attributeValue) {
  255. return node;
  256. }
  257. for (const child of node.childNodes ?? []) {
  258. const match = findByAttributeValue(child, attributeName, attributeValue);
  259. if (match) {
  260. return match;
  261. }
  262. }
  263. return null;
  264. }
  265. function installMinimalDom(hoverNone = false) {
  266. const documentMock = {
  267. addEventListener: () => {},
  268. createElement: (tagName: string) =>
  269. createMinimalElement(documentMock as unknown as Document, tagName),
  270. createElementNS: (_namespace: string, tagName: string) =>
  271. createMinimalElement(documentMock as unknown as Document, tagName),
  272. createTextNode: (nodeValue: string) => ({
  273. nodeType: 3,
  274. nodeValue,
  275. ownerDocument: documentMock,
  276. parentNode: null,
  277. }),
  278. nodeType: 9,
  279. removeEventListener: () => {},
  280. } as unknown as Document;
  281. const windowMock = {
  282. addEventListener: () => {},
  283. document: documentMock,
  284. HTMLIFrameElement: function HTMLIFrameElement() {},
  285. HTMLElement: function HTMLElement() {},
  286. matchMedia: () => ({ matches: hoverNone }),
  287. Node: function Node() {},
  288. removeEventListener: () => {},
  289. };
  290. Object.defineProperty(globalThis, "document", {
  291. configurable: true,
  292. value: documentMock,
  293. });
  294. Object.defineProperty(globalThis, "window", {
  295. configurable: true,
  296. value: windowMock,
  297. });
  298. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  299. configurable: true,
  300. value: true,
  301. });
  302. return createMinimalElement(documentMock);
  303. }
  304. describe("TaskListItem hover action rendering", () => {
  305. afterEach(() => {
  306. contextMenuMounts.length = 0;
  307. contextMenuOpenChangeHandlers.length = 0;
  308. contextActionsCalls.length = 0;
  309. leadingIndicatorState.value = "none";
  310. formatRelativeTimeCalls.length = 0;
  311. tooltipCalls.length = 0;
  312. triggerChildren.length = 0;
  313. delete (globalThis as { document?: unknown }).document;
  314. delete (globalThis as { window?: unknown }).window;
  315. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown })
  316. .IS_REACT_ACT_ENVIRONMENT;
  317. });
  318. it("keeps idle rows free of per-row context menu and hover-only archive tooltip", async () => {
  319. const { MemoTaskItem } = await import("@/TaskListItem.js");
  320. const root: Root = createRoot(installMinimalDom());
  321. act(() => {
  322. root.render(
  323. createElement(MemoTaskItem, {
  324. intl: stableIntl,
  325. isActive: false,
  326. isArchiveConfirming: false,
  327. isPinned: false,
  328. onArchiveTask: vi.fn(),
  329. onArchiveTaskInline: vi.fn(),
  330. onCancelArchiveConfirm: vi.fn(),
  331. onMarkTaskAsUnread: vi.fn(),
  332. onSelectTask: vi.fn(),
  333. onStartRenameTask: vi.fn(),
  334. onTogglePinTask: vi.fn(),
  335. task: createTask(),
  336. workspacePath: "/workspace",
  337. }),
  338. );
  339. });
  340. expect(contextMenuOpenChangeHandlers).toHaveLength(0);
  341. expect(contextMenuMounts).toHaveLength(0);
  342. expect(contextActionsCalls).toHaveLength(0);
  343. expect(tooltipCalls).toHaveLength(0);
  344. act(() => {
  345. root.unmount();
  346. });
  347. });
  348. it("触屏常驻 actions 时仍保留 task 元信息", async () => {
  349. const { MemoTaskItem } = await import("@/TaskListItem.js");
  350. const container = installMinimalDom(true);
  351. const root: Root = createRoot(container);
  352. leadingIndicatorState.value = "unread";
  353. act(() => {
  354. root.render(
  355. createElement(MemoTaskItem, {
  356. intl: stableIntl,
  357. isActive: false,
  358. isArchiveConfirming: false,
  359. isPinned: false,
  360. onArchiveTask: vi.fn(),
  361. onArchiveTaskInline: vi.fn(),
  362. onCancelArchiveConfirm: vi.fn(),
  363. onMarkTaskAsUnread: vi.fn(),
  364. onSelectTask: vi.fn(),
  365. onStartRenameTask: vi.fn(),
  366. onTogglePinTask: vi.fn(),
  367. task: createTask(),
  368. workspacePath: "/workspace",
  369. }),
  370. );
  371. });
  372. expect(findByAttribute(container, "data-task-row-actions")).not.toBeNull();
  373. const metadata = findByAttribute(container, "data-task-row-metadata");
  374. expect(metadata).not.toBeNull();
  375. expect(metadata?.__attrs.get("class")).not.toContain("hidden");
  376. const unreadIndicator = findByAttribute(container, "data-unread-indicator");
  377. expect(unreadIndicator).not.toBeNull();
  378. expect(unreadIndicator?.parentNode?.__attrs.get("class")).not.toContain(
  379. "hidden",
  380. );
  381. act(() => {
  382. root.unmount();
  383. });
  384. });
  385. it("keeps default rows in the compact layout without idle dots", async () => {
  386. const { MemoTaskItem } = await import("@/TaskListItem.js");
  387. const container = installMinimalDom();
  388. const root: Root = createRoot(container);
  389. act(() => {
  390. root.render(
  391. createElement(MemoTaskItem, {
  392. intl: stableIntl,
  393. isActive: false,
  394. isArchiveConfirming: false,
  395. isPinned: false,
  396. onArchiveTask: vi.fn(),
  397. onArchiveTaskInline: vi.fn(),
  398. onCancelArchiveConfirm: vi.fn(),
  399. onMarkTaskAsUnread: vi.fn(),
  400. onSelectTask: vi.fn(),
  401. onStartRenameTask: vi.fn(),
  402. onTogglePinTask: vi.fn(),
  403. task: {
  404. ...createTask(),
  405. workspacePath: "/Users/demo/.zcode/workspace/default",
  406. },
  407. variant: "default",
  408. workspacePath: "/Users/demo/.zcode/workspace/default",
  409. }),
  410. );
  411. });
  412. const row = container.querySelector("[data-task-item-key]");
  413. expect(row?.getAttribute("class")).toContain("items-center");
  414. expect(row?.getAttribute("class")).not.toContain("items-start");
  415. expect(container.querySelector("[data-idle-indicator]")).toBeNull();
  416. act(() => {
  417. root.unmount();
  418. });
  419. });
  420. it("does not re-render when task meta is replaced with equivalent display fields", async () => {
  421. const { MemoTaskItem } = await import("@/TaskListItem.js");
  422. const root: Root = createRoot(installMinimalDom());
  423. const task = createTask();
  424. const props = {
  425. intl: stableIntl,
  426. isActive: false,
  427. isArchiveConfirming: false,
  428. isPinned: false,
  429. onArchiveTask: vi.fn(),
  430. onArchiveTaskInline: vi.fn(),
  431. onCancelArchiveConfirm: vi.fn(),
  432. onMarkTaskAsUnread: vi.fn(),
  433. onSelectTask: vi.fn(),
  434. onStartRenameTask: vi.fn(),
  435. onTogglePinTask: vi.fn(),
  436. task,
  437. workspacePath: "/workspace",
  438. };
  439. act(() => {
  440. root.render(createElement(MemoTaskItem, props));
  441. });
  442. expect(formatRelativeTimeCalls).toHaveLength(1);
  443. act(() => {
  444. root.render(
  445. createElement(MemoTaskItem, {
  446. ...props,
  447. task: { ...task },
  448. }),
  449. );
  450. });
  451. expect(formatRelativeTimeCalls).toHaveLength(1);
  452. act(() => {
  453. root.unmount();
  454. });
  455. });
  456. it("re-renders when a task receives automation identity", async () => {
  457. const { MemoTaskItem } = await import("@/TaskListItem.js");
  458. const container = installMinimalDom();
  459. const root: Root = createRoot(container);
  460. const task = createTask();
  461. const props = {
  462. intl: stableIntl,
  463. isActive: false,
  464. isArchiveConfirming: false,
  465. isPinned: false,
  466. onArchiveTask: vi.fn(),
  467. onArchiveTaskInline: vi.fn(),
  468. onCancelArchiveConfirm: vi.fn(),
  469. onMarkTaskAsUnread: vi.fn(),
  470. onSelectTask: vi.fn(),
  471. onStartRenameTask: vi.fn(),
  472. onTogglePinTask: vi.fn(),
  473. task,
  474. workspacePath: "/workspace",
  475. };
  476. act(() => {
  477. root.render(createElement(MemoTaskItem, props));
  478. });
  479. expect(container.querySelector("[data-cron-task-icon]")).toBeNull();
  480. act(() => {
  481. root.render(
  482. createElement(MemoTaskItem, {
  483. ...props,
  484. task: {
  485. ...task,
  486. automationId: "automation-1",
  487. } as ZCodeTaskMeta & { automationId: string },
  488. }),
  489. );
  490. });
  491. expect(container.querySelector("[data-cron-task-icon]")).not.toBeNull();
  492. act(() => {
  493. root.unmount();
  494. });
  495. });
  496. it("renders cron icon in the timeline time metadata", async () => {
  497. const { MemoTaskItem } = await import("@/TaskListItem.js");
  498. const container = installMinimalDom();
  499. const root: Root = createRoot(container);
  500. act(() => {
  501. root.render(
  502. createElement(MemoTaskItem, {
  503. intl: stableIntl,
  504. isActive: false,
  505. isArchiveConfirming: false,
  506. isPinned: false,
  507. onArchiveTask: vi.fn(),
  508. onArchiveTaskInline: vi.fn(),
  509. onCancelArchiveConfirm: vi.fn(),
  510. onMarkTaskAsUnread: vi.fn(),
  511. onSelectTask: vi.fn(),
  512. onStartRenameTask: vi.fn(),
  513. onTogglePinTask: vi.fn(),
  514. task: {
  515. ...createTask(),
  516. cronAutomationId: "automation-1",
  517. },
  518. variant: "timeline",
  519. workspacePath: "/workspace",
  520. }),
  521. );
  522. });
  523. expect(container.querySelector("[data-cron-task-icon]")).not.toBeNull();
  524. act(() => {
  525. root.unmount();
  526. });
  527. });
  528. it("keeps archive confirmation active after the pointer leaves the row", async () => {
  529. const { MemoTaskItem } = await import("@/TaskListItem.js");
  530. const container = installMinimalDom();
  531. const root: Root = createRoot(container);
  532. const onCancelArchiveConfirm = vi.fn();
  533. act(() => {
  534. root.render(
  535. createElement(MemoTaskItem, {
  536. intl: stableIntl,
  537. isActive: false,
  538. isArchiveConfirming: true,
  539. isPinned: false,
  540. onArchiveTask: vi.fn(),
  541. onArchiveTaskInline: vi.fn(),
  542. onCancelArchiveConfirm,
  543. onMarkTaskAsUnread: vi.fn(),
  544. onSelectTask: vi.fn(),
  545. onStartRenameTask: vi.fn(),
  546. onTogglePinTask: vi.fn(),
  547. task: createTask(),
  548. workspacePath: "/workspace",
  549. }),
  550. );
  551. });
  552. const row = container.querySelector("[data-task-item-key]") as
  553. | TestElement
  554. | null;
  555. expect(row).not.toBeNull();
  556. act(() => {
  557. row?.dispatchEvent({
  558. bubbles: true,
  559. relatedTarget: null,
  560. type: "mouseout",
  561. });
  562. });
  563. expect(onCancelArchiveConfirm).not.toHaveBeenCalled();
  564. const confirmButton = findByAttributeValue(
  565. container,
  566. "aria-label",
  567. "common.confirm",
  568. );
  569. expect(confirmButton?.__attrs.get("class")).toContain("flex");
  570. expect(confirmButton?.__attrs.get("class")).not.toContain("hidden");
  571. act(() => {
  572. root.unmount();
  573. });
  574. });
  575. });