conversation-session-v4-video-preview.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. // VI06 + VI07 门禁:媒体卡片、共享 gallery、本地路径/分片预览、失败重开与 edit 原始索引。
  2. // 证据层 L3:
  3. // 1) Composer 与 sent 消息都按原顺序渲染 image/video grid card,video 共享播放角标;
  4. // 2) 图片与视频进入同一个 gallery,并通过按钮/方向键首尾循环,图片工具与视频 controls 隔离;
  5. // 3) Desktop sent video 优先播放 artifact/local_ref 路径,非 fast-start MP4 也支持 seek,无可用路径时走 artifact 分片;
  6. // 4) 不可解码视频保留 gallery 导航/重开,edit 与完整进程重启后仍按持久化原始序号预览。
  7. import { mkdir, open, readFile, rm, writeFile } from "node:fs/promises";
  8. import { join } from "node:path";
  9. import { fileURLToPath } from "node:url";
  10. import { TID_V4_ATTACHMENT, TID_V4_ROW_ATTACHMENTS } from "@zcode/shared/test-ids";
  11. import { PROTOCOL_V4_LIMITS } from "@zcode/shared/zcode-protocol-v4";
  12. import { DEFAULT_WORKSPACE, clearAppData } from "#e2e/helpers/desktop-app";
  13. import { restartIntoWorkspacePreservingProfile } from "#e2e/helpers/model-provider-restart";
  14. import { removeV4ComposerAttachmentAt } from "#e2e/helpers/v4-composer-edit";
  15. import {
  16. beginFirstV4UserQueryEdit,
  17. clickV4Send,
  18. pasteV4ComposerFileAttachment,
  19. pasteV4ComposerImageAttachment,
  20. pickV4ComposerFiles,
  21. prepareV4ConversationE2E,
  22. selectV4TaskById,
  23. waitForV4Pane,
  24. waitForV4TimelineContaining,
  25. } from "#e2e/helpers/v4-conversation";
  26. const CASE_ROOT = join(DEFAULT_WORKSPACE, ".zcode-e2e", "conversation-session-v4-video-preview");
  27. const PLAYABLE_VIDEO_FILENAME = "e2e-composer-preview.mp4";
  28. const GALLERY_IMAGE_FILENAME = "e2e-gallery-image.png";
  29. const UNSUPPORTED_VIDEO_FILENAME = "e2e-unsupported.mov";
  30. const LARGE_VIDEO_FILENAME = "e2e-sent-large.mp4";
  31. const CHUNK_FALLBACK_VIDEO_FILENAME = "e2e-chunk-fallback.ogg";
  32. const VIDEO_SOURCE_PATH = fileURLToPath(
  33. new URL("../../fixtures/media/sample-video.mp4", import.meta.url),
  34. );
  35. const MEDIA_KINDS = ["video", "image", "video", "video", "video"] as const;
  36. type MediaKind = "image" | "video";
  37. type MediaCardState = {
  38. height: number;
  39. kind: MediaKind;
  40. role: string | null;
  41. src: string;
  42. uploadStatus: string | null;
  43. width: number;
  44. };
  45. type GalleryState = {
  46. alertText: string;
  47. alt: string;
  48. autoplay: boolean;
  49. controls: boolean;
  50. error: boolean;
  51. hasImageTools: boolean;
  52. hasNavigation: boolean;
  53. kind: "image" | "none" | "video";
  54. playsInline: boolean;
  55. readyState: number;
  56. src: string;
  57. title: string;
  58. };
  59. describe("v4 VI06/VI07:image/video 媒体 gallery 与 edit", () => {
  60. after(async () => {
  61. await browser.electron.restoreAllMocks();
  62. await clearAppData();
  63. await rm(CASE_ROOT, { recursive: true, force: true });
  64. });
  65. it("混合媒体首发 → sent gallery/reopen → edit 索引/删除", async () => {
  66. await prepareV4ConversationE2E();
  67. // Bug 根因:旧 E2E 只使用 moov 在 mdat 前的 fast-start MP4,无法触发自定义
  68. // scheme 对文件尾元数据的读取;改用同一可播 fixture 的尾部 moov 形态覆盖真实回归。
  69. const sourceVideo = moveMoovBoxBehindMediaData(await readFile(VIDEO_SOURCE_PATH));
  70. const playableVideoPath = join(CASE_ROOT, PLAYABLE_VIDEO_FILENAME);
  71. const largeVideoPath = join(CASE_ROOT, LARGE_VIDEO_FILENAME);
  72. await mkdir(CASE_ROOT, { recursive: true });
  73. await createSparseLargePlayableMp4(largeVideoPath, sourceVideo);
  74. await writeFile(playableVideoPath, sourceVideo);
  75. // 合成的 new File 没有磁盘路径,无法命中共享入口错误剥离本地媒体预览的分支。
  76. await browser.execute(() => {
  77. const input = document.createElement("input");
  78. input.type = "file";
  79. input.id = "e2e-local-video-drop";
  80. // 修复原因:默认样式的 file input 追加在 body 末尾,Windows 下会落在可视区外/被判定不可交互,
  81. // setValue 报 did not become interactable;固定到视口左上角并置顶,保证可交互。
  82. Object.assign(input.style, {
  83. position: "fixed",
  84. top: "0",
  85. left: "0",
  86. width: "100px",
  87. height: "24px",
  88. opacity: "1",
  89. zIndex: "2147483647",
  90. });
  91. document.body.append(input);
  92. });
  93. try {
  94. await $("#e2e-local-video-drop").setValue(playableVideoPath);
  95. const paths = await browser.execute(() => {
  96. const input = document.querySelector<HTMLInputElement>("#e2e-local-video-drop");
  97. const file = input?.files?.[0];
  98. const target = document.querySelector<HTMLElement>(
  99. '[data-v4-conversation-drop-target="true"]',
  100. );
  101. if (!file || !target) throw new Error("缺少本地视频 File 或会话 drop surface");
  102. const bridge = (
  103. window as Window & { zcode?: { getPathForFile(file: File): string | null } }
  104. ).zcode;
  105. const data = new DataTransfer();
  106. data.items.add(file);
  107. const result = [bridge?.getPathForFile(file), bridge?.getPathForFile(data.files[0]!)];
  108. target.dispatchEvent(
  109. new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data }),
  110. );
  111. return result;
  112. });
  113. expect(paths).toEqual([playableVideoPath, playableVideoPath]);
  114. } finally {
  115. await browser.execute(() => document.querySelector("#e2e-local-video-drop")?.remove());
  116. }
  117. await pasteV4ComposerImageAttachment(GALLERY_IMAGE_FILENAME);
  118. await pasteV4ComposerFileAttachment(UNSUPPORTED_VIDEO_FILENAME, {
  119. base64: Buffer.from("not playable", "utf8").toString("base64"),
  120. mimeType: "video/quicktime",
  121. });
  122. // `video/ogg` 可以进入 video 语义,但现有 artifact 派生缓存没有对应扩展名;
  123. // 它固定覆盖 local source 不可用时仍走既有分片/Blob 预览,而不是新增测试开关。
  124. await pasteV4ComposerFileAttachment(CHUNK_FALLBACK_VIDEO_FILENAME, {
  125. base64: Buffer.from("not playable", "utf8").toString("base64"),
  126. mimeType: "video/ogg",
  127. });
  128. await pickV4ComposerFiles([largeVideoPath]);
  129. const composerCards = await waitForComposerMediaCards(MEDIA_KINDS);
  130. expect(composerCards.map(({ width }) => width)).toEqual([48, 48, 48, 48, 48]);
  131. expect(composerCards.map(({ height }) => height)).toEqual([48, 48, 48, 48, 48]);
  132. expect(composerCards.map(({ role }) => role)).toEqual([
  133. "button",
  134. "button",
  135. "button",
  136. "button",
  137. null,
  138. ]);
  139. expect(composerCards.slice(0, 4).every(({ src }) => src.startsWith("blob:"))).toBe(true);
  140. // Bug 根因:视频 input File 仍采用本机路径预览;本用例不把路径视频改成 Blob 卡片。
  141. expect(composerCards[4]?.src.startsWith("blob:")).toBe(false);
  142. await openComposerMedia(0);
  143. await waitForPlayableVideo(PLAYABLE_VIDEO_FILENAME);
  144. await browser.keys(["ArrowRight"]);
  145. await waitForGalleryImage(GALLERY_IMAGE_FILENAME);
  146. await clickGalleryNavigation("next");
  147. await waitForUnsupportedVideo(UNSUPPORTED_VIDEO_FILENAME);
  148. await clickGalleryNavigation("previous");
  149. await waitForGalleryImage(GALLERY_IMAGE_FILENAME);
  150. await browser.keys(["ArrowLeft"]);
  151. await waitForPlayableVideo(PLAYABLE_VIDEO_FILENAME);
  152. await browser.keys(["ArrowLeft"]);
  153. await waitForUnsupportedVideo(CHUNK_FALLBACK_VIDEO_FILENAME);
  154. await closeMediaPreview();
  155. // 点击中间图片必须从其原始 gallery 位置打开,而不是每次都回到第一项。
  156. await openComposerMedia(1);
  157. await waitForGalleryImage(GALLERY_IMAGE_FILENAME);
  158. await closeMediaPreview();
  159. await installVideoBlobProbe();
  160. await clickV4Send();
  161. await waitForV4TimelineContaining("V4_VIDEO_PREVIEW_SEND_OK", 45_000);
  162. const sentSession = await waitForV4Pane(
  163. (state) => !state.canStop && state.sessionId !== "draft" && state.sessionId !== null,
  164. "混合媒体首发后没有回到空闲态且绑定 session",
  165. 45_000,
  166. );
  167. const sessionId = sentSession.sessionId;
  168. if (!sessionId || sessionId === "draft") {
  169. throw new Error(`混合媒体首发后缺少真实 sessionId: ${sessionId ?? "null"}`);
  170. }
  171. const sentCards = await waitForSentMediaCards(MEDIA_KINDS);
  172. expect(sentCards.map(({ width }) => width)).toEqual([80, 80, 80, 80, 80]);
  173. expect(sentCards.map(({ height }) => height)).toEqual([80, 80, 80, 80, 80]);
  174. expect(sentCards.every(({ role }) => role === "button")).toBe(true);
  175. expect(sentCards[0]?.src.startsWith("zcode-media:")).toBe(true);
  176. expect(sentCards[1]?.src.startsWith("blob:")).toBe(true);
  177. expect(sentCards[2]?.src.startsWith("zcode-media:")).toBe(true);
  178. expect(sentCards[3]?.src.startsWith("blob:")).toBe(true);
  179. expect(sentCards[4]?.src.startsWith("zcode-media:")).toBe(true);
  180. expect(localMediaPath(sentCards[0]?.src).split(/[\\/]/)).toContain("video-cache");
  181. // 修复原因:Windows 路径大小写不敏感,实际路径盘符后目录大小写(Code/code)可能与测试拼出的不同;
  182. // 比较时在 Windows 上忽略大小写,避免把大小写差异当成路径不一致。
  183. const normalizeWinPath = (value: string) =>
  184. process.platform === "win32" ? value.toLowerCase() : value;
  185. expect(normalizeWinPath(localMediaPath(sentCards[4]?.src))).toBe(
  186. normalizeWinPath(largeVideoPath),
  187. );
  188. await expectUnauthorizedLocalMediaPathRejected(VIDEO_SOURCE_PATH);
  189. await waitForVideoBlob("video/ogg");
  190. expect(
  191. (await readVideoBlobCalls()).every(
  192. ({ size, type }) => !type.startsWith("video/") || size <= sourceVideo.byteLength,
  193. ),
  194. ).toBe(true);
  195. await restoreVideoBlobProbe();
  196. const largeVideoThumbnailSrc = sentCards[4]?.src;
  197. expect(largeVideoThumbnailSrc).toBeTruthy();
  198. await openSentMedia(4);
  199. await waitForPlayableVideo(LARGE_VIDEO_FILENAME, largeVideoThumbnailSrc);
  200. await seekPreviewVideo(LARGE_VIDEO_FILENAME);
  201. await browser.keys(["ArrowRight"]);
  202. await waitForPlayableVideo(PLAYABLE_VIDEO_FILENAME, sentCards[0]?.src);
  203. await browser.keys(["ArrowRight"]);
  204. await waitForGalleryImage(GALLERY_IMAGE_FILENAME);
  205. await clickGalleryNavigation("next");
  206. await waitForUnsupportedVideo(UNSUPPORTED_VIDEO_FILENAME);
  207. await closeMediaPreview();
  208. // 分片 fallback 项关闭后仍能从原位置重开,并能继续导航到本地路径项。
  209. await openSentMedia(3);
  210. await waitForUnsupportedVideo(CHUNK_FALLBACK_VIDEO_FILENAME);
  211. await clickGalleryNavigation("next");
  212. await waitForPlayableVideo(LARGE_VIDEO_FILENAME, largeVideoThumbnailSrc);
  213. await closeMediaPreview();
  214. // composer 编辑态载入原有序 refs,复用 composer 48px 媒体卡(AL13)。
  215. await beginFirstV4UserQueryEdit("");
  216. await waitForEditedComposerMediaCards(MEDIA_KINDS);
  217. await removeV4ComposerAttachmentAt(0);
  218. await waitForEditedComposerMediaCards(["image", "video", "video", "video"]);
  219. // 删除原索引 0 后,大视频展示索引前移,但 preview query 仍必须携带持久化原索引 4。
  220. await openComposerMedia(3);
  221. await waitForPlayableVideo(LARGE_VIDEO_FILENAME, largeVideoThumbnailSrc);
  222. await browser.keys(["ArrowRight"]);
  223. await waitForGalleryImage(GALLERY_IMAGE_FILENAME);
  224. await closeMediaPreview();
  225. await clickV4Send();
  226. await waitForV4TimelineContaining("V4_VIDEO_PREVIEW_EDIT_OK", 45_000);
  227. const editedSentCards = await waitForSentMediaCards(["image", "video", "video", "video"]);
  228. expect(editedSentCards[3]?.src.startsWith("zcode-media:")).toBe(true);
  229. await openSentMedia(3);
  230. await waitForPlayableVideo(LARGE_VIDEO_FILENAME, editedSentCards[3]?.src);
  231. await closeMediaPreview();
  232. await restartIntoWorkspacePreservingProfile();
  233. await selectV4TaskById(sessionId, 60_000);
  234. await waitForV4Pane(
  235. (state) =>
  236. state.sessionId === sessionId && state.timelineText.includes("V4_VIDEO_PREVIEW_EDIT_OK"),
  237. `完整进程重启后没有冷恢复视频会话 ${sessionId}`,
  238. 90_000,
  239. );
  240. const coldCards = await waitForSentMediaCards(["image", "video", "video", "video"]);
  241. expect(localMediaPath(coldCards[1]?.src).split(/[\\/]/)).toContain("video-cache");
  242. expect(coldCards[2]?.src.startsWith("blob:")).toBe(true);
  243. expect(normalizeWinPath(localMediaPath(coldCards[3]?.src))).toBe(
  244. normalizeWinPath(largeVideoPath),
  245. );
  246. await openSentMedia(3);
  247. await waitForPlayableVideo(LARGE_VIDEO_FILENAME, coldCards[3]?.src);
  248. await seekPreviewVideo(LARGE_VIDEO_FILENAME);
  249. await closeMediaPreview();
  250. await openSentMedia(2);
  251. await waitForUnsupportedVideo(CHUNK_FALLBACK_VIDEO_FILENAME);
  252. await closeMediaPreview();
  253. }).timeout(360_000);
  254. });
  255. async function createSparseLargePlayableMp4(path: string, source: Buffer): Promise<void> {
  256. const targetBytes = PROTOCOL_V4_LIMITS.attachmentPreviewMaxBytes + 1024 * 1024;
  257. const moovBox = findTopLevelMp4Box(source, "moov");
  258. if (moovBox.offset + moovBox.size !== source.byteLength) {
  259. throw new Error("非 fast-start E2E 视频的 moov box 必须位于文件末尾");
  260. }
  261. const prefix = source.subarray(0, moovBox.offset);
  262. const moov = source.subarray(moovBox.offset);
  263. const freeBoxBytes = targetBytes - prefix.byteLength - moov.byteLength;
  264. if (freeBoxBytes < 8) throw new Error("大视频 E2E fixture 没有足够空间写入 free box");
  265. const freeBoxHeader = Buffer.alloc(8);
  266. freeBoxHeader.writeUInt32BE(freeBoxBytes, 0);
  267. freeBoxHeader.write("free", 4, "ascii");
  268. const file = await open(path, "w");
  269. try {
  270. await file.write(prefix, 0, prefix.byteLength, 0);
  271. await file.write(freeBoxHeader, 0, freeBoxHeader.byteLength, prefix.byteLength);
  272. await file.write(moov, 0, moov.byteLength, targetBytes - moov.byteLength);
  273. } finally {
  274. await file.close();
  275. }
  276. }
  277. type Mp4Box = { offset: number; size: number; type: string };
  278. function moveMoovBoxBehindMediaData(source: Buffer): Buffer {
  279. const moovBox = findTopLevelMp4Box(source, "moov");
  280. const mdatBox = findTopLevelMp4Box(source, "mdat");
  281. if (moovBox.offset > mdatBox.offset) return source;
  282. // 保留原 moov 占用的字节,避免移动 mdat 后让 chunk offset 失效。
  283. const placeholder = Buffer.alloc(moovBox.size);
  284. placeholder.writeUInt32BE(moovBox.size, 0);
  285. placeholder.write("free", 4, "ascii");
  286. const result = Buffer.concat([
  287. source.subarray(0, moovBox.offset),
  288. placeholder,
  289. source.subarray(moovBox.offset + moovBox.size),
  290. source.subarray(moovBox.offset, moovBox.offset + moovBox.size),
  291. ]);
  292. if (findTopLevelMp4Box(result, "moov").offset <= findTopLevelMp4Box(result, "mdat").offset) {
  293. throw new Error("没有生成 moov 位于 mdat 之后的 E2E 视频");
  294. }
  295. return result;
  296. }
  297. function findTopLevelMp4Box(source: Buffer, expectedType: string): Mp4Box {
  298. let offset = 0;
  299. while (offset + 8 <= source.byteLength) {
  300. const size = source.readUInt32BE(offset);
  301. const type = source.toString("ascii", offset + 4, offset + 8);
  302. if (size < 8 || offset + size > source.byteLength) {
  303. throw new Error(`无效的 MP4 top-level box: type=${type}, offset=${offset}, size=${size}`);
  304. }
  305. if (type === expectedType) return { offset, size, type };
  306. offset += size;
  307. }
  308. throw new Error(`MP4 E2E fixture 缺少 ${expectedType} box`);
  309. }
  310. async function waitForComposerMediaCards(expectedKinds: readonly MediaKind[]) {
  311. let cards: MediaCardState[] = [];
  312. await browser.waitUntil(
  313. async () => {
  314. cards = await browser.execute(readComposerMediaCardsFromDom, TID_V4_ATTACHMENT as string);
  315. return mediaCardsMatch(cards, expectedKinds, 48, false);
  316. },
  317. { timeout: 45_000, timeoutMsg: "Composer 媒体卡片没有按原顺序进入 ready" },
  318. );
  319. return cards;
  320. }
  321. async function waitForSentMediaCards(expectedKinds: readonly MediaKind[]) {
  322. let cards: MediaCardState[] = [];
  323. await browser.waitUntil(
  324. async () => {
  325. cards = await browser.execute(readSentMediaCardsFromDom, TID_V4_ROW_ATTACHMENTS as string);
  326. return mediaCardsMatch(cards, expectedKinds, 80, true);
  327. },
  328. { timeout: 45_000, timeoutMsg: "sent 媒体卡片/首帧没有按原顺序收敛" },
  329. );
  330. return cards;
  331. }
  332. function mediaCardsMatch(
  333. cards: MediaCardState[],
  334. expectedKinds: readonly MediaKind[],
  335. expectedSize: number,
  336. requireEveryPreview: boolean,
  337. ): boolean {
  338. return (
  339. cards.length === expectedKinds.length &&
  340. cards.every(
  341. (card, index) =>
  342. card.kind === expectedKinds[index] &&
  343. card.width === expectedSize &&
  344. card.height === expectedSize &&
  345. (card.uploadStatus === null || card.uploadStatus === "ready") &&
  346. (!requireEveryPreview || card.src.length > 0) &&
  347. (card.kind !== "image" || card.src.startsWith("blob:")) &&
  348. (card.kind !== "video" ||
  349. requireEveryPreview ||
  350. index === expectedKinds.length - 1 ||
  351. card.src.startsWith("blob:")),
  352. )
  353. );
  354. }
  355. // 编辑态载入的是 session-owned ref,图片不一定有本地 blob URL(见 chat-message-queue spec),
  356. // 因此不复用 waitForComposerMediaCards 的 blob/src 断言,只校验顺序、种类、ready 与 48px 尺寸。
  357. async function waitForEditedComposerMediaCards(expectedKinds: readonly MediaKind[]) {
  358. await browser.waitUntil(
  359. () =>
  360. browser.execute(
  361. (attachmentPrefix, kinds) => {
  362. const cards = Array.from(
  363. document.querySelectorAll<HTMLElement>(
  364. `[data-testid^="${attachmentPrefix}-"][data-upload-status]`,
  365. ),
  366. );
  367. return (
  368. cards.length === kinds.length &&
  369. cards.every((card, index) => {
  370. const rect = card.getBoundingClientRect();
  371. return (
  372. card.getAttribute("data-composer-attachment-kind") === kinds[index] &&
  373. card.getAttribute("data-upload-status") === "ready" &&
  374. Math.round(rect.width) === 48 &&
  375. Math.round(rect.height) === 48
  376. );
  377. })
  378. );
  379. },
  380. TID_V4_ATTACHMENT,
  381. [...expectedKinds],
  382. ),
  383. { timeout: 15_000, timeoutMsg: "v4 composer 编辑态媒体卡片状态没有收敛" },
  384. );
  385. }
  386. async function openComposerMedia(index: number) {
  387. const cards = await $$(`[data-testid^="${TID_V4_ATTACHMENT}-"][data-upload-status]`);
  388. const target = cards[index];
  389. if (!target) throw new Error(`Composer media card 不存在: index=${index}`);
  390. expect(await target.getAttribute("role")).toBe("button");
  391. await target.waitForClickable({
  392. timeout: 15_000,
  393. timeoutMsg: `Composer media card 不可点击: index=${index}`,
  394. });
  395. await target.click();
  396. }
  397. async function openSentMedia(index: number) {
  398. const groups = await $$(
  399. `[data-testid^="${TID_V4_ROW_ATTACHMENTS}-"] [data-v4-user-input-media-attachments="true"]`,
  400. );
  401. const group = groups[0];
  402. if (!group) throw new Error("sent media attachment group 不存在");
  403. const cards = await group.$$('[data-v4-user-input-media-attachment="true"]');
  404. const target = cards[index];
  405. if (!target) throw new Error(`sent media card 不存在: index=${index}`);
  406. expect(await target.getAttribute("role")).toBe("button");
  407. await target.waitForClickable({
  408. timeout: 15_000,
  409. timeoutMsg: `sent media card 不可点击: index=${index}`,
  410. });
  411. await target.click();
  412. }
  413. async function waitForPlayableVideo(filename: string, expectedSrc?: string) {
  414. await browser.waitUntil(
  415. async () => {
  416. const state = await browser.execute(readGalleryStateFromDom);
  417. return (
  418. state.title === filename &&
  419. state.kind === "video" &&
  420. (expectedSrc ? state.src === expectedSrc : state.src.startsWith("blob:")) &&
  421. state.readyState >= 1 &&
  422. !state.error &&
  423. state.controls &&
  424. state.playsInline &&
  425. !state.autoplay &&
  426. state.hasNavigation &&
  427. !state.hasImageTools
  428. );
  429. },
  430. { timeout: 30_000, timeoutMsg: `${filename} 没有进入共享 gallery 的可播放 video` },
  431. );
  432. }
  433. async function waitForGalleryImage(filename: string) {
  434. await browser.waitUntil(
  435. async () => {
  436. const state = await browser.execute(readGalleryStateFromDom);
  437. return (
  438. state.title === filename &&
  439. state.kind === "image" &&
  440. state.alt === filename &&
  441. state.src.startsWith("blob:") &&
  442. state.hasNavigation &&
  443. state.hasImageTools
  444. );
  445. },
  446. { timeout: 15_000, timeoutMsg: `${filename} 没有进入共享 gallery 的图片项` },
  447. );
  448. }
  449. async function waitForUnsupportedVideo(filename: string) {
  450. await browser.waitUntil(
  451. async () => {
  452. const state = await browser.execute(readGalleryStateFromDom);
  453. return (
  454. state.title === filename &&
  455. (state.alertText.includes("can still be sent") ||
  456. state.alertText.includes("可以正常发送")) &&
  457. state.hasNavigation &&
  458. !state.hasImageTools
  459. );
  460. },
  461. { timeout: 15_000, timeoutMsg: `${filename} 没有展示可导航的非阻断预览错误` },
  462. );
  463. }
  464. async function installVideoBlobProbe() {
  465. await browser.execute(() => {
  466. const probeWindow = window as Window & {
  467. __zcodeVideoBlobProbe?: {
  468. calls: Array<{ size: number; type: string }>;
  469. original: typeof URL.createObjectURL;
  470. };
  471. };
  472. const original = URL.createObjectURL.bind(URL);
  473. const calls: Array<{ size: number; type: string }> = [];
  474. probeWindow.__zcodeVideoBlobProbe = { calls, original };
  475. URL.createObjectURL = (object: Blob | MediaSource) => {
  476. if (object instanceof Blob) calls.push({ size: object.size, type: object.type });
  477. return original(object);
  478. };
  479. });
  480. }
  481. async function waitForVideoBlob(mediaType: string) {
  482. await browser.waitUntil(
  483. () =>
  484. browser.execute((expectedMediaType) => {
  485. const probeWindow = window as Window & {
  486. __zcodeVideoBlobProbe?: { calls: Array<{ size: number; type: string }> };
  487. };
  488. return (
  489. probeWindow.__zcodeVideoBlobProbe?.calls.some(
  490. (call) => call.type === expectedMediaType && call.size > 0,
  491. ) === true
  492. );
  493. }, mediaType),
  494. { timeout: 30_000, timeoutMsg: `${mediaType} 没有通过分片字节创建 Blob URL` },
  495. );
  496. }
  497. async function readVideoBlobCalls(): Promise<Array<{ size: number; type: string }>> {
  498. return browser.execute(() => {
  499. const probeWindow = window as Window & {
  500. __zcodeVideoBlobProbe?: { calls: Array<{ size: number; type: string }> };
  501. };
  502. return probeWindow.__zcodeVideoBlobProbe?.calls ?? [];
  503. });
  504. }
  505. async function restoreVideoBlobProbe() {
  506. await browser.execute(() => {
  507. const probeWindow = window as Window & {
  508. __zcodeVideoBlobProbe?: { original: typeof URL.createObjectURL };
  509. };
  510. const probe = probeWindow.__zcodeVideoBlobProbe;
  511. if (probe) URL.createObjectURL = probe.original;
  512. delete probeWindow.__zcodeVideoBlobProbe;
  513. });
  514. }
  515. async function clickGalleryNavigation(direction: "next" | "previous") {
  516. const labels =
  517. direction === "next" ? ["Next image", "下一张图片"] : ["Previous image", "上一张图片"];
  518. for (const label of labels) {
  519. const button = await $(`[role="dialog"] button[aria-label="${label}"]`);
  520. if (!(await button.isExisting())) continue;
  521. await button.waitForClickable({
  522. timeout: 15_000,
  523. timeoutMsg: `media gallery ${direction} 按钮不可点击`,
  524. });
  525. await button.click();
  526. return;
  527. }
  528. throw new Error(`media gallery ${direction} 按钮不存在`);
  529. }
  530. async function closeMediaPreview() {
  531. await browser.keys(["Escape"]);
  532. await browser.waitUntil(() => browser.execute(() => !document.querySelector('[role="dialog"]')), {
  533. timeout: 10_000,
  534. timeoutMsg: "media gallery Dialog 没有关闭",
  535. });
  536. }
  537. function localMediaPath(src: string | undefined): string {
  538. if (!src) throw new Error("本地媒体 URL 不存在");
  539. const url = new URL(src);
  540. expect(url.protocol).toBe("zcode-media:");
  541. const path = url.searchParams.get("path");
  542. if (!path) throw new Error(`本地媒体 URL 缺少 path: ${src}`);
  543. return path;
  544. }
  545. async function expectUnauthorizedLocalMediaPathRejected(path: string) {
  546. const result = await browser.executeAsync((candidatePath, done) => {
  547. const url = new URL("zcode-media://local/preview");
  548. url.searchParams.set("path", candidatePath);
  549. // 旧协议会被这个 renderer 自报 MIME 绕过;新协议只认 Main 的精确路径授权集合。
  550. url.searchParams.set("mediaType", "video/mp4");
  551. const video = document.createElement("video");
  552. const timer = window.setTimeout(() => done("timeout"), 10_000);
  553. video.addEventListener(
  554. "loadedmetadata",
  555. () => {
  556. window.clearTimeout(timer);
  557. done("loaded");
  558. },
  559. { once: true },
  560. );
  561. video.addEventListener(
  562. "error",
  563. () => {
  564. window.clearTimeout(timer);
  565. done("error");
  566. },
  567. { once: true },
  568. );
  569. video.src = url.toString();
  570. video.load();
  571. }, path);
  572. expect(result).toBe("error");
  573. }
  574. async function seekPreviewVideo(filename: string) {
  575. const targetTime = await browser.execute((expectedTitle) => {
  576. const dialog = document.querySelector<HTMLElement>('[role="dialog"]');
  577. const title = dialog?.querySelector("h2")?.textContent?.trim();
  578. const video = dialog?.querySelector<HTMLVideoElement>("video");
  579. if (
  580. title !== expectedTitle ||
  581. !video ||
  582. !Number.isFinite(video.duration) ||
  583. video.duration <= 0
  584. ) {
  585. return null;
  586. }
  587. const target = Math.min(Math.max(video.duration / 2, 0.1), video.duration - 0.05);
  588. video.currentTime = target;
  589. return target;
  590. }, filename);
  591. if (targetTime === null) throw new Error(`${filename} 不具备可 seek 的媒体元数据`);
  592. let lastState: Record<string, unknown> | null = null;
  593. await browser
  594. .waitUntil(
  595. async () => {
  596. const state = await browser.execute(
  597. (expectedTitle, expectedTime) => {
  598. const dialog = document.querySelector<HTMLElement>('[role="dialog"]');
  599. const title = dialog?.querySelector("h2")?.textContent?.trim();
  600. const video = dialog?.querySelector<HTMLVideoElement>("video");
  601. return {
  602. currentTime: video?.currentTime ?? null,
  603. duration: video?.duration ?? null,
  604. errorCode: video?.error?.code ?? null,
  605. networkState: video?.networkState ?? null,
  606. readyState: video?.readyState ?? null,
  607. seekable: video
  608. ? Array.from({ length: video.seekable.length }, (_, index) => [
  609. video.seekable.start(index),
  610. video.seekable.end(index),
  611. ])
  612. : [],
  613. seeking: video?.seeking ?? null,
  614. success:
  615. title === expectedTitle &&
  616. Boolean(video) &&
  617. !video?.seeking &&
  618. Math.abs((video?.currentTime ?? 0) - expectedTime) < 0.25,
  619. title,
  620. };
  621. },
  622. filename,
  623. targetTime,
  624. );
  625. lastState = state;
  626. return state.success;
  627. },
  628. { timeout: 15_000, timeoutMsg: `${filename} 没有通过本地媒体协议完成 seek` },
  629. )
  630. .catch((error) => {
  631. throw new Error(`${filename} seek 状态异常: ${JSON.stringify(lastState)}`, {
  632. cause: error,
  633. });
  634. });
  635. }
  636. function readComposerMediaCardsFromDom(attachmentPrefix: string): MediaCardState[] {
  637. const elements = Array.from(
  638. document.querySelectorAll<HTMLElement>(
  639. `[data-testid^="${attachmentPrefix}-"][data-upload-status]`,
  640. ),
  641. );
  642. return elements.map((element) => {
  643. const overlay = element.querySelector('[data-attachment-video-play-overlay="true"]');
  644. const media = element.querySelector<HTMLImageElement | HTMLVideoElement>("img, video");
  645. const rect = element.getBoundingClientRect();
  646. return {
  647. height: Math.round(rect.height),
  648. kind: overlay ? "video" : "image",
  649. role: element.getAttribute("role"),
  650. src: media?.src ?? "",
  651. uploadStatus: element.getAttribute("data-upload-status"),
  652. width: Math.round(rect.width),
  653. };
  654. });
  655. }
  656. function readSentMediaCardsFromDom(attachmentsPrefix: string): MediaCardState[] {
  657. const group = document.querySelector<HTMLElement>(
  658. `[data-testid^="${attachmentsPrefix}-"] [data-v4-user-input-media-attachments="true"]`,
  659. );
  660. const elements = Array.from(
  661. group?.querySelectorAll<HTMLElement>(':scope > [data-v4-user-input-media-attachment="true"]') ??
  662. [],
  663. );
  664. return elements.map((element) => {
  665. const overlay = element.querySelector('[data-attachment-video-play-overlay="true"]');
  666. const media = element.querySelector<HTMLImageElement | HTMLVideoElement>("img, video");
  667. const rect = element.getBoundingClientRect();
  668. return {
  669. height: Math.round(rect.height),
  670. kind: overlay ? "video" : "image",
  671. role: element.getAttribute("role"),
  672. src: media?.src ?? "",
  673. uploadStatus: element.getAttribute("data-upload-status"),
  674. width: Math.round(rect.width),
  675. };
  676. });
  677. }
  678. function readGalleryStateFromDom(): GalleryState {
  679. const dialog = document.querySelector<HTMLElement>('[role="dialog"]');
  680. const image = dialog?.querySelector<HTMLImageElement>("img");
  681. const video = dialog?.querySelector<HTMLVideoElement>("video");
  682. const labels = Array.from(
  683. dialog?.querySelectorAll<HTMLButtonElement>("button[aria-label]") ?? [],
  684. ).map((button) => button.getAttribute("aria-label"));
  685. const hasLabel = (...candidates: string[]) =>
  686. labels.some((label) => label !== null && candidates.includes(label));
  687. return {
  688. alertText: dialog?.querySelector<HTMLElement>('[role="alert"]')?.innerText ?? "",
  689. alt: image?.alt ?? "",
  690. autoplay: video?.autoplay ?? false,
  691. controls: video?.controls ?? false,
  692. error: Boolean(video?.error),
  693. hasImageTools:
  694. hasLabel("Download image", "下载图片") &&
  695. hasLabel("Zoom in", "放大") &&
  696. hasLabel("Zoom out", "缩小"),
  697. hasNavigation: hasLabel("Previous image", "上一张图片") && hasLabel("Next image", "下一张图片"),
  698. kind: video ? "video" : image ? "image" : "none",
  699. playsInline: video?.playsInline ?? false,
  700. readyState: video?.readyState ?? 0,
  701. src: video?.src ?? image?.src ?? "",
  702. title: dialog?.querySelector("h2")?.textContent?.trim() ?? "",
  703. };
  704. }