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

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