conversation-session-r3-media-preview.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import { selectTaskOrganizeMode } from "#e2e/helpers/workspace-agent-warmup";
  2. import {
  3. disconnectRemoteSource,
  4. reconnectRemoteProject,
  5. } from "#e2e/helpers/remote-project-actions";
  6. import { mkdir, readFile, writeFile } from "node:fs/promises";
  7. import { createHash } from "node:crypto";
  8. import { resolve } from "node:path";
  9. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  10. import { TID_V4_SESSION_PANE, testId } from "@zcode/shared/test-ids";
  11. import { clearAppData, waitForWorkspaceApp } from "#e2e/helpers/desktop-app";
  12. import {
  13. getUpstreamRequestRecordCount,
  14. getUpstreamRequestEvidence,
  15. waitForUpstreamRequest,
  16. } from "#e2e/helpers/conversation-session-network";
  17. import {
  18. connectSSHWorkspaceAndSendFirstTurn,
  19. prepareSSHLifecycle,
  20. type SSHLifecycleProvider,
  21. } from "#e2e/helpers/ssh-remote-lifecycle";
  22. import { readRemoteTabSnapshot, runSSHCommand } from "#e2e/helpers/ssh-remote-p0";
  23. import {
  24. clickV4Send,
  25. pasteV4ComposerFileAttachment,
  26. selectV4TaskById,
  27. setV4ComposerText,
  28. waitForV4AssistantMessageContaining,
  29. waitForV4ConversationState,
  30. waitForV4RowAttachments,
  31. } from "#e2e/helpers/v4-conversation";
  32. const CASE_MARKER = "E2E_R3_MEDIA_PREVIEW";
  33. const artifactDir = resolve(
  34. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-media-preview",
  35. );
  36. const IMAGE_FILE = "r3-dev05-preview.png";
  37. // 2x2 红色 PNG(有效、可解码),用于校验预览真实加载出像素尺寸。
  38. const PNG_2X2_BASE64 =
  39. "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAEElEQVR4nGP4z8AARAwQCgAf7gP9i18U1AAAAABJRU5ErkJggg==";
  40. interface GalleryState {
  41. open: boolean;
  42. imageLoaded: boolean;
  43. naturalWidth: number;
  44. src: string;
  45. errorText: string;
  46. // 超时后补齐的现场事实:同一段点击代码在线时能打开 gallery,重连后打不开,
  47. // 必须知道"卡片是什么状态、有没有 portal 挂载"才能区分时序与产品行为。
  48. diagnostics?: unknown;
  49. }
  50. async function openSentImageAndReadGallery(requireCard = true): Promise<GalleryState> {
  51. const paneSelector = `[data-testid="${testId(TID_V4_SESSION_PANE, "workspace-main")}"]`;
  52. const clickCard = async () => {
  53. // 重连可能保留退场内容;限定主 pane,并使用用户可达的真实指针,不点击全局旧 DOM。
  54. const card = $(
  55. `${paneSelector} [data-v4-user-input-media-attachment="true"]:has(img[alt=${JSON.stringify(IMAGE_FILE)}])`,
  56. );
  57. if (
  58. !(await card.isDisplayed()) ||
  59. (await card.getAttribute("role")) !== "button" ||
  60. (await card.getAttribute("aria-disabled")) === "true"
  61. )
  62. return false;
  63. await card.scrollIntoView({ block: "center" });
  64. if (!(await card.isClickable())) return false;
  65. await card.click();
  66. return true;
  67. };
  68. let opened = false;
  69. if (requireCard) {
  70. // task 激活先于历史/缩略图挂载;失败录像中随后已出现图片,不能一次读取就判失败。
  71. await browser
  72. .waitUntil(
  73. async () => {
  74. opened = await clickCard();
  75. return opened;
  76. },
  77. {
  78. timeout: 30_000,
  79. interval: 200,
  80. timeoutMsg: `${CASE_MARKER}: 已恢复任务没有可点击的 ${IMAGE_FILE} 缩略图`,
  81. },
  82. )
  83. .catch(async (error) => {
  84. const cards = await browser.execute(() =>
  85. Array.from(
  86. document.querySelectorAll<HTMLElement>("[data-v4-user-input-media-attachment='true']"),
  87. ).map((card) => ({
  88. visible: card.getClientRects().length > 0,
  89. disabled: card.getAttribute("aria-disabled"),
  90. role: card.getAttribute("role"),
  91. title: card.getAttribute("title"),
  92. images: Array.from(card.querySelectorAll<HTMLImageElement>("img")).map((image) => ({
  93. alt: image.alt,
  94. complete: image.complete,
  95. width: image.naturalWidth,
  96. })),
  97. })),
  98. );
  99. throw new Error(`${CASE_MARKER}: 缩略图尚未恢复或名称不匹配: ${JSON.stringify(cards)}`, {
  100. cause: error,
  101. });
  102. });
  103. } else {
  104. opened = await clickCard();
  105. }
  106. if (!opened)
  107. return {
  108. open: false,
  109. imageLoaded: false,
  110. naturalWidth: 0,
  111. src: "",
  112. errorText: "thumbnail-not-openable",
  113. };
  114. let state: GalleryState = {
  115. open: false,
  116. imageLoaded: false,
  117. naturalWidth: 0,
  118. src: "",
  119. errorText: "",
  120. };
  121. let diagnostics: unknown;
  122. await browser
  123. .waitUntil(
  124. async () => {
  125. state = await browser.execute(() => {
  126. const dialog = document.querySelector<HTMLElement>("[role='dialog']");
  127. const image = dialog?.querySelector<HTMLImageElement>("img");
  128. const errorText = Array.from(
  129. dialog?.querySelectorAll<HTMLElement>("[role='alert'], [data-error], p") ?? [],
  130. )
  131. .map((n) => n.innerText.trim())
  132. .filter((t) => /失败|错误|无法|error|fail/iu.test(t))
  133. .join(" | ")
  134. .slice(0, 200);
  135. return {
  136. open: Boolean(dialog),
  137. imageLoaded: Boolean(image && image.complete && image.naturalWidth > 0),
  138. naturalWidth: image?.naturalWidth ?? 0,
  139. src: (image?.src ?? "").slice(0, 40),
  140. errorText,
  141. };
  142. });
  143. return state.open && (state.imageLoaded || state.errorText.length > 0);
  144. },
  145. // role=button 已证明缩略图具备打开能力;图片 gallery 只需提交本地展示状态。
  146. // 旧 45 秒余量掩盖了在 onOpen 尚未提供时点击空 DIV 的测试错误。
  147. { timeout: 10_000, interval: 200, timeoutMsg: "gallery" },
  148. )
  149. .catch(async () => {
  150. diagnostics = await browser
  151. .execute((filename) => {
  152. const cards = Array.from(
  153. document.querySelectorAll<HTMLElement>("[data-v4-user-input-media-attachment='true']"),
  154. );
  155. const target = cards.find((candidate) =>
  156. candidate.querySelector<HTMLImageElement>(`img[alt="${filename}"]`),
  157. );
  158. const image = target?.querySelector<HTMLImageElement>(`img[alt="${filename}"]`);
  159. return {
  160. cardCount: cards.length,
  161. targetFound: Boolean(target),
  162. targetTag: target?.tagName ?? null,
  163. targetAriaDisabled: target?.getAttribute("aria-disabled") ?? null,
  164. targetRole: target?.getAttribute("role") ?? null,
  165. targetTitle: target?.getAttribute("title") ?? null,
  166. targetDataset: target ? { ...target.dataset } : null,
  167. thumbnailComplete: Boolean(image?.complete),
  168. thumbnailNaturalWidth: image?.naturalWidth ?? 0,
  169. thumbnailSrcScheme: (image?.src ?? "").split(":")[0] ?? "",
  170. dialogCount: document.querySelectorAll("[role='dialog']").length,
  171. portalCount: document.querySelectorAll("[data-radix-portal],[data-portal]").length,
  172. bodyLastChildTag: document.body.lastElementChild?.tagName ?? null,
  173. };
  174. }, IMAGE_FILE)
  175. .catch((error: unknown) => ({
  176. error: error instanceof Error ? error.message : String(error),
  177. }));
  178. });
  179. return { ...state, ...(diagnostics === undefined ? {} : { diagnostics }) };
  180. }
  181. // 远端 tab 不会自动成为 primary pane(离线隐藏任务行、重连后主区停在欢迎页),
  182. // 两处读取 gallery 之前都要经 tab store 显式激活。
  183. async function activateRemoteTab(identity: string): Promise<void> {
  184. const activated = await browser.execute((id) => {
  185. const store = (
  186. window as Window & {
  187. __zcodeTabStoreE2E?: {
  188. getState?: () => {
  189. tabs?: Array<{ id: string; workspaceIdentity?: string }>;
  190. activateTab?: (tabId: string) => void;
  191. };
  192. };
  193. }
  194. ).__zcodeTabStoreE2E;
  195. const state = store?.getState?.();
  196. const tab = state?.tabs?.find((candidate) => candidate.workspaceIdentity === id);
  197. if (!tab || !state?.activateTab) return false;
  198. state.activateTab(tab.id);
  199. return true;
  200. }, identity);
  201. expect(activated).toBe(true);
  202. await browser.waitUntil(
  203. async () => (await readRemoteTabSnapshot()).activeWorkspaceIdentity === identity,
  204. {
  205. timeout: 15_000,
  206. timeoutMsg: `${CASE_MARKER}: 未激活目标远端工作区`,
  207. },
  208. );
  209. }
  210. async function closeGallery(): Promise<void> {
  211. await browser.keys(["Escape"]);
  212. await browser.waitUntil(() => browser.execute(() => !document.querySelector("[role='dialog']")), {
  213. timeout: 10_000,
  214. timeoutMsg: `${CASE_MARKER}: gallery 没有关闭`,
  215. });
  216. }
  217. describe(`${CASE_MARKER}: 远端媒体附件的预览读取、断线后访问与恢复`, () => {
  218. let provider: SSHLifecycleProvider | null = null;
  219. const facts: Record<string, unknown> = {};
  220. after(async () => {
  221. await mkdir(artifactDir, { recursive: true });
  222. await writeFile(resolve(artifactDir, "media-preview.json"), JSON.stringify(facts, null, 2));
  223. await provider?.tunnel.close().catch(() => undefined);
  224. provider = null;
  225. await browser.electron.restoreAllMocks();
  226. await clearAppData();
  227. });
  228. it("R3A-DEV-05/10 远端图片真实预览、断线与重连;重连后下载到本机字节一致,取消保存不覆盖文件", async function () {
  229. this.timeout(25 * 60_000);
  230. const prepared = await prepareSSHLifecycle(CASE_MARKER, {
  231. apiType: "anthropic-messages",
  232. tunnelUsername: "tunnel",
  233. });
  234. provider = prepared.provider;
  235. const [workspaceA] = prepared.config.workspacePaths;
  236. const taskA = await connectSSHWorkspaceAndSendFirstTurn({
  237. caseMarker: CASE_MARKER,
  238. config: prepared.config,
  239. label: "A",
  240. provider,
  241. workspacePath: workspaceA,
  242. });
  243. await setV4ComposerText(`${CASE_MARKER}_IMAGE 看图`);
  244. await pasteV4ComposerFileAttachment(IMAGE_FILE, { pngBase64: PNG_2X2_BASE64 });
  245. await browser.waitUntil(
  246. () =>
  247. browser.execute(
  248. (name) =>
  249. Boolean(
  250. Array.from(
  251. document.querySelectorAll<HTMLImageElement>(
  252. '[data-composer-attachment-kind="image"][data-upload-status="ready"] img[alt]',
  253. ),
  254. )
  255. .find((img) => img.alt === name)
  256. ?.src.startsWith("blob:"),
  257. ),
  258. IMAGE_FILE,
  259. ),
  260. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 图片没有完成上传与缩略图` },
  261. );
  262. const start = await getUpstreamRequestRecordCount();
  263. await clickV4Send();
  264. await waitForV4RowAttachments(60_000);
  265. await waitForUpstreamRequest(
  266. { lastUserMessageIncludes: [`${CASE_MARKER}_IMAGE`] },
  267. `${CASE_MARKER}: 图片回合没有到达回放`,
  268. 90_000,
  269. { afterIndex: start - 1 },
  270. );
  271. await waitForV4AssistantMessageContaining("R3_MEDIA_PREVIEW_REPLY", 90_000);
  272. await waitForV4ConversationState(
  273. (s) => s.taskId === taskA.taskId && s.state === "idle",
  274. `${CASE_MARKER}: 图片回合没有收口`,
  275. 90_000,
  276. );
  277. // 在线预览:gallery 打开且图片真实解码(naturalWidth=2)。
  278. const online = await openSentImageAndReadGallery();
  279. facts.previewOnline = online;
  280. expect(online.open).toBe(true);
  281. expect(online.imageLoaded).toBe(true);
  282. expect(online.naturalWidth).toBe(2);
  283. const [imageRequest] = await getUpstreamRequestEvidence(
  284. {
  285. lastUserMessageIncludes: [`${CASE_MARKER}_IMAGE`],
  286. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  287. },
  288. { afterIndex: start - 1 },
  289. );
  290. const remoteImagePath = JSON.stringify(imageRequest?.requestJson).match(
  291. /\[Image: source: ([^\]]+)\]/u,
  292. )?.[1];
  293. expect(remoteImagePath).toMatch(/^\/home\/dev\/\.zcode\/cli\/image-cache\/[A-Za-z0-9_./-]+$/u);
  294. const remoteHash = await runSSHCommand(prepared.config, `sha256sum -- '${remoteImagePath}'`);
  295. expect(remoteHash.code).toBe(0);
  296. const expectedImageHash = createHash("sha256")
  297. .update(Buffer.from(PNG_2X2_BASE64, "base64"))
  298. .digest("hex");
  299. expect(remoteHash.stdout.split(/\s/u)[0]).toBe(expectedImageHash);
  300. facts.remoteImageSha256 = expectedImageHash;
  301. await closeGallery();
  302. // 断开 Source:sent row 缩略图/预览的表现(不得假成功地宣称新读取,不崩;允许使用本地 blob 缓存)。
  303. const sourceId = parseRemoteWorkspaceIdentity(taskA.identity)?.sourceServerId ?? "";
  304. await selectTaskOrganizeMode(["项目", "Project"]);
  305. await disconnectRemoteSource(sourceId!, CASE_MARKER, { workspaceIdentities: [taskA.identity] });
  306. await browser.pause(1_500);
  307. // 离线时任务行隐藏(O-07),经 tab store 激活远端 tab 后读取 gallery。
  308. await activateRemoteTab(taskA.identity);
  309. const offline = await openSentImageAndReadGallery(false);
  310. const rendererAlive = await browser.execute(() =>
  311. Boolean(
  312. document.querySelector('[data-testid^="v4-session-pane"], [data-testid="task-list"], main'),
  313. ),
  314. );
  315. facts.previewOffline = { ...offline, rendererAlive };
  316. expect(rendererAlive).toBe(true);
  317. if (offline.imageLoaded) expect(offline.src).toMatch(/^blob:/u);
  318. await closeGallery();
  319. // 重连后再次预览可读。
  320. await reconnectRemoteProject(taskA.identity, CASE_MARKER);
  321. await browser.waitUntil(
  322. async () =>
  323. Boolean((await readRemoteTabSnapshot(taskA.identity).catch(() => null))?.remoteSessionId),
  324. { timeout: 120_000, interval: 1000, timeoutMsg: `${CASE_MARKER}: 重连没有恢复` },
  325. );
  326. // 修复原因:上一步只等 remoteSessionId 出现,恢复链路此时还在拉任务列表;立刻点侧栏
  327. // task 会落在空草稿上(实测 latest.rowCount=0、sessionId="draft",timeline 还是欢迎页)。
  328. // 先等工作区真正挂回来,再选任务。
  329. await waitForWorkspaceApp(workspaceA, 60_000);
  330. // 修复原因:远端 tab 在重连后不会自动成为 primary pane,主区停在"选择项目"欢迎页,
  331. // 点侧栏 task 也切不过去(实测 rowCount=0、sessionId="draft")。离线读取那一步已经
  332. // 承认要手动激活远端 tab,重连后同样需要。
  333. await activateRemoteTab(taskA.identity);
  334. await selectV4TaskById(taskA.taskId, 60_000);
  335. const after = await openSentImageAndReadGallery();
  336. facts.previewAfterReconnect = after;
  337. expect(after.open).toBe(true);
  338. expect(after.imageLoaded).toBe(true);
  339. // DEV-10 的导出走真实 gallery → Main Save As;只控制 OS 选择路径,文件写入不替代。
  340. await mkdir(artifactDir, { recursive: true });
  341. const exportedPath = resolve(artifactDir, "exported-remote-image.png");
  342. const canceledPath = resolve(artifactDir, "canceled-export-canary.png");
  343. const cancelCanary = "R3_MEDIA_CANCEL_MUST_PRESERVE";
  344. await writeFile(canceledPath, cancelCanary);
  345. const saveDialog = await browser.electron.mock("dialog", "showSaveDialog");
  346. await saveDialog.mockResolvedValueOnce({ canceled: false, filePath: exportedPath });
  347. const download = $(
  348. '[role="dialog"] button[aria-label="下载图片"], [role="dialog"] button[aria-label="Download image"]',
  349. );
  350. await download.waitForClickable({ timeout: 15_000 });
  351. await download.click();
  352. let exported: Buffer | undefined;
  353. await browser.waitUntil(
  354. async () => {
  355. try {
  356. exported = await readFile(exportedPath);
  357. } catch (error) {
  358. if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
  359. throw error;
  360. }
  361. return exported.length > 0;
  362. },
  363. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 下载没有在本机保存文件` },
  364. );
  365. expect(exported).toEqual(Buffer.from(PNG_2X2_BASE64, "base64"));
  366. facts.exportedImageSha256 = createHash("sha256").update(exported!).digest("hex");
  367. expect(facts.exportedImageSha256).toBe(facts.remoteImageSha256);
  368. await download.waitForEnabled({ timeout: 15_000 });
  369. await saveDialog.mockResolvedValueOnce({ canceled: true, filePath: canceledPath });
  370. await download.click();
  371. await browser.waitUntil(
  372. async () => {
  373. await saveDialog.update();
  374. return saveDialog.mock.calls.length === 2 && (await download.isEnabled());
  375. },
  376. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 取消保存没有结束` },
  377. );
  378. expect(await readFile(canceledPath, "utf8")).toBe(cancelCanary);
  379. facts.cancelPreservedLocalFile = true;
  380. await closeGallery();
  381. });
  382. });