v4ConversationComposerAttachmentProgress.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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";
  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("图片中央显示主题 token 圆环与百分比,未 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("bg-background/85");
  183. expect(html).toContain("size-3.5 rounded-full bg-primary");
  184. expect(html).toContain('data-composer-attachment-kind="image"');
  185. expect(html).toContain("size-12");
  186. expect(html).toContain("size-12 overflow-hidden rounded-lg");
  187. expect(html).toContain('data-composer-image-preview="image.png"');
  188. expect(html).not.toContain("bg-white");
  189. expect(html).toContain(`disabled="" data-testid="${TID_V4_COMPOSER_SEND}"`);
  190. });
  191. it("输入框附件按媒体(图片/视频)优先于文件排序,媒体组内保持添加顺序", () => {
  192. attachmentState.attachments = [
  193. {
  194. adopted: false,
  195. autoRetryCount: 0,
  196. filename: "SNAKE-ARENA.md",
  197. id: "file-first",
  198. localZeroCopy: false,
  199. referenceOwnership: "composer",
  200. mimeType: "text/markdown",
  201. operationId: "operation-file-first",
  202. showComplete: false,
  203. sizeBytes: 100,
  204. staged: false,
  205. uploadProgress: 100,
  206. uploadStatus: "ready",
  207. },
  208. {
  209. adopted: false,
  210. autoRetryCount: 0,
  211. filename: "avatar.png",
  212. id: "image-second",
  213. localZeroCopy: false,
  214. referenceOwnership: "composer",
  215. mimeType: "image/png",
  216. objectUrl: "blob:image-second",
  217. operationId: "operation-image-second",
  218. showComplete: false,
  219. sizeBytes: 100,
  220. staged: false,
  221. uploadProgress: 100,
  222. uploadStatus: "ready",
  223. },
  224. {
  225. adopted: false,
  226. autoRetryCount: 0,
  227. filename: "demo.mov",
  228. id: "video-third",
  229. localZeroCopy: false,
  230. referenceOwnership: "composer",
  231. mimeType: "video/quicktime",
  232. objectUrl: "blob:video-third",
  233. operationId: "operation-video-third",
  234. showComplete: false,
  235. sizeBytes: 100,
  236. staged: false,
  237. uploadProgress: 100,
  238. uploadStatus: "ready",
  239. },
  240. ];
  241. const html = renderComposer();
  242. expect(html.indexOf('data-composer-attachment-kind="image"')).toBeLessThan(
  243. html.indexOf('data-composer-attachment-kind="file"'),
  244. );
  245. expect(html.indexOf('data-composer-attachment-kind="video"')).toBeLessThan(
  246. html.indexOf('data-composer-attachment-kind="file"'),
  247. );
  248. // 媒体组内按添加顺序混排:后加的图片仍在先加的视频之前。
  249. expect(html.indexOf('data-composer-attachment-kind="image"')).toBeLessThan(
  250. html.indexOf('data-composer-attachment-kind="video"'),
  251. );
  252. expect(html).toContain('data-composer-file-attachments-row="true"');
  253. expect(html).toContain("flex-col items-start");
  254. expect(html).toContain('data-composer-attachment-kind="image"');
  255. expect(html).toContain('data-composer-attachment-kind="video"');
  256. expect(html).toContain('data-composer-attachment-kind="file"');
  257. // 视频与图片共用 48px 媒体卡片;本地 objectUrl 存在时显示首帧。
  258. expect(html).toContain('data-composer-attachment-kind="video"');
  259. expect(html).toContain('data-composer-attachment-url="blob:video-third"');
  260. expect(html).toContain('data-composer-image-preview="avatar.png,demo.mov"');
  261. expect(html).toContain("size-12");
  262. expect(html).toContain("h-12");
  263. expect(html).toContain("w-fit max-w-full");
  264. expect(html).toContain("gap-2 rounded-lg border");
  265. expect(html).toContain("size-9 rounded-md bg-background");
  266. expect(html).toContain("pr-6");
  267. expect(html).not.toContain("pr-8");
  268. expect(html).toContain("SNAKE-ARENA.md");
  269. expect(html).toContain('title="SNAKE-ARENA.md"');
  270. expect(html).toContain("truncate text-ui-base");
  271. expect(html).toContain("min-w-0 max-w-40 flex-1");
  272. expect(html).toContain(">MD<");
  273. expect(html.match(/data-composer-attachment-remove=/gu)).toHaveLength(3);
  274. expect(html).toContain("size-3.5 rounded-full bg-primary");
  275. expect(html).toContain("lucide-x size-2.5");
  276. expect(html).toContain("opacity-0");
  277. expect(html).toContain("group-hover:opacity-100");
  278. expect(html).toContain("focus-visible:opacity-100");
  279. expect(html).toContain("[@media(hover:none)]:opacity-100");
  280. expect(html.match(/top-0\.5/gu)).toHaveLength(3);
  281. expect(html.match(/right-0\.5/gu)).toHaveLength(3);
  282. expect(html).not.toContain("top-1");
  283. expect(html).not.toContain("right-1");
  284. });
  285. it("视频附件与图片同样显示主题 token 上传进度环与 48px 卡片", () => {
  286. attachmentState.attachments = [
  287. {
  288. adopted: false,
  289. autoRetryCount: 0,
  290. filename: "demo.mov",
  291. id: "video-1",
  292. localZeroCopy: false,
  293. referenceOwnership: "composer",
  294. mimeType: "video/quicktime",
  295. objectUrl: "blob:video-1",
  296. operationId: "operation-video-1",
  297. showComplete: false,
  298. sizeBytes: 100,
  299. staged: false,
  300. uploadProgress: 42,
  301. uploadStatus: "uploading",
  302. },
  303. ];
  304. const html = renderComposer();
  305. expect(html).toContain(`data-testid="${testId(TID_V4_ATTACHMENT_UPLOAD_PROGRESS, "video-1")}"`);
  306. expect(html).toContain('role="status"');
  307. expect(html).toContain("42%");
  308. expect(html).toContain('stroke-dasharray="42 100"');
  309. expect(html).toContain('data-composer-attachment-kind="video"');
  310. expect(html).toContain('data-composer-attachment-url="blob:video-1"');
  311. expect(html).toContain("size-12 overflow-hidden rounded-lg");
  312. });
  313. it("非图片失败态提供 alert、错误提示、重试和适配窄屏的行内布局", () => {
  314. attachmentState.attachments = [
  315. {
  316. adopted: false,
  317. autoRetryCount: 1,
  318. filename: "notes.md",
  319. id: "file-1",
  320. localZeroCopy: false,
  321. referenceOwnership: "composer",
  322. mimeType: "text/markdown",
  323. operationId: "operation-file-1",
  324. showComplete: false,
  325. sizeBytes: 100,
  326. staged: false,
  327. uploadError: "network unavailable",
  328. uploadProgress: 17,
  329. uploadStatus: "failed",
  330. },
  331. ];
  332. const html = renderComposer();
  333. expect(html).toContain('role="alert"');
  334. expect(html).toContain("network unavailable");
  335. expect(html).toContain(`data-testid="${testId(TID_V4_ATTACHMENT_UPLOAD_RETRY, "file-1")}"`);
  336. expect(html).toContain('aria-label="重试上传"');
  337. expect(html).toContain("flex-wrap");
  338. expect(html).toContain("max-w-full");
  339. expect(html).toContain("text-destructive");
  340. });
  341. });