archiveManagement.test.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. // @vitest-environment jsdom
  2. import { act, cleanup, renderHook } from "@testing-library/react";
  3. import { afterEach, expect, it, vi } from "vitest";
  4. import type { ProjectTask, ProjectTree } from "@/project-sidebar/contract.js";
  5. import { buildArchiveGroups, archiveTaskKey } from "@/project-sidebar/archive-view.js";
  6. import { mutateProjectTask } from "@/project-sidebar/task-mutation.js";
  7. import { useArchiveManagement } from "@/project-sidebar/useArchiveManagement.js";
  8. const mocks = vi.hoisted(() => ({
  9. directory: {} as any,
  10. mutateTask: vi.fn(),
  11. confirm: vi.fn(),
  12. removeTaskState: vi.fn(),
  13. }));
  14. vi.mock("@/project-sidebar/ProjectDirectoryProvider.js", () => ({
  15. useProjectDirectory: () => mocks.directory,
  16. }));
  17. vi.mock("@/hooks/useWorkspaceServices.js", () => ({
  18. useBaseWorkspaceServices: () => ({ windowControllerService: mocks, zcodeTaskService: {} }),
  19. }));
  20. vi.mock("@/hooks/useConfirmDialog.js", () => ({ useConfirmDialog: () => mocks.confirm }));
  21. vi.mock("@/store/zcodeSessionStore.js", () => ({
  22. useZCodeSessionStore: (select: any) => select(mocks),
  23. }));
  24. vi.mock("@/i18n/IntlProvider.js", () => ({
  25. useZCodeIntl: () => ({
  26. intl: { formatMessage: ({ id }: any, values: any) => `${id}:${JSON.stringify(values)}` },
  27. }),
  28. }));
  29. const task = (id: string, extra: Partial<ProjectTask> = {}): ProjectTask => ({
  30. taskId: id,
  31. title: id,
  32. traceId: id,
  33. workspacePath: "/same",
  34. hostId: "local",
  35. projectId: "one",
  36. pinned: false,
  37. archived: true,
  38. createdAt: 1,
  39. updatedAt: 2,
  40. mode: "default",
  41. ...extra,
  42. });
  43. const project = (id: string, extra = {}) => ({
  44. id,
  45. hostId: "local",
  46. name: `Virtual ${id}`,
  47. roots: [{ rootPath: "/same", isPrimary: true, position: 0 }],
  48. deleted: false,
  49. pinned: false,
  50. position: 0,
  51. nameOverridden: true,
  52. createdAt: 1,
  53. updatedAt: 1,
  54. ...extra,
  55. });
  56. const tree = (): ProjectTree => ({
  57. projects: [
  58. project("one"),
  59. project("two"),
  60. project("one", { hostId: "remote:server:r", name: "Remote virtual" }),
  61. project("deleted", { deleted: true }),
  62. ],
  63. tasks: [
  64. task("alpha"),
  65. task("beta", { projectId: "two", cronAutomationId: "cron" }),
  66. task("alpha", { hostId: "remote:server:r", workspaceIdentity: "remote:server:r:/same" }),
  67. task("orphan", { projectId: null }),
  68. task("old", { projectId: "deleted" }),
  69. task("active", { archived: false }),
  70. ],
  71. });
  72. afterEach(() => {
  73. cleanup();
  74. vi.clearAllMocks();
  75. });
  76. it("groups by virtual identity rather than shared roots and preserves removed/unclassified archives", () => {
  77. const groups = buildArchiveGroups(tree());
  78. expect(groups.map((g) => g.tasks.length)).toEqual([1, 1, 1, 1, 1]);
  79. expect(new Set(groups.map((g) => g.key)).size).toBe(5);
  80. expect(groups.find((g) => g.project?.id === "deleted")?.project?.deleted).toBe(true);
  81. expect(groups.find((g) => g.project === undefined)?.tasks[0]?.taskId).toBe("orphan");
  82. expect(archiveTaskKey(tree().tasks[0]!)).not.toBe(archiveTaskKey(tree().tasks[2]!));
  83. });
  84. it("intersects title/project and switches between CLI updated and created time", () => {
  85. const t = tree();
  86. t.tasks.push(task("alpha-second", { createdAt: 9, updatedAt: 1 }));
  87. const before = JSON.stringify(t);
  88. const key = buildArchiveGroups(t).find(
  89. (g) => g.project?.id === "one" && g.hostId === "local",
  90. )!.key;
  91. expect(
  92. buildArchiveGroups(t, { query: "ALPHA", sort: "updated", project: key })[0]?.tasks.map(
  93. (t) => t.taskId,
  94. ),
  95. ).toEqual(["alpha", "alpha-second"]);
  96. expect(
  97. buildArchiveGroups(t, { query: "ALPHA", sort: "created", project: key })[0]?.tasks.map(
  98. (t) => t.taskId,
  99. ),
  100. ).toEqual(["alpha-second", "alpha"]);
  101. expect(JSON.stringify(t)).toBe(before);
  102. });
  103. it("routes archived actions with full remote identity and uses the existing local service fallback", async () => {
  104. const row = task("same", {
  105. workspaceIdentity: "remote:server:r:/same",
  106. hostId: "remote:server:r",
  107. });
  108. await mutateProjectTask(
  109. { controller: mocks, service: {} as never },
  110. row,
  111. { kind: "delete" },
  112. "attachment",
  113. );
  114. expect(mocks.mutateTask).toHaveBeenCalledWith({
  115. address: {
  116. taskId: "same",
  117. workspacePath: "/same",
  118. workspaceIdentity: "remote:server:r:/same",
  119. remoteSessionId: "attachment",
  120. sourceServerId: "r",
  121. },
  122. mutation: { kind: "delete" },
  123. });
  124. const service = { unarchiveTask: vi.fn(async () => row) };
  125. await mutateProjectTask({ service: service as never }, task("local"), {
  126. kind: "archive",
  127. archived: false,
  128. });
  129. expect(service.unarchiveTask).toHaveBeenCalledWith({
  130. workspacePath: "/same",
  131. workspaceIdentity: undefined,
  132. taskId: "local",
  133. });
  134. });
  135. function setup() {
  136. mocks.directory = {
  137. tree: tree(),
  138. directory: { hosts: [], entries: [] },
  139. availability: new Map(),
  140. refresh: vi.fn(async () => {}),
  141. error: null,
  142. loading: false,
  143. };
  144. mocks.confirm.mockResolvedValue(true);
  145. mocks.mutateTask.mockResolvedValue(null);
  146. return renderHook(() => useArchiveManagement());
  147. }
  148. it("cancelled deletion does not mutate; one in-flight batch rejects duplicate clicks and preserves failures", async () => {
  149. const { result } = setup();
  150. mocks.confirm.mockResolvedValueOnce(false);
  151. await act(async () => {
  152. await result.current.run([tree().tasks[0]!], "delete");
  153. });
  154. expect(mocks.mutateTask).not.toHaveBeenCalled();
  155. let release!: () => void;
  156. mocks.mutateTask
  157. .mockImplementationOnce(
  158. () =>
  159. new Promise<void>((r) => {
  160. release = r;
  161. }),
  162. )
  163. .mockRejectedValueOnce(new Error("offline"));
  164. let pending!: Promise<void>;
  165. act(() => {
  166. pending = result.current.run(tree().tasks.slice(0, 2), "unarchive");
  167. });
  168. await act(async () => {
  169. await result.current.run([tree().tasks[0]!], "unarchive");
  170. });
  171. expect(mocks.mutateTask).toHaveBeenCalledTimes(1);
  172. await act(async () => {
  173. release();
  174. await pending;
  175. });
  176. expect(mocks.mutateTask).toHaveBeenCalledTimes(2);
  177. expect(result.current.result).toEqual({ succeeded: 1, failed: 1, skipped: 0 });
  178. expect(mocks.directory.refresh).toHaveBeenCalledOnce();
  179. expect(result.current.busy).toBe(false);
  180. });
  181. it("does not expand the confirmed batch and skips rows unarchived while the dialog is open", async () => {
  182. const { result, rerender } = setup();
  183. let confirm!: (value: boolean) => void;
  184. mocks.confirm.mockImplementationOnce(
  185. () =>
  186. new Promise<boolean>((r) => {
  187. confirm = r;
  188. }),
  189. );
  190. let pending!: Promise<void>;
  191. act(() => {
  192. pending = result.current.run([tree().tasks[0]!], "delete");
  193. });
  194. mocks.directory = {
  195. ...mocks.directory,
  196. tree: { ...tree(), tasks: [task("alpha", { archived: false }), task("new")] },
  197. };
  198. rerender();
  199. await act(async () => {
  200. confirm(true);
  201. await pending;
  202. });
  203. expect(mocks.mutateTask).not.toHaveBeenCalled();
  204. expect(result.current.result?.skipped).toBe(1);
  205. });