feedbackSubmitFormRetry.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. import { act, createElement } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  4. import type { IFeedbackService } from "@zcode/services";
  5. import type { IPlatformService } from "@zcode/shared";
  6. import { FeedbackSubmitForm } from "@/feedback/FeedbackSubmitForm.js";
  7. import type {
  8. FeedbackSubmissionJob,
  9. FeedbackSubmissionJobState,
  10. } from "@/feedback/feedbackSubmissionJob.js";
  11. const formCapture = vi.hoisted(() => ({
  12. contactProps: null as Record<string, unknown> | null,
  13. descriptionProps: null as Record<string, unknown> | null,
  14. footerProps: null as Record<string, unknown> | null,
  15. screenshotProps: null as Record<string, unknown> | null,
  16. logProps: null as Record<string, unknown> | null,
  17. getSubmissionJob: vi.fn(),
  18. startSubmission: vi.fn(),
  19. }));
  20. vi.mock("@/components/ui/toast.js", () => ({ toast: vi.fn() }));
  21. vi.mock("@/feedback/feedbackBadges.js", async () => {
  22. const React = await import("react");
  23. return {
  24. FeedbackErrorTip: ({ message }: { message: string }) =>
  25. React.createElement("div", { "data-error": message }),
  26. };
  27. });
  28. vi.mock("@/feedback/feedbackContactPreference.js", () => ({
  29. readFeedbackContactPreference: () => "user@example.com",
  30. }));
  31. vi.mock("@/feedback/FeedbackScreenshotPicker.js", async () => {
  32. const React = await import("react");
  33. return {
  34. FeedbackScreenshotPicker: (props: Record<string, unknown>) => {
  35. formCapture.screenshotProps = props;
  36. return React.createElement("div");
  37. },
  38. readScreenshotDraft: vi.fn(),
  39. };
  40. });
  41. vi.mock("@/feedback/FeedbackSubmitSections.js", async () => {
  42. const React = await import("react");
  43. return {
  44. ContactSection: (props: Record<string, unknown>) => {
  45. formCapture.contactProps = props;
  46. return React.createElement("div");
  47. },
  48. DescriptionSection: (props: Record<string, unknown>) => {
  49. formCapture.descriptionProps = props;
  50. return React.createElement("div");
  51. },
  52. LogUploadToggle: (props: Record<string, unknown>) => {
  53. formCapture.logProps = props;
  54. return React.createElement("div");
  55. },
  56. Section: ({ children }: { children?: unknown }) => React.createElement("div", null, children),
  57. SubmitFooter: (props: Record<string, unknown>) => {
  58. formCapture.footerProps = props;
  59. return React.createElement("div");
  60. },
  61. };
  62. });
  63. vi.mock("@/components/ui/scroll-fade-viewport.js", async () => {
  64. const React = await import("react");
  65. return {
  66. ScrollFadeViewport: ({ children }: { children?: unknown }) =>
  67. React.createElement("div", null, children),
  68. };
  69. });
  70. vi.mock("@/feedback/feedbackSubmitModelContext.js", () => ({
  71. readCurrentAgentModelContext: () => ({}),
  72. }));
  73. vi.mock("@/logger.js", () => ({
  74. logger: { debug: vi.fn() },
  75. }));
  76. vi.mock("@/feedback/feedbackSubmissionJob.js", () => ({
  77. cancelFeedbackCreateSubmissionJob: vi.fn(),
  78. getFeedbackSubmissionJob: formCapture.getSubmissionJob,
  79. }));
  80. vi.mock("@/feedback/feedbackSubmissionCopy.js", () => ({
  81. useFeedbackSubmissionCopy: () => ({
  82. connectingLabel: "connecting",
  83. connectingDetail: "connecting detail",
  84. failedLabel: "failed",
  85. networkErrorDetail: "network error",
  86. postCreateNetworkErrorDetail: "created but upload failed",
  87. }),
  88. }));
  89. vi.mock("@/feedback/feedbackSubmitSubmission.js", () => ({
  90. DEFAULT_FEEDBACK_MODULE: "其它",
  91. DEFAULT_FEEDBACK_SEVERITY: "P2-中",
  92. DEFAULT_FEEDBACK_TYPE: "bug",
  93. startSimplifiedFeedbackSubmission: formCapture.startSubmission,
  94. }));
  95. vi.mock("@/i18n/IntlProvider.js", () => ({
  96. useZCodeIntl: () => ({
  97. intl: { formatMessage: ({ id }: { id: string }) => id },
  98. locale: "en-US",
  99. }),
  100. }));
  101. vi.mock("@/store/TabStoreProvider.js", () => ({
  102. useTabStore: (selector: (state: Record<string, unknown>) => unknown) =>
  103. selector({ activeWorkspaceIdentity: null, activeWorkspacePath: null }),
  104. }));
  105. vi.mock("@/store/zcodeSessionStore.js", () => ({
  106. selectWorkspaceZCodeState: () => null,
  107. useZCodeSessionStore: (selector: (state: Record<string, unknown>) => unknown) => selector({}),
  108. }));
  109. const mountedRoots: Root[] = [];
  110. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  111. const element = {
  112. addEventListener: () => {},
  113. appendChild: (child: { parentNode?: unknown }) => {
  114. child.parentNode = element;
  115. return child;
  116. },
  117. childNodes: [] as unknown[],
  118. getAttribute: () => null,
  119. insertBefore: (child: { parentNode?: unknown }) => {
  120. child.parentNode = element;
  121. return child;
  122. },
  123. nodeName: tagName.toUpperCase(),
  124. nodeType: 1,
  125. ownerDocument,
  126. parentNode: null as unknown,
  127. removeAttribute: () => {},
  128. removeChild: (child: { parentNode?: unknown }) => {
  129. child.parentNode = null;
  130. return child;
  131. },
  132. removeEventListener: () => {},
  133. setAttribute: () => {},
  134. style: { removeProperty: () => {}, setProperty: () => {} },
  135. tagName: tagName.toUpperCase(),
  136. };
  137. return element as unknown as Element;
  138. }
  139. function installMinimalDom(): Element {
  140. const documentMock = {
  141. addEventListener: () => {},
  142. createElement: (tagName: string) =>
  143. createMinimalElement(documentMock as unknown as Document, tagName),
  144. createTextNode: (nodeValue: string) => ({
  145. nodeType: 3,
  146. nodeValue,
  147. ownerDocument: documentMock,
  148. parentNode: null,
  149. }),
  150. nodeType: 9,
  151. removeEventListener: () => {},
  152. } as unknown as Document;
  153. const windowMock = {
  154. addEventListener: () => {},
  155. document: documentMock,
  156. HTMLIFrameElement: function HTMLIFrameElement() {},
  157. HTMLElement: function HTMLElement() {},
  158. Node: function Node() {},
  159. removeEventListener: () => {},
  160. setTimeout,
  161. };
  162. Object.defineProperty(globalThis, "document", { configurable: true, value: documentMock });
  163. Object.defineProperty(globalThis, "window", { configurable: true, value: windowMock });
  164. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  165. configurable: true,
  166. value: true,
  167. });
  168. return createMinimalElement(documentMock, "div");
  169. }
  170. function getCapturedSubmit(): () => Promise<void> {
  171. const submit = formCapture.footerProps?.onSubmit;
  172. if (typeof submit !== "function") {
  173. throw new Error("Feedback submit handler was not rendered");
  174. }
  175. return submit as () => Promise<void>;
  176. }
  177. function createSubmissionJobFixture(
  178. state: FeedbackSubmissionJobState,
  179. overrides: Partial<FeedbackSubmissionJob> = {},
  180. ): FeedbackSubmissionJob {
  181. return {
  182. id: state.id,
  183. formDraft: {
  184. description: "",
  185. screenshots: [],
  186. includeLogs: false,
  187. type: "bug",
  188. },
  189. done: new Promise(() => {}),
  190. getState: () => state,
  191. subscribe: (listener) => {
  192. listener(state);
  193. return { dispose: vi.fn() };
  194. },
  195. cancelSubmission: vi.fn(),
  196. cancelActiveUpload: vi.fn(),
  197. continueLogUpload: vi.fn(),
  198. ...overrides,
  199. };
  200. }
  201. describe("FeedbackSubmitForm retry", () => {
  202. beforeEach(() => {
  203. formCapture.contactProps = null;
  204. formCapture.descriptionProps = null;
  205. formCapture.footerProps = null;
  206. formCapture.screenshotProps = null;
  207. formCapture.getSubmissionJob.mockReset();
  208. formCapture.getSubmissionJob.mockReturnValue(null);
  209. formCapture.startSubmission.mockReset();
  210. });
  211. afterEach(() => {
  212. for (const root of mountedRoots.splice(0)) {
  213. act(() => root.unmount());
  214. }
  215. delete (globalThis as { document?: unknown }).document;
  216. delete (globalThis as { window?: unknown }).window;
  217. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  218. });
  219. it.each([undefined, false, true])(
  220. "preserves draft log choice %s and submits user opt-out",
  221. async (includeLogs) => {
  222. const root = createRoot(installMinimalDom());
  223. mountedRoots.push(root);
  224. formCapture.startSubmission.mockResolvedValue(
  225. createSubmissionJobFixture({
  226. id: "log-choice",
  227. status: "running",
  228. progress: { label: "connecting" },
  229. }),
  230. );
  231. await act(async () => {
  232. root.render(
  233. createElement(FeedbackSubmitForm, {
  234. feedbackService: {} as IFeedbackService,
  235. platform: {} as IPlatformService,
  236. initialDraft: { description: "日志默认值", includeLogs },
  237. onSubmitted: vi.fn(),
  238. onViewTickets: vi.fn(),
  239. onCancel: vi.fn(),
  240. }),
  241. );
  242. });
  243. expect(formCapture.logProps?.checked).toBe(includeLogs ?? true);
  244. act(() => (formCapture.logProps?.onCheckedChange as (checked: boolean) => void)(false));
  245. await act(async () => {
  246. await getCapturedSubmit()();
  247. });
  248. expect(formCapture.startSubmission).toHaveBeenCalledWith(
  249. expect.objectContaining({ includeLogs: false }),
  250. );
  251. },
  252. );
  253. it("keeps description, screenshot, and contact when a network failure is retried", async () => {
  254. let state: FeedbackSubmissionJobState = {
  255. id: "feedback-retry",
  256. status: "running",
  257. progress: { label: "connecting" },
  258. };
  259. let stateListener: ((next: FeedbackSubmissionJobState) => void) | undefined;
  260. const job = createSubmissionJobFixture(state, {
  261. getState: () => state,
  262. subscribe: (listener) => {
  263. stateListener = listener;
  264. listener(state);
  265. return { dispose: vi.fn() };
  266. },
  267. });
  268. formCapture.startSubmission.mockResolvedValue(job);
  269. const root = createRoot(installMinimalDom());
  270. mountedRoots.push(root);
  271. await act(async () => {
  272. root.render(
  273. createElement(FeedbackSubmitForm, {
  274. feedbackService: {} as IFeedbackService,
  275. platform: {} as IPlatformService,
  276. initialDraft: {
  277. description: "用户现场描述",
  278. screenshots: [
  279. {
  280. filename: "现场.png",
  281. contentType: "image/png",
  282. dataBase64: "ZmFrZQ==",
  283. size: 4,
  284. },
  285. ],
  286. },
  287. onSubmitted: vi.fn(),
  288. onViewTickets: vi.fn(),
  289. onCancel: vi.fn(),
  290. }),
  291. );
  292. });
  293. await act(async () => {
  294. await getCapturedSubmit()();
  295. });
  296. state = {
  297. id: job.id,
  298. status: "error",
  299. error: "Check your network, VPN, or proxy settings, then try again.",
  300. progress: { label: "failed", detail: "network error" },
  301. };
  302. act(() => stateListener?.(state));
  303. expect(formCapture.descriptionProps?.value).toBe("用户现场描述");
  304. expect(formCapture.contactProps?.value).toBe("user@example.com");
  305. expect(formCapture.screenshotProps?.screenshots).toEqual([
  306. expect.objectContaining({ filename: "现场.png", dataBase64: "ZmFrZQ==" }),
  307. ]);
  308. await act(async () => {
  309. await getCapturedSubmit()();
  310. });
  311. expect(formCapture.startSubmission).toHaveBeenCalledTimes(2);
  312. expect(formCapture.startSubmission).toHaveBeenLastCalledWith(
  313. expect.objectContaining({
  314. contact: "user@example.com",
  315. description: "用户现场描述",
  316. screenshots: [expect.objectContaining({ filename: "现场.png", dataBase64: "ZmFrZQ==" })],
  317. }),
  318. );
  319. });
  320. it("restores the selected background job's original form draft", async () => {
  321. const state: FeedbackSubmissionJobState = {
  322. id: "feedback-background-a",
  323. status: "running",
  324. ticketId: "ticket-a",
  325. progress: { label: "uploading logs" },
  326. };
  327. const job = createSubmissionJobFixture(state, {
  328. formDraft: {
  329. description: "卡片 A 的用户原始问题描述",
  330. contact: "card-a@example.com",
  331. screenshots: [
  332. {
  333. filename: "card-a.png",
  334. contentType: "image/png",
  335. dataBase64: "Y2FyZC1h",
  336. size: 6,
  337. },
  338. ],
  339. includeLogs: true,
  340. type: "bug",
  341. severity: "P1-高",
  342. module: "UI布局 / 交互",
  343. },
  344. });
  345. formCapture.getSubmissionJob.mockReturnValue(job);
  346. const root = createRoot(installMinimalDom());
  347. mountedRoots.push(root);
  348. await act(async () => {
  349. root.render(
  350. createElement(FeedbackSubmitForm, {
  351. feedbackService: {} as IFeedbackService,
  352. platform: {} as IPlatformService,
  353. submissionJobId: job.id,
  354. onSubmitted: vi.fn(),
  355. onViewTickets: vi.fn(),
  356. onCancel: vi.fn(),
  357. }),
  358. );
  359. });
  360. expect(formCapture.getSubmissionJob).toHaveBeenCalledWith(job.id);
  361. expect(formCapture.descriptionProps?.value).toBe("卡片 A 的用户原始问题描述");
  362. expect(formCapture.contactProps?.value).toBe("card-a@example.com");
  363. expect(formCapture.screenshotProps?.screenshots).toEqual([
  364. expect.objectContaining({
  365. filename: "card-a.png",
  366. dataBase64: "Y2FyZC1h",
  367. }),
  368. ]);
  369. });
  370. });