v4ConversationComposerAttachmentProgress.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import { createElement, type ComponentType, type ReactNode } from "react";
  2. import { renderToStaticMarkup } from "react-dom/server";
  3. import { describe, expect, it, vi } from "vitest";
  4. import {
  5. TID_V4_ATTACHMENT_UPLOAD_PROGRESS,
  6. TID_V4_ATTACHMENT_UPLOAD_RETRY,
  7. TID_V4_COMPOSER_SEND,
  8. testId,
  9. } from "@zcode/shared/test-ids";
  10. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  11. import { ConversationComposer } from "@/v4/ConversationComposer.js";
  12. const attachmentState = vi.hoisted(() => ({
  13. attachments: [] as Array<Record<string, unknown>>,
  14. hookOptions: [] as Array<Record<string, unknown>>,
  15. retryAttachment: vi.fn(),
  16. }));
  17. const cuaEntryProps = vi.hoisted(() => [] as Array<Record<string, unknown>>);
  18. vi.mock("@/ControlHintTooltip.js", async () => {
  19. const React = await import("react");
  20. return {
  21. ControlHintTooltip: ({ children }: { children: ReactNode }) =>
  22. React.createElement(React.Fragment, null, children),
  23. };
  24. });
  25. vi.mock("@/prompt-editor/ChatPromptEditor.js", async () => {
  26. const React = await import("react");
  27. return {
  28. ChatPromptEditor: (props: Record<string, unknown>) =>
  29. React.createElement(
  30. "form",
  31. null,
  32. props.topContent as ReactNode,
  33. props.leadingActions as ReactNode,
  34. props.submitControl as ReactNode,
  35. ),
  36. };
  37. });
  38. vi.mock("@/components/ai-elements/attachments.js", async () => {
  39. const React = await import("react");
  40. const Container = ({
  41. children,
  42. data,
  43. openLabel: _openLabel,
  44. ...props
  45. }: { children?: ReactNode; data?: { url?: string } } & Record<string, unknown>) =>
  46. React.createElement(
  47. "div",
  48. { ...props, "data-composer-attachment-url": data?.url ?? "" },
  49. children,
  50. );
  51. return {
  52. Attachment: Container,
  53. AttachmentHoverCard: Container,
  54. AttachmentHoverCardContent: Container,
  55. AttachmentHoverCardTrigger: ({ children }: { children?: ReactNode }) => children,
  56. AttachmentInfo: (props: Record<string, unknown>) => React.createElement("span", props),
  57. AttachmentPreview: ({ fallbackIcon: _fallbackIcon, ...props }: Record<string, unknown>) =>
  58. React.createElement("span", props),
  59. AttachmentRemove: (props: Record<string, unknown>) => React.createElement("button", props),
  60. Attachments: Container,
  61. };
  62. });
  63. vi.mock("@/components/ai-elements/image-preview-dialog.js", async () => {
  64. const React = await import("react");
  65. return {
  66. ImagePreviewDialog: ({ items }: { items: Array<{ filename?: string }> }) =>
  67. React.createElement("div", {
  68. "data-composer-image-preview": items.map((item) => item.filename).join(","),
  69. }),
  70. };
  71. });
  72. vi.mock("@/v4/composer/useComposerAttachments.js", () => ({
  73. useComposerAttachments: (options: Record<string, unknown>) => {
  74. attachmentState.hookOptions.push(options);
  75. return {
  76. attachmentError: null,
  77. adoptSentAttachments: vi.fn(async () => {}),
  78. attachmentInputRef: { current: null },
  79. attachments: attachmentState.attachments,
  80. clearAttachments: vi.fn(),
  81. handleAttachmentInputChange: vi.fn(),
  82. handleDragLeaveComposer: vi.fn(),
  83. handleDragOverComposer: vi.fn(),
  84. handleDropComposer: vi.fn(),
  85. handlePaste: vi.fn(),
  86. handleWhiteboardMentionSelected: vi.fn(),
  87. hasAttachments: attachmentState.attachments.length > 0,
  88. hasUnreadyAttachments: attachmentState.attachments.some(
  89. (item) => item.uploadStatus !== "ready",
  90. ),
  91. isDraggingOverComposer: false,
  92. openAttachmentPicker: vi.fn(),
  93. prepareForSend: vi.fn(async () => null),
  94. removeAttachment: vi.fn(),
  95. retryAttachment: attachmentState.retryAttachment,
  96. setAttachmentError: vi.fn(),
  97. };
  98. },
  99. }));
  100. vi.mock("@/v4/composer/V4ComposerCuaEntry.js", async () => {
  101. const React = await import("react");
  102. return {
  103. V4ComposerCuaEntry: (props: Record<string, unknown>) => {
  104. cuaEntryProps.push(props);
  105. return React.createElement("span", { "data-cua-entry": "true" });
  106. },
  107. };
  108. });
  109. vi.mock("@/v4/composer/V4ComposerToolbar.js", async () => {
  110. const React = await import("react");
  111. return {
  112. V4ComposerModeSwitch: () => React.createElement("span"),
  113. V4ComposerModelControls: () => React.createElement("span"),
  114. };
  115. });
  116. const AnyConversationComposer = ConversationComposer as unknown as ComponentType<
  117. Record<string, unknown>
  118. >;
  119. function renderComposer(overrides: Record<string, unknown> = {}) {
  120. return renderToStaticMarkup(
  121. createElement(
  122. ZCodeIntlProvider,
  123. { initialLocale: "zh-CN" },
  124. createElement(AnyConversationComposer, {
  125. draftMode: true,
  126. onSelectModel: vi.fn(),
  127. onSelectThought: vi.fn(),
  128. onSendText: vi.fn(async () => {}),
  129. onStop: vi.fn(),
  130. onSwitchMode: vi.fn(),
  131. sessionId: null,
  132. snapshot: null,
  133. workspacePath: "/workspace",
  134. ...overrides,
  135. }),
  136. ),
  137. );
  138. }
  139. describe("ConversationComposer attachment upload progress", () => {
  140. it("只让聚焦且未禁用的 composer 监听 add-to-chat,并保留 CUA 常驻入口", () => {
  141. const html = renderComposer({
  142. disabled: true,
  143. isWebRemoteControl: true,
  144. listenAddToChatEvents: false,
  145. remoteSessionId: "remote-1",
  146. });
  147. expect(attachmentState.hookOptions.at(-1)).toMatchObject({
  148. listenAddToChatEvents: false,
  149. });
  150. expect(html).toContain('data-cua-entry="true"');
  151. expect(cuaEntryProps.at(-1)).toMatchObject({
  152. currentSessionBusy: false,
  153. isWebRemoteControl: true,
  154. remoteSessionId: "remote-1",
  155. workspacePath: "/workspace",
  156. });
  157. });
  158. it("图片显示上传圆环与百分比,未 ready 时发送按钮 disabled", () => {
  159. attachmentState.attachments = [
  160. {
  161. adopted: false,
  162. autoRetryCount: 0,
  163. filename: "image.png",
  164. id: "image-1",
  165. localZeroCopy: false,
  166. referenceOwnership: "composer",
  167. mimeType: "image/png",
  168. objectUrl: "blob:image-1",
  169. operationId: "operation-image-1",
  170. showComplete: false,
  171. sizeBytes: 100,
  172. staged: false,
  173. uploadProgress: 42,
  174. uploadStatus: "uploading",
  175. },
  176. ];
  177. const html = renderComposer();
  178. expect(html).toContain(`data-testid="${testId(TID_V4_ATTACHMENT_UPLOAD_PROGRESS, "image-1")}"`);
  179. expect(html).toContain('role="status"');
  180. expect(html).toContain("42%");
  181. expect(html).toContain('stroke-dasharray="42 100"');
  182. expect(html).toContain('data-composer-attachment-kind="image"');
  183. expect(html).toContain('data-composer-image-preview="image.png"');
  184. expect(html).toContain(`disabled="" data-testid="${TID_V4_COMPOSER_SEND}"`);
  185. });
  186. it("输入框附件按媒体(图片/视频)优先于文件排序,媒体组内保持添加顺序", () => {
  187. attachmentState.attachments = [
  188. {
  189. adopted: false,
  190. autoRetryCount: 0,
  191. filename: "SNAKE-ARENA.md",
  192. id: "file-first",
  193. localZeroCopy: false,
  194. referenceOwnership: "composer",
  195. mimeType: "text/markdown",
  196. operationId: "operation-file-first",
  197. showComplete: false,
  198. sizeBytes: 100,
  199. staged: false,
  200. uploadProgress: 100,
  201. uploadStatus: "ready",
  202. },
  203. {
  204. adopted: false,
  205. autoRetryCount: 0,
  206. filename: "avatar.png",
  207. id: "image-second",
  208. localZeroCopy: false,
  209. referenceOwnership: "composer",
  210. mimeType: "image/png",
  211. objectUrl: "blob:image-second",
  212. operationId: "operation-image-second",
  213. showComplete: false,
  214. sizeBytes: 100,
  215. staged: false,
  216. uploadProgress: 100,
  217. uploadStatus: "ready",
  218. },
  219. {
  220. adopted: false,
  221. autoRetryCount: 0,
  222. filename: "demo.mov",
  223. id: "video-third",
  224. localZeroCopy: false,
  225. referenceOwnership: "composer",
  226. mimeType: "video/quicktime",
  227. objectUrl: "blob:video-third",
  228. operationId: "operation-video-third",
  229. showComplete: false,
  230. sizeBytes: 100,
  231. staged: false,
  232. uploadProgress: 100,
  233. uploadStatus: "ready",
  234. },
  235. ];
  236. const html = renderComposer();
  237. expect(html.indexOf('data-composer-attachment-kind="image"')).toBeLessThan(
  238. html.indexOf('data-composer-attachment-kind="file"'),
  239. );
  240. expect(html.indexOf('data-composer-attachment-kind="video"')).toBeLessThan(
  241. html.indexOf('data-composer-attachment-kind="file"'),
  242. );
  243. // 媒体组内按添加顺序混排:后加的图片仍在先加的视频之前。
  244. expect(html.indexOf('data-composer-attachment-kind="image"')).toBeLessThan(
  245. html.indexOf('data-composer-attachment-kind="video"'),
  246. );
  247. expect(html).toContain('data-composer-file-attachments-row="true"');
  248. expect(html).toContain('data-composer-attachment-kind="image"');
  249. expect(html).toContain('data-composer-attachment-kind="video"');
  250. expect(html).toContain('data-composer-attachment-kind="file"');
  251. // 视频与图片共享预览列表;保留原始 objectUrl。
  252. expect(html).toContain('data-composer-attachment-url="blob:video-third"');
  253. expect(html).toContain('data-composer-image-preview="avatar.png,demo.mov"');
  254. expect(html).toContain("SNAKE-ARENA.md");
  255. expect(html).toContain('title="SNAKE-ARENA.md"');
  256. expect(html).toContain(">MD<");
  257. expect(html.match(/data-composer-attachment-remove=/gu)).toHaveLength(3);
  258. expect(html).toContain("opacity-0");
  259. expect(html).toContain("group-hover:opacity-100");
  260. expect(html).toContain("focus-visible:opacity-100");
  261. expect(html).toContain("[@media(hover:none)]:opacity-100");
  262. });
  263. it("视频附件显示上传进度环与原始预览地址", () => {
  264. attachmentState.attachments = [
  265. {
  266. adopted: false,
  267. autoRetryCount: 0,
  268. filename: "demo.mov",
  269. id: "video-1",
  270. localZeroCopy: false,
  271. referenceOwnership: "composer",
  272. mimeType: "video/quicktime",
  273. objectUrl: "blob:video-1",
  274. operationId: "operation-video-1",
  275. showComplete: false,
  276. sizeBytes: 100,
  277. staged: false,
  278. uploadProgress: 42,
  279. uploadStatus: "uploading",
  280. },
  281. ];
  282. const html = renderComposer();
  283. expect(html).toContain(`data-testid="${testId(TID_V4_ATTACHMENT_UPLOAD_PROGRESS, "video-1")}"`);
  284. expect(html).toContain('role="status"');
  285. expect(html).toContain("42%");
  286. expect(html).toContain('stroke-dasharray="42 100"');
  287. expect(html).toContain('data-composer-attachment-kind="video"');
  288. expect(html).toContain('data-composer-attachment-url="blob:video-1"');
  289. });
  290. it("非图片失败态提供 alert、错误提示和可访问重试入口", () => {
  291. attachmentState.attachments = [
  292. {
  293. adopted: false,
  294. autoRetryCount: 1,
  295. filename: "notes.md",
  296. id: "file-1",
  297. localZeroCopy: false,
  298. referenceOwnership: "composer",
  299. mimeType: "text/markdown",
  300. operationId: "operation-file-1",
  301. showComplete: false,
  302. sizeBytes: 100,
  303. staged: false,
  304. uploadError: "network unavailable",
  305. uploadProgress: 17,
  306. uploadStatus: "failed",
  307. },
  308. ];
  309. const html = renderComposer();
  310. expect(html).toContain('role="alert"');
  311. expect(html).toContain("network unavailable");
  312. expect(html).toContain(`data-testid="${testId(TID_V4_ATTACHMENT_UPLOAD_RETRY, "file-1")}"`);
  313. expect(html).toContain('aria-label="重试上传"');
  314. expect(html).toContain("text-destructive");
  315. });
  316. });