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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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 } from "node:fs/promises";
  8. import { join } from "node:path";
  9. import { fileURLToPath } from "node:url";
  10. import type { ElectronMock } from "@wdio/electron-types";
  11. import {
  12. TID_CHAT_ATTACHMENT_BUTTON,
  13. TID_CHAT_ATTACHMENT_MENU_ITEM,
  14. TID_V4_ATTACHMENT,
  15. TID_V4_EDIT_ATTACHMENT_REMOVE,
  16. TID_V4_EDIT_SUBMIT,
  17. TID_V4_ROW_ATTACHMENTS,
  18. testId,
  19. } from "@zcode/shared";
  20. import { PROTOCOL_V4_LIMITS } from "@zcode/shared/zcode-protocol-v4";
  21. import { DEFAULT_WORKSPACE, clearAppData, clickTestIdByDom } from "../helpers/desktop-app.js";
  22. import { restartIntoWorkspacePreservingProfile } from "../helpers/model-provider-restart.js";
  23. import {
  24. beginFirstV4UserQueryEdit,
  25. clickV4Send,
  26. pasteV4ComposerFileAttachment,
  27. pasteV4ComposerImageAttachment,
  28. prepareV4ConversationE2E,
  29. selectV4TaskById,
  30. waitForV4Pane,
  31. waitForV4TimelineContaining,
  32. } from "../helpers/v4-conversation.js";
  33. const CASE_ROOT = join(DEFAULT_WORKSPACE, ".zcode-e2e", "conversation-session-v4-video-preview");
  34. const PLAYABLE_VIDEO_FILENAME = "e2e-composer-preview.mp4";
  35. const GALLERY_IMAGE_FILENAME = "e2e-gallery-image.png";
  36. const UNSUPPORTED_VIDEO_FILENAME = "e2e-unsupported.mov";
  37. const LARGE_VIDEO_FILENAME = "e2e-sent-large.mp4";
  38. const CHUNK_FALLBACK_VIDEO_FILENAME = "e2e-chunk-fallback.ogg";
  39. const VIDEO_SOURCE_PATH = fileURLToPath(
  40. new URL("../fixtures/media/sample-video.mp4", import.meta.url),
  41. );
  42. const MEDIA_KINDS = ["video", "image", "video", "video", "video"] as const;
  43. type MediaKind = "image" | "video";
  44. type MediaCardState = {
  45. height: number;
  46. kind: MediaKind;
  47. role: string | null;
  48. src: string;
  49. uploadStatus: string | null;
  50. width: number;
  51. };
  52. type GalleryState = {
  53. alertText: string;
  54. alt: string;
  55. autoplay: boolean;
  56. controls: boolean;
  57. error: boolean;
  58. hasImageTools: boolean;
  59. hasNavigation: boolean;
  60. kind: "image" | "none" | "video";
  61. playsInline: boolean;
  62. readyState: number;
  63. src: string;
  64. title: string;
  65. };
  66. describe("v4 VI06/VI07:image/video 媒体 gallery 与 edit", () => {
  67. after(async () => {
  68. await browser.electron.restoreAllMocks();
  69. await clearAppData();
  70. await rm(CASE_ROOT, { recursive: true, force: true });
  71. });
  72. it("混合媒体首发 → sent gallery/reopen → edit 索引/删除", async () => {
  73. await prepareV4ConversationE2E();
  74. // Bug 根因:旧 E2E 只使用 moov 在 mdat 前的 fast-start MP4,无法触发自定义
  75. // scheme 对文件尾元数据的读取;改用同一可播 fixture 的尾部 moov 形态覆盖真实回归。
  76. const sourceVideo = moveMoovBoxBehindMediaData(await readFile(VIDEO_SOURCE_PATH));
  77. const largeVideoPath = join(CASE_ROOT, LARGE_VIDEO_FILENAME);
  78. await mkdir(CASE_ROOT, { recursive: true });
  79. await createSparseLargePlayableMp4(largeVideoPath, sourceVideo);
  80. const showOpenDialogMock = await browser.electron.mock("dialog", "showOpenDialog");
  81. await pasteV4ComposerFileAttachment(PLAYABLE_VIDEO_FILENAME, {
  82. base64: sourceVideo.toString("base64"),
  83. mimeType: "video/mp4",
  84. });
  85. await pasteV4ComposerImageAttachment(GALLERY_IMAGE_FILENAME);
  86. await pasteV4ComposerFileAttachment(UNSUPPORTED_VIDEO_FILENAME, {
  87. base64: Buffer.from("not playable", "utf8").toString("base64"),
  88. mimeType: "video/quicktime",
  89. });
  90. // `video/ogg` 可以进入 video 语义,但现有 artifact 派生缓存没有对应扩展名;
  91. // 它固定覆盖 local source 不可用时仍走既有分片/Blob 预览,而不是新增测试开关。
  92. await pasteV4ComposerFileAttachment(CHUNK_FALLBACK_VIDEO_FILENAME, {
  93. base64: Buffer.from("not playable", "utf8").toString("base64"),
  94. mimeType: "video/ogg",
  95. });
  96. await pickNativeFiles([largeVideoPath], showOpenDialogMock);
  97. const composerCards = await waitForComposerMediaCards(MEDIA_KINDS);
  98. expect(composerCards.map(({ width }) => width)).toEqual([48, 48, 48, 48, 48]);
  99. expect(composerCards.map(({ height }) => height)).toEqual([48, 48, 48, 48, 48]);
  100. expect(composerCards.map(({ role }) => role)).toEqual([
  101. "button",
  102. "button",
  103. "button",
  104. "button",
  105. null,
  106. ]);
  107. expect(composerCards.slice(0, 4).every(({ src }) => src.startsWith("blob:"))).toBe(true);
  108. expect(composerCards[4]?.src.startsWith("blob:")).toBe(false);
  109. await openComposerMedia(0);
  110. await waitForPlayableVideo(PLAYABLE_VIDEO_FILENAME);
  111. await browser.keys(["ArrowRight"]);
  112. await waitForGalleryImage(GALLERY_IMAGE_FILENAME);
  113. await clickGalleryNavigation("next");
  114. await waitForUnsupportedVideo(UNSUPPORTED_VIDEO_FILENAME);
  115. await clickGalleryNavigation("previous");
  116. await waitForGalleryImage(GALLERY_IMAGE_FILENAME);
  117. await browser.keys(["ArrowLeft"]);
  118. await waitForPlayableVideo(PLAYABLE_VIDEO_FILENAME);
  119. await browser.keys(["ArrowLeft"]);
  120. await waitForUnsupportedVideo(CHUNK_FALLBACK_VIDEO_FILENAME);
  121. await closeMediaPreview();
  122. // 点击中间图片必须从其原始 gallery 位置打开,而不是每次都回到第一项。
  123. await openComposerMedia(1);
  124. await waitForGalleryImage(GALLERY_IMAGE_FILENAME);
  125. await closeMediaPreview();
  126. await installVideoBlobProbe();
  127. await clickV4Send();
  128. await waitForV4TimelineContaining("V4_VIDEO_PREVIEW_SEND_OK", 45_000);
  129. const sentSession = await waitForV4Pane(
  130. (state) => !state.canStop && state.sessionId !== "draft" && state.sessionId !== null,
  131. "混合媒体首发后没有回到空闲态且绑定 session",
  132. 45_000,
  133. );
  134. const sessionId = sentSession.sessionId;
  135. if (!sessionId || sessionId === "draft") {
  136. throw new Error(`混合媒体首发后缺少真实 sessionId: ${sessionId ?? "null"}`);
  137. }
  138. const sentCards = await waitForSentMediaCards(MEDIA_KINDS);
  139. expect(sentCards.map(({ width }) => width)).toEqual([80, 80, 80, 80, 80]);
  140. expect(sentCards.map(({ height }) => height)).toEqual([80, 80, 80, 80, 80]);
  141. expect(sentCards.every(({ role }) => role === "button")).toBe(true);
  142. expect(sentCards[0]?.src.startsWith("zcode-media:")).toBe(true);
  143. expect(sentCards[1]?.src.startsWith("blob:")).toBe(true);
  144. expect(sentCards[2]?.src.startsWith("zcode-media:")).toBe(true);
  145. expect(sentCards[3]?.src.startsWith("blob:")).toBe(true);
  146. expect(sentCards[4]?.src.startsWith("zcode-media:")).toBe(true);
  147. expect(localMediaPath(sentCards[0]?.src).split(/[\\/]/)).toContain("video-cache");
  148. expect(localMediaPath(sentCards[4]?.src)).toBe(largeVideoPath);
  149. await expectUnauthorizedLocalMediaPathRejected(VIDEO_SOURCE_PATH);
  150. await waitForVideoBlob("video/ogg");
  151. expect(
  152. (await readVideoBlobCalls()).every(
  153. ({ size, type }) => !type.startsWith("video/") || size <= sourceVideo.byteLength,
  154. ),
  155. ).toBe(true);
  156. await restoreVideoBlobProbe();
  157. const largeVideoThumbnailSrc = sentCards[4]?.src;
  158. expect(largeVideoThumbnailSrc).toBeTruthy();
  159. await openSentMedia(4);
  160. await waitForPlayableVideo(LARGE_VIDEO_FILENAME, largeVideoThumbnailSrc);
  161. await seekPreviewVideo(LARGE_VIDEO_FILENAME);
  162. await browser.keys(["ArrowRight"]);
  163. await waitForPlayableVideo(PLAYABLE_VIDEO_FILENAME, sentCards[0]?.src);
  164. await browser.keys(["ArrowRight"]);
  165. await waitForGalleryImage(GALLERY_IMAGE_FILENAME);
  166. await clickGalleryNavigation("next");
  167. await waitForUnsupportedVideo(UNSUPPORTED_VIDEO_FILENAME);
  168. await closeMediaPreview();
  169. // 分片 fallback 项关闭后仍能从原位置重开,并能继续导航到本地路径项。
  170. await openSentMedia(3);
  171. await waitForUnsupportedVideo(CHUNK_FALLBACK_VIDEO_FILENAME);
  172. await clickGalleryNavigation("next");
  173. await waitForPlayableVideo(LARGE_VIDEO_FILENAME, largeVideoThumbnailSrc);
  174. await closeMediaPreview();
  175. const rowId = await beginFirstV4UserQueryEdit("");
  176. await waitForEditedMediaCards(rowId, MEDIA_KINDS);
  177. await clickTestIdByDom(testId(TID_V4_EDIT_ATTACHMENT_REMOVE, `${rowId}-0`), {
  178. timeout: 15_000,
  179. timeoutMsg: `v4 edit 第一个 video 删除按钮没有出现: rowId=${rowId}`,
  180. });
  181. await waitForEditedMediaCards(rowId, ["image", "video", "video", "video"]);
  182. // 删除原索引 0 后,大视频展示索引前移,但 preview query 仍必须携带持久化原索引 4。
  183. await openEditedMedia(rowId, 3);
  184. await waitForPlayableVideo(LARGE_VIDEO_FILENAME, largeVideoThumbnailSrc);
  185. await browser.keys(["ArrowRight"]);
  186. await waitForGalleryImage(GALLERY_IMAGE_FILENAME);
  187. await closeMediaPreview();
  188. await clickTestIdByDom(testId(TID_V4_EDIT_SUBMIT, rowId), {
  189. timeout: 15_000,
  190. timeoutMsg: `v4 mixed media edit 提交按钮不可点击: rowId=${rowId}`,
  191. });
  192. await waitForV4TimelineContaining("V4_VIDEO_PREVIEW_EDIT_OK", 45_000);
  193. const editedSentCards = await waitForSentMediaCards(["image", "video", "video", "video"]);
  194. expect(editedSentCards[3]?.src.startsWith("zcode-media:")).toBe(true);
  195. await openSentMedia(3);
  196. await waitForPlayableVideo(LARGE_VIDEO_FILENAME, editedSentCards[3]?.src);
  197. await closeMediaPreview();
  198. await restartIntoWorkspacePreservingProfile();
  199. await selectV4TaskById(sessionId, 60_000);
  200. await waitForV4Pane(
  201. (state) =>
  202. state.sessionId === sessionId && state.timelineText.includes("V4_VIDEO_PREVIEW_EDIT_OK"),
  203. `完整进程重启后没有冷恢复视频会话 ${sessionId}`,
  204. 90_000,
  205. );
  206. const coldCards = await waitForSentMediaCards(["image", "video", "video", "video"]);
  207. expect(localMediaPath(coldCards[1]?.src).split(/[\\/]/)).toContain("video-cache");
  208. expect(coldCards[2]?.src.startsWith("blob:")).toBe(true);
  209. expect(localMediaPath(coldCards[3]?.src)).toBe(largeVideoPath);
  210. await openSentMedia(3);
  211. await waitForPlayableVideo(LARGE_VIDEO_FILENAME, coldCards[3]?.src);
  212. await seekPreviewVideo(LARGE_VIDEO_FILENAME);
  213. await closeMediaPreview();
  214. await openSentMedia(2);
  215. await waitForUnsupportedVideo(CHUNK_FALLBACK_VIDEO_FILENAME);
  216. await closeMediaPreview();
  217. }).timeout(360_000);
  218. });
  219. async function createSparseLargePlayableMp4(path: string, source: Buffer): Promise<void> {
  220. const targetBytes = PROTOCOL_V4_LIMITS.attachmentPreviewMaxBytes + 1024 * 1024;
  221. const moovBox = findTopLevelMp4Box(source, "moov");
  222. if (moovBox.offset + moovBox.size !== source.byteLength) {
  223. throw new Error("非 fast-start E2E 视频的 moov box 必须位于文件末尾");
  224. }
  225. const prefix = source.subarray(0, moovBox.offset);
  226. const moov = source.subarray(moovBox.offset);
  227. const freeBoxBytes = targetBytes - prefix.byteLength - moov.byteLength;
  228. if (freeBoxBytes < 8) throw new Error("大视频 E2E fixture 没有足够空间写入 free box");
  229. const freeBoxHeader = Buffer.alloc(8);
  230. freeBoxHeader.writeUInt32BE(freeBoxBytes, 0);
  231. freeBoxHeader.write("free", 4, "ascii");
  232. const file = await open(path, "w");
  233. try {
  234. await file.write(prefix, 0, prefix.byteLength, 0);
  235. await file.write(freeBoxHeader, 0, freeBoxHeader.byteLength, prefix.byteLength);
  236. await file.write(moov, 0, moov.byteLength, targetBytes - moov.byteLength);
  237. } finally {
  238. await file.close();
  239. }
  240. }
  241. type Mp4Box = { offset: number; size: number; type: string };
  242. function moveMoovBoxBehindMediaData(source: Buffer): Buffer {
  243. const moovBox = findTopLevelMp4Box(source, "moov");
  244. const mdatBox = findTopLevelMp4Box(source, "mdat");
  245. if (moovBox.offset > mdatBox.offset) return source;
  246. // 保留原 moov 占用的字节,避免移动 mdat 后让 chunk offset 失效。
  247. const placeholder = Buffer.alloc(moovBox.size);
  248. placeholder.writeUInt32BE(moovBox.size, 0);
  249. placeholder.write("free", 4, "ascii");
  250. const result = Buffer.concat([
  251. source.subarray(0, moovBox.offset),
  252. placeholder,
  253. source.subarray(moovBox.offset + moovBox.size),
  254. source.subarray(moovBox.offset, moovBox.offset + moovBox.size),
  255. ]);
  256. if (findTopLevelMp4Box(result, "moov").offset <= findTopLevelMp4Box(result, "mdat").offset) {
  257. throw new Error("没有生成 moov 位于 mdat 之后的 E2E 视频");
  258. }
  259. return result;
  260. }
  261. function findTopLevelMp4Box(source: Buffer, expectedType: string): Mp4Box {
  262. let offset = 0;
  263. while (offset + 8 <= source.byteLength) {
  264. const size = source.readUInt32BE(offset);
  265. const type = source.toString("ascii", offset + 4, offset + 8);
  266. if (size < 8 || offset + size > source.byteLength) {
  267. throw new Error(`无效的 MP4 top-level box: type=${type}, offset=${offset}, size=${size}`);
  268. }
  269. if (type === expectedType) return { offset, size, type };
  270. offset += size;
  271. }
  272. throw new Error(`MP4 E2E fixture 缺少 ${expectedType} box`);
  273. }
  274. async function pickNativeFiles(paths: string[], showOpenDialogMock: ElectronMock) {
  275. await showOpenDialogMock.mockResolvedValueOnce({ canceled: false, filePaths: paths });
  276. const trigger = await $(`[data-testid="${TID_CHAT_ATTACHMENT_BUTTON}"]`);
  277. await trigger.waitForClickable({ timeout: 15_000 });
  278. await trigger.click();
  279. const menuItem = await $(`[data-testid="${TID_CHAT_ATTACHMENT_MENU_ITEM}"]`);
  280. await menuItem.waitForClickable({ timeout: 10_000 });
  281. await menuItem.click();
  282. await expect(showOpenDialogMock).toHaveBeenCalledWith({
  283. properties: ["openFile", "multiSelections"],
  284. });
  285. }
  286. async function waitForComposerMediaCards(expectedKinds: readonly MediaKind[]) {
  287. let cards: MediaCardState[] = [];
  288. await browser.waitUntil(
  289. async () => {
  290. cards = await browser.execute(readComposerMediaCardsFromDom, TID_V4_ATTACHMENT as string);
  291. return mediaCardsMatch(cards, expectedKinds, 48, false);
  292. },
  293. { timeout: 45_000, timeoutMsg: "Composer 媒体卡片没有按原顺序进入 ready" },
  294. );
  295. return cards;
  296. }
  297. async function waitForSentMediaCards(expectedKinds: readonly MediaKind[]) {
  298. let cards: MediaCardState[] = [];
  299. await browser.waitUntil(
  300. async () => {
  301. cards = await browser.execute(readSentMediaCardsFromDom, TID_V4_ROW_ATTACHMENTS as string);
  302. return mediaCardsMatch(cards, expectedKinds, 80, true);
  303. },
  304. { timeout: 45_000, timeoutMsg: "sent 媒体卡片/首帧没有按原顺序收敛" },
  305. );
  306. return cards;
  307. }
  308. function mediaCardsMatch(
  309. cards: MediaCardState[],
  310. expectedKinds: readonly MediaKind[],
  311. expectedSize: number,
  312. requireEveryPreview: boolean,
  313. ): boolean {
  314. return (
  315. cards.length === expectedKinds.length &&
  316. cards.every(
  317. (card, index) =>
  318. card.kind === expectedKinds[index] &&
  319. card.width === expectedSize &&
  320. card.height === expectedSize &&
  321. (card.uploadStatus === null || card.uploadStatus === "ready") &&
  322. (!requireEveryPreview || card.src.length > 0) &&
  323. (card.kind !== "image" || card.src.startsWith("blob:")) &&
  324. (card.kind !== "video" ||
  325. requireEveryPreview ||
  326. index === expectedKinds.length - 1 ||
  327. card.src.startsWith("blob:")),
  328. )
  329. );
  330. }
  331. async function waitForEditedMediaCards(rowId: number, expectedKinds: readonly MediaKind[]) {
  332. const attachmentsTestId = testId(TID_V4_ROW_ATTACHMENTS, String(rowId)) as string;
  333. await browser.waitUntil(
  334. () =>
  335. browser.execute(
  336. (attachmentsTestId, kinds) => {
  337. const group = document.querySelector<HTMLElement>(`[data-testid="${attachmentsTestId}"]`);
  338. const cards = Array.from(
  339. group?.querySelectorAll<HTMLElement>("[data-v4-user-edit-attachment-kind]") ?? [],
  340. );
  341. return (
  342. cards.length === kinds.length &&
  343. cards.every((card, index) => {
  344. const rect = card.getBoundingClientRect();
  345. return (
  346. card.getAttribute("data-v4-user-edit-attachment-kind") === kinds[index] &&
  347. Math.round(rect.width) === 48 &&
  348. Math.round(rect.height) === 48
  349. );
  350. })
  351. );
  352. },
  353. attachmentsTestId,
  354. [...expectedKinds],
  355. ),
  356. { timeout: 15_000, timeoutMsg: `v4 edit 媒体卡片状态没有收敛: rowId=${rowId}` },
  357. );
  358. }
  359. async function openComposerMedia(index: number) {
  360. const cards = await $$(`[data-testid^="${TID_V4_ATTACHMENT}-"][data-upload-status]`);
  361. const target = cards[index];
  362. if (!target) throw new Error(`Composer media card 不存在: index=${index}`);
  363. expect(await target.getAttribute("role")).toBe("button");
  364. await target.waitForClickable({
  365. timeout: 15_000,
  366. timeoutMsg: `Composer media card 不可点击: index=${index}`,
  367. });
  368. await target.click();
  369. }
  370. async function openSentMedia(index: number) {
  371. const groups = await $$(
  372. `[data-testid^="${TID_V4_ROW_ATTACHMENTS}-"] [data-v4-user-input-media-attachments="true"]`,
  373. );
  374. const group = groups[0];
  375. if (!group) throw new Error("sent media attachment group 不存在");
  376. const cards = await group.$$('[data-v4-user-input-media-attachment="true"]');
  377. const target = cards[index];
  378. if (!target) throw new Error(`sent media card 不存在: index=${index}`);
  379. expect(await target.getAttribute("role")).toBe("button");
  380. await target.waitForClickable({
  381. timeout: 15_000,
  382. timeoutMsg: `sent media card 不可点击: index=${index}`,
  383. });
  384. await target.click();
  385. }
  386. async function openEditedMedia(rowId: number, index: number) {
  387. const attachmentsTestId = testId(TID_V4_ROW_ATTACHMENTS, String(rowId)) as string;
  388. const group = await $(`[data-testid="${attachmentsTestId}"]`);
  389. await group.waitForExist({
  390. timeout: 15_000,
  391. timeoutMsg: `v4 edit media attachment group 不存在: rowId=${rowId}`,
  392. });
  393. const cards = await group.$$("[data-v4-user-edit-attachment-kind]");
  394. const target = cards[index];
  395. if (!target) throw new Error(`v4 edit media card 不存在: rowId=${rowId}, index=${index}`);
  396. expect(await target.getAttribute("role")).toBe("button");
  397. await target.waitForClickable({
  398. timeout: 15_000,
  399. timeoutMsg: `v4 edit media card 不可点击: rowId=${rowId}, 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. }