workflowArtifactSidePane.test.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. // @vitest-environment jsdom
  2. // `workflow-artifact` tab:一个用户面产物的全尺寸查看(docs/dynamic-workflow/authoring.md「How the user sees them」+
  3. // 「正文渲染器」两行)。
  4. //
  5. // ⚠ 术语:这里的 artifact 是脚本经 `artifact.*` 交付给用户的产出,不是引擎内部那个
  6. // 「脚本顶层返回值」的同名词(spec 的「术语」表是唯一消歧处)。
  7. //
  8. // 钉三件事:
  9. // 1. 正文按 journal 记录上的 `contentType` 分派到既有叶子查看器(零新渲染依赖);
  10. // 2. 版本步进器按**已知版本的数组**翻,而不是凭最新版号编造 1..n;
  11. // 3. 「在工作区显示」与 html 的「在浏览器中打开」的门(desktop-local ∧ sourcePath ∧ 最新版)。
  12. // 4. 「作为文件打开」:宿主能落副本才出入口,落的是**正在看的那一版**的字节。
  13. import { createElement, type ReactNode } from "react";
  14. import { act, cleanup, fireEvent, render, waitFor } from "@testing-library/react";
  15. import { beforeEach, describe, expect, it, vi } from "vitest";
  16. import { TID_WORKFLOW_ARTIFACT_PANE, type IPlatformService } from "@zcode/shared";
  17. import type {
  18. V4ConversationWorkflowRunArtifactDataResult,
  19. V4ConversationWorkflowRunArtifactReadResult,
  20. V4ConversationWorkflowRunArtifactsResult,
  21. WorkflowRunArtifact,
  22. } from "@zcode/shared/zcode-protocol-v4";
  23. import type { WorkflowArtifactSidePaneTab } from "@/lib/workspaceSidePane.js";
  24. vi.mock("@/logger.js", () => ({
  25. logger: { debug: vi.fn(), warn: vi.fn() },
  26. }));
  27. const toast = vi.fn();
  28. vi.mock("@/components/ui/toast.js", () => ({
  29. toast: (...args: unknown[]) => toast(...args),
  30. }));
  31. const workflowRunArtifacts = vi.fn<() => Promise<V4ConversationWorkflowRunArtifactsResult>>();
  32. const workflowRunArtifactData = vi.fn<() => Promise<V4ConversationWorkflowRunArtifactDataResult>>();
  33. const workflowRunArtifactRead =
  34. vi.fn<
  35. (params: {
  36. version: number;
  37. offset: number;
  38. limit: number;
  39. }) => Promise<V4ConversationWorkflowRunArtifactReadResult>
  40. >();
  41. const release = vi.fn();
  42. // layer 必须是稳定引用:租约 effect 以它为依赖(同 workflowRunSidePane.test.ts 的注记)。
  43. const layer = { acquire: vi.fn(() => ({ release })) };
  44. vi.mock("@/v4/V4ConversationContext.js", () => ({
  45. V4PaneConversationProvider: ({ children }: { children: ReactNode }) => children,
  46. useV4Conversation: () => ({
  47. layer,
  48. workflowRunArtifacts,
  49. workflowRunArtifactData,
  50. workflowRunArtifactRead,
  51. }),
  52. }));
  53. let snapshot: unknown = null;
  54. vi.mock("@/v4/useConversationProjection.js", () => ({
  55. useConversationProjection: () => ({ snapshot }),
  56. }));
  57. // 三个重量级叶子查看器:真身各自要 pdf.js / docx-preview / xlsx wasm,在 jsdom 里既慢又与
  58. // 本用例无关。桩把 props 原样挂到 DOM 上,好断言「正文交给了谁、喂的是什么」。
  59. vi.mock("@/previewPanePdfContent.js", () => ({
  60. PdfPreviewContent: ({ source }: { source: Blob }) =>
  61. createElement("div", { "data-testid": "pdf-viewer", "data-size": String(source.size) }),
  62. }));
  63. vi.mock("@/previewPanePptxContent.js", () => ({
  64. PptxPreviewContent: ({ data, fileName }: { data: ArrayBuffer; fileName?: string }) =>
  65. createElement("div", {
  66. "data-testid": "pptx-viewer",
  67. "data-file-name": fileName ?? "",
  68. "data-size": String(data.byteLength),
  69. }),
  70. }));
  71. vi.mock("@/previewPaneOfficeContent.js", () => ({
  72. PreviewPaneOfficeContent: ({
  73. kind,
  74. preview,
  75. resolvedTheme,
  76. }: {
  77. kind: string;
  78. preview: { dataBase64: string; totalBytes: number } | null;
  79. resolvedTheme: string;
  80. }) =>
  81. createElement("div", {
  82. "data-testid": "office-viewer",
  83. "data-kind": kind,
  84. "data-resolved-theme": resolvedTheme,
  85. "data-total-bytes": String(preview?.totalBytes ?? 0),
  86. }),
  87. }));
  88. vi.mock("@/components/ai-elements/message.js", () => ({
  89. MessageResponse: ({ children, theme }: { children?: ReactNode; theme?: string }) =>
  90. createElement(
  91. "div",
  92. { "data-testid": "markdown-response", "data-theme": theme ?? "" },
  93. children,
  94. ),
  95. }));
  96. vi.mock("@/components/ai-elements/code-block.js", () => ({
  97. CodeBlock: ({ code, language }: { code: string; language?: string }) =>
  98. createElement("pre", { "data-testid": "code-block", "data-language": language ?? "" }, code),
  99. }));
  100. // eslint-disable-next-line import/first -- 必须在全部 mock 之后再引入被测组件。
  101. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  102. // eslint-disable-next-line import/first
  103. import { WorkflowArtifactSidePane } from "@/app-shell/WorkflowArtifactSidePane.js";
  104. // eslint-disable-next-line import/first
  105. import { encodeBytesToBase64 } from "@/hooks/useWorkflowRunArtifactBytes.js";
  106. // eslint-disable-next-line import/first
  107. import { PlatformProvider } from "@/hooks/usePlatform.js";
  108. const onOpenBrowserUrl = vi.fn();
  109. const onRevealFileInTree = vi.fn();
  110. function tabOf(overrides: Partial<WorkflowArtifactSidePaneTab> = {}): WorkflowArtifactSidePaneTab {
  111. return {
  112. id: "workflow-artifact:%2Fworkspace:parent-a:dwfrun-1:book",
  113. type: "workflow-artifact",
  114. workspaceKey: "/workspace",
  115. workspacePath: "/workspace",
  116. parentSessionId: "parent-a",
  117. runId: "dwfrun-1",
  118. artifactId: "book",
  119. ...overrides,
  120. };
  121. }
  122. function record(overrides: Partial<WorkflowRunArtifact> = {}): WorkflowRunArtifact {
  123. return {
  124. id: "book",
  125. kind: "file",
  126. title: "审计报告",
  127. contentType: "application/pdf",
  128. sourcePath: "out/book.pdf",
  129. version: 1,
  130. versions: [{ version: 1, publishedAt: 1, bytes: 8, sourcePath: "out/book.pdf" }],
  131. itemCount: 0,
  132. ...overrides,
  133. };
  134. }
  135. function textChunk(text: string, mediaType: string): V4ConversationWorkflowRunArtifactReadResult {
  136. const bytes = new TextEncoder().encode(text) as Uint8Array<ArrayBuffer>;
  137. return {
  138. dataBase64: encodeBytesToBase64(bytes),
  139. mediaType,
  140. totalBytes: bytes.length,
  141. nextOffset: null,
  142. };
  143. }
  144. function renderPane(
  145. options: {
  146. tab?: WorkflowArtifactSidePaneTab;
  147. locale?: "en-US" | "zh-CN";
  148. withBrowser?: boolean;
  149. withReveal?: boolean;
  150. /** 缺席即不挂 PlatformProvider(与既有用例一致:没有宿主能力)。 */
  151. platform?: Partial<IPlatformService>;
  152. } = {},
  153. ) {
  154. const pane = createElement(WorkflowArtifactSidePane, {
  155. tab: options.tab ?? tabOf(),
  156. ...(options.withBrowser === false ? {} : { onOpenBrowserUrl }),
  157. ...(options.withReveal === false ? {} : { onRevealFileInTree }),
  158. });
  159. return render(
  160. createElement(
  161. ZCodeIntlProvider,
  162. { initialLocale: options.locale ?? "zh-CN" },
  163. options.platform === undefined
  164. ? pane
  165. : createElement(PlatformProvider, {
  166. platform: options.platform as IPlatformService,
  167. children: pane,
  168. }),
  169. ),
  170. );
  171. }
  172. beforeEach(() => {
  173. cleanup();
  174. snapshot = null;
  175. toast.mockClear();
  176. onOpenBrowserUrl.mockClear();
  177. onRevealFileInTree.mockClear();
  178. layer.acquire.mockClear();
  179. workflowRunArtifacts.mockReset();
  180. workflowRunArtifactData.mockReset();
  181. workflowRunArtifactRead.mockReset();
  182. workflowRunArtifacts.mockResolvedValue({ artifacts: [record()] });
  183. workflowRunArtifactData.mockResolvedValue({ items: [], hasMore: false });
  184. workflowRunArtifactRead.mockResolvedValue(textChunk("bytes---", "application/pdf"));
  185. // resolveTheme("system") 会问 matchMedia;jsdom 不带它。
  186. (window as unknown as { matchMedia: (query: string) => unknown }).matchMedia = () => ({
  187. matches: false,
  188. addEventListener: () => {},
  189. removeEventListener: () => {},
  190. addListener: () => {},
  191. removeListener: () => {},
  192. });
  193. });
  194. describe("WorkflowArtifactSidePane 正文分派", () => {
  195. it("pdf 交给既有的 PdfViewer,喂的是 Blob(不落地成文件、不走 range transport)", async () => {
  196. const view = renderPane();
  197. await waitFor(() => expect(view.getByTestId("pdf-viewer")).toBeTruthy());
  198. expect(view.getByTestId("pdf-viewer").getAttribute("data-size")).toBe("8");
  199. expect(view.getByTestId("workflow-artifact-title").textContent).toBe("审计报告");
  200. });
  201. it("markdown 走 MessageResponse 并**传 theme**(深底深字修过一次)", async () => {
  202. workflowRunArtifacts.mockResolvedValue({
  203. artifacts: [
  204. record({
  205. id: "notes",
  206. kind: "markdown",
  207. contentType: "text/markdown",
  208. sourcePath: undefined,
  209. versions: [{ version: 1, publishedAt: 1, bytes: 5 }],
  210. }),
  211. ],
  212. });
  213. workflowRunArtifactRead.mockResolvedValue(textChunk("# hi", "text/markdown"));
  214. const view = renderPane({ tab: tabOf({ artifactId: "notes" }) });
  215. await waitFor(() => expect(view.getByTestId("markdown-response")).toBeTruthy());
  216. expect(view.getByTestId("markdown-response").textContent).toBe("# hi");
  217. expect(view.getByTestId("markdown-response").getAttribute("data-theme")).toBe("system");
  218. });
  219. it("图片走 blob object url 的 <img>", async () => {
  220. (URL as unknown as { createObjectURL: (blob: Blob) => string }).createObjectURL = () =>
  221. "blob:artifact-img";
  222. (URL as unknown as { revokeObjectURL: (url: string) => void }).revokeObjectURL = () => {};
  223. workflowRunArtifacts.mockResolvedValue({
  224. artifacts: [record({ id: "shot", contentType: "image/png" })],
  225. });
  226. workflowRunArtifactRead.mockResolvedValue(textChunk("png-bytes", "image/png"));
  227. const view = renderPane({ tab: tabOf({ artifactId: "shot" }) });
  228. await waitFor(() => expect(view.getByTestId("workflow-artifact-image")).toBeTruthy());
  229. expect(view.getByTestId("workflow-artifact-image").getAttribute("src")).toBe(
  230. "blob:artifact-img",
  231. );
  232. });
  233. it("csv / json 走等宽 code viewer", async () => {
  234. workflowRunArtifacts.mockResolvedValue({
  235. artifacts: [record({ id: "rows", contentType: "text/csv" })],
  236. });
  237. workflowRunArtifactRead.mockResolvedValue(textChunk("a,b\n1,2", "text/csv"));
  238. const view = renderPane({ tab: tabOf({ artifactId: "rows" }) });
  239. await waitFor(() => expect(view.getByTestId("code-block")).toBeTruthy());
  240. expect(view.getByTestId("code-block").getAttribute("data-language")).toBe("csv");
  241. });
  242. it("docx 交给既有 office 查看器,喂的是字节(不是路径)", async () => {
  243. workflowRunArtifacts.mockResolvedValue({
  244. artifacts: [
  245. record({
  246. id: "doc",
  247. contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  248. }),
  249. ],
  250. });
  251. workflowRunArtifactRead.mockResolvedValue(
  252. textChunk("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
  253. );
  254. const view = renderPane({ tab: tabOf({ artifactId: "doc" }) });
  255. await waitFor(() => expect(view.getByTestId("office-viewer")).toBeTruthy());
  256. expect(view.getByTestId("office-viewer").getAttribute("data-kind")).toBe("docx");
  257. expect(view.getByTestId("office-viewer").getAttribute("data-total-bytes")).toBe("4");
  258. });
  259. it("pptx 交给既有 pptx 查看器,喂的是 ArrayBuffer", async () => {
  260. const contentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
  261. workflowRunArtifacts.mockResolvedValue({
  262. artifacts: [record({ id: "deck", contentType, sourcePath: "out/deck.pptx" })],
  263. });
  264. workflowRunArtifactRead.mockResolvedValue(textChunk("pptx-bytes", contentType));
  265. const view = renderPane({ tab: tabOf({ artifactId: "deck" }) });
  266. await waitFor(() => expect(view.getByTestId("pptx-viewer")).toBeTruthy());
  267. expect(view.getByTestId("pptx-viewer").getAttribute("data-size")).toBe("10");
  268. expect(view.getByTestId("pptx-viewer").getAttribute("data-file-name")).toBe("out/deck.pptx");
  269. });
  270. it("表外类型给一张元数据卡 + 「在工作区显示」,不假装能渲染", async () => {
  271. workflowRunArtifacts.mockResolvedValue({
  272. artifacts: [
  273. record({ id: "blob", contentType: "application/octet-stream", sourcePath: "out/x.bin" }),
  274. ],
  275. });
  276. workflowRunArtifactRead.mockResolvedValue(textChunk("bin", "application/octet-stream"));
  277. const view = renderPane({ tab: tabOf({ artifactId: "blob" }) });
  278. await waitFor(() => expect(view.getByTestId("workflow-artifact-unsupported")).toBeTruthy());
  279. const card = view.getByTestId("workflow-artifact-unsupported");
  280. expect(card.textContent).toContain("application/octet-stream");
  281. expect(card.textContent).toContain("out/x.bin");
  282. fireEvent.click(view.getByTestId("workflow-artifact-unsupported-reveal"));
  283. // 「在工作区显示」拿到的是 workspacePath 拼出来的本机绝对路径。
  284. expect(onRevealFileInTree).toHaveBeenCalledWith("/workspace/out/x.bin");
  285. });
  286. it("预置看板画在 tab 里,且**不读一个字节**", async () => {
  287. workflowRunArtifacts.mockResolvedValue({
  288. artifacts: [
  289. record({
  290. id: "rounds",
  291. kind: "table",
  292. contentType: undefined,
  293. sourcePath: undefined,
  294. versions: [{ version: 1, publishedAt: 1 }],
  295. spec: { columns: [{ field: "round" }] },
  296. itemCount: 1,
  297. }),
  298. ],
  299. });
  300. workflowRunArtifactData.mockResolvedValue({
  301. items: [{ sequence: 1, siteId: "report#1", ordinal: 1, item: { round: 7 } }],
  302. hasMore: false,
  303. });
  304. const view = renderPane({ tab: tabOf({ artifactId: "rounds" }) });
  305. await waitFor(() => expect(view.getByTestId("artifact-table")).toBeTruthy());
  306. expect(view.getByText("7")).toBeTruthy();
  307. expect(workflowRunArtifactRead).not.toHaveBeenCalled();
  308. });
  309. });
  310. describe("WorkflowArtifactSidePane html 卡", () => {
  311. const htmlRecord = (sourcePath: string | undefined, versionCount = 1) =>
  312. record({
  313. id: "site",
  314. contentType: "text/html",
  315. ...(sourcePath === undefined ? { sourcePath: undefined } : { sourcePath }),
  316. version: versionCount,
  317. versions: Array.from({ length: versionCount }, (_unused, index) => ({
  318. version: index + 1,
  319. publishedAt: index + 1,
  320. bytes: 4,
  321. })),
  322. });
  323. beforeEach(() => {
  324. workflowRunArtifactRead.mockResolvedValue(textChunk("<h1>", "text/html"));
  325. });
  326. it("本地工作区 + 最新版:给「在浏览器中打开」,打开的是工作区原件的 file:// URL", async () => {
  327. workflowRunArtifacts.mockResolvedValue({ artifacts: [htmlRecord("out/site.html")] });
  328. const view = renderPane({ tab: tabOf({ artifactId: "site" }) });
  329. await waitFor(() => expect(view.getByTestId("workflow-artifact-html-card")).toBeTruthy());
  330. fireEvent.click(view.getByTestId("workflow-artifact-open-in-browser"));
  331. expect(onOpenBrowserUrl).toHaveBeenCalledWith("file:///workspace/out/site.html");
  332. // 卡上必须写明打开的是工作区那一份,而不是这一版被钉住的字节。
  333. expect(view.getByTestId("workflow-artifact-note").textContent).toContain("工作区");
  334. });
  335. it("远程 workspace(有 remoteSessionId)退成「仅本地工作区可预览」", async () => {
  336. workflowRunArtifacts.mockResolvedValue({ artifacts: [htmlRecord("out/site.html")] });
  337. const view = renderPane({
  338. tab: tabOf({
  339. artifactId: "site",
  340. remoteSessionId: "remote-1",
  341. workspaceIdentity: "ssh://host/workspace",
  342. }),
  343. });
  344. await waitFor(() => expect(view.getByTestId("workflow-artifact-html-card")).toBeTruthy());
  345. expect(view.queryByTestId("workflow-artifact-open-in-browser")).toBeNull();
  346. expect(view.getByTestId("workflow-artifact-note").textContent).toContain("仅本地工作区");
  347. expect(view.queryByTestId("workflow-artifact-reveal")).toBeNull();
  348. });
  349. it("看的是旧版时不给「在浏览器中打开」——工作区原件早被同名覆盖了", async () => {
  350. workflowRunArtifacts.mockResolvedValue({ artifacts: [htmlRecord("out/site.html", 2)] });
  351. const view = renderPane({ tab: tabOf({ artifactId: "site", version: 1 }) });
  352. await waitFor(() => expect(view.getByTestId("workflow-artifact-html-card")).toBeTruthy());
  353. expect(view.queryByTestId("workflow-artifact-open-in-browser")).toBeNull();
  354. expect(view.getByTestId("workflow-artifact-html-reveal")).toBeTruthy();
  355. });
  356. });
  357. describe("WorkflowArtifactSidePane 版本步进器", () => {
  358. it("只有一版时整块缺席,只留一个版本号", async () => {
  359. const view = renderPane();
  360. await waitFor(() => expect(view.getByTestId("pdf-viewer")).toBeTruthy());
  361. expect(view.queryByTestId("workflow-artifact-version-stepper")).toBeNull();
  362. expect(view.getByTestId("workflow-artifact-version").textContent).toBe("第 1 版");
  363. });
  364. it("多版时按**已知版本的数组**翻,并按所选版本重读字节", async () => {
  365. workflowRunArtifacts.mockResolvedValue({
  366. artifacts: [
  367. record({
  368. version: 3,
  369. versions: [
  370. { version: 1, publishedAt: 1, bytes: 2 },
  371. { version: 2, publishedAt: 2, bytes: 4 },
  372. { version: 3, publishedAt: 3, bytes: 8 },
  373. ],
  374. }),
  375. ],
  376. });
  377. const view = renderPane();
  378. await waitFor(() => expect(view.getByTestId("workflow-artifact-version-stepper")).toBeTruthy());
  379. // 缺省落点是最新版(chip 从不带版本号)。
  380. expect(view.getByTestId("workflow-artifact-version").textContent).toBe("第 3 版 / 共 3 版");
  381. expect(view.getByTestId("workflow-artifact-version-next").hasAttribute("disabled")).toBe(true);
  382. fireEvent.click(view.getByTestId("workflow-artifact-version-previous"));
  383. await waitFor(() =>
  384. expect(view.getByTestId("workflow-artifact-version").textContent).toBe("第 2 版 / 共 3 版"),
  385. );
  386. await waitFor(() => expect(workflowRunArtifactRead.mock.calls.at(-1)?.[0]?.version).toBe(2));
  387. });
  388. it("journal 读不到版本历史时不凭最新版号编造 1..n", async () => {
  389. // 只有摘要(活投影)在场:步进器必须消失,而不是给出一批取不到字节的版本号。
  390. workflowRunArtifacts.mockRejectedValue(new Error("fault.command.capabilityUnsupported"));
  391. snapshot = {
  392. workflowRuns: {
  393. revision: 1,
  394. runs: [
  395. {
  396. runId: "dwfrun-1",
  397. status: "completed",
  398. usage: { spentTokens: 0, nodesUsed: 0 },
  399. actors: [],
  400. nodes: [],
  401. lastEventSequence: 0,
  402. artifacts: [
  403. {
  404. id: "book",
  405. kind: "file",
  406. title: "审计报告",
  407. version: 4,
  408. contentType: "application/pdf",
  409. bytes: 8,
  410. },
  411. ],
  412. },
  413. ],
  414. },
  415. };
  416. const view = renderPane();
  417. await waitFor(() => expect(view.getByTestId("pdf-viewer")).toBeTruthy());
  418. expect(view.queryByTestId("workflow-artifact-version-stepper")).toBeNull();
  419. expect(view.getByTestId("workflow-artifact-version").textContent).toBe("第 4 版");
  420. });
  421. });
  422. describe("WorkflowArtifactSidePane 元数据来源与空态", () => {
  423. it("run 在活投影里:source 标为 live,摘要先画出来", async () => {
  424. snapshot = {
  425. workflowRuns: {
  426. revision: 1,
  427. runs: [
  428. {
  429. runId: "dwfrun-1",
  430. status: "running",
  431. usage: { spentTokens: 0, nodesUsed: 0 },
  432. actors: [],
  433. nodes: [],
  434. lastEventSequence: 0,
  435. artifacts: [
  436. { id: "book", kind: "file", version: 1, contentType: "application/pdf", bytes: 8 },
  437. ],
  438. },
  439. ],
  440. },
  441. };
  442. const view = renderPane();
  443. await waitFor(() => expect(view.getByTestId("pdf-viewer")).toBeTruthy());
  444. expect(view.getByTestId(TID_WORKFLOW_ARTIFACT_PANE).getAttribute("data-artifact-source")).toBe(
  445. "live",
  446. );
  447. });
  448. it("run 不在活投影里:source 标为 journal(冷恢复走 durable 读法)", async () => {
  449. const view = renderPane();
  450. await waitFor(() => expect(view.getByTestId("pdf-viewer")).toBeTruthy());
  451. expect(view.getByTestId(TID_WORKFLOW_ARTIFACT_PANE).getAttribute("data-artifact-source")).toBe(
  452. "journal",
  453. );
  454. });
  455. it("读完了但这个 id 不在清单里:说「已经不在了」,不永远停在加载文案上", async () => {
  456. workflowRunArtifacts.mockResolvedValue({ artifacts: [] });
  457. const view = renderPane();
  458. await waitFor(() =>
  459. expect(view.getByTestId("workflow-artifact-placeholder").textContent).toBe(
  460. "这个产物已经不在了。",
  461. ),
  462. );
  463. });
  464. it("会话不支持产物查询(老 CLI)时说的是「读不到详情」,不是「不在了」", async () => {
  465. workflowRunArtifacts.mockRejectedValue(new Error("fault.command.capabilityUnsupported"));
  466. const view = renderPane();
  467. await waitFor(() =>
  468. expect(view.getByTestId("workflow-artifact-placeholder").textContent).toBe(
  469. "当前会话读不到产物详情。",
  470. ),
  471. );
  472. });
  473. it("面板订阅的是**父会话**的投影(产物的新鲜元数据是它的一部分)", async () => {
  474. renderPane();
  475. await act(async () => {});
  476. expect(layer.acquire).toHaveBeenCalledWith("parent-a");
  477. });
  478. });
  479. describe("WorkflowArtifactSidePane 头部动作", () => {
  480. it("宿主不能落副本时,「在工作区显示」独立留在头部(desktop-local ∧ sourcePath 在场才出现)", async () => {
  481. const view = renderPane();
  482. await waitFor(() => expect(view.getByTestId("workflow-artifact-reveal")).toBeTruthy());
  483. fireEvent.click(view.getByTestId("workflow-artifact-reveal"));
  484. expect(onRevealFileInTree).toHaveBeenCalledWith("/workspace/out/book.pdf");
  485. });
  486. it("markdown 没有工作区出处,因此没有「在工作区显示」,但有「复制」", async () => {
  487. workflowRunArtifacts.mockResolvedValue({
  488. artifacts: [
  489. record({
  490. id: "notes",
  491. kind: "markdown",
  492. contentType: "text/markdown",
  493. sourcePath: undefined,
  494. versions: [{ version: 1, publishedAt: 1, bytes: 4 }],
  495. }),
  496. ],
  497. });
  498. workflowRunArtifactRead.mockResolvedValue(textChunk("# hi", "text/markdown"));
  499. const view = renderPane({ tab: tabOf({ artifactId: "notes" }) });
  500. await waitFor(() => expect(view.getByTestId("workflow-artifact-copy")).toBeTruthy());
  501. expect(view.queryByTestId("workflow-artifact-reveal")).toBeNull();
  502. });
  503. it("pdf 不给「复制」(二进制复制成文本是一句谎)", async () => {
  504. const view = renderPane();
  505. await waitFor(() => expect(view.getByTestId("pdf-viewer")).toBeTruthy());
  506. expect(view.queryByTestId("workflow-artifact-copy")).toBeNull();
  507. });
  508. it("没有「下载」按钮——renderer 没有任何把字节存成用户文件的宿主能力", async () => {
  509. const view = renderPane();
  510. await waitFor(() => expect(view.getByTestId("pdf-viewer")).toBeTruthy());
  511. expect(view.queryByText("下载")).toBeNull();
  512. });
  513. });
  514. describe("WorkflowArtifactSidePane 作为文件打开", () => {
  515. const markdownRecord = () =>
  516. record({
  517. id: "notes",
  518. kind: "markdown",
  519. contentType: "text/markdown",
  520. sourcePath: undefined,
  521. versions: [{ version: 1, publishedAt: 1, bytes: 4 }],
  522. });
  523. function desktopPlatform(overrides: Partial<IPlatformService> = {}) {
  524. return {
  525. materializeWorkflowArtifactFile: vi.fn(async (payload: { fileName: string }) => ({
  526. localPath: `/copies/${payload.fileName}`,
  527. })),
  528. openExternalFile: vi.fn(async () => ({ success: true })),
  529. getInstalledEditors: vi.fn(async () => [
  530. { id: "vscode", name: "VS Code", iconDataUrl: "data:," },
  531. { id: "finder", name: "Finder", iconDataUrl: "data:," },
  532. ]),
  533. openInEditor: vi.fn(async () => ({ success: true })),
  534. ...overrides,
  535. };
  536. }
  537. function decode(bytes: unknown): string {
  538. return new TextDecoder().decode(bytes as Uint8Array);
  539. }
  540. it("宿主不能落副本时(手机远控 / web)不出入口", async () => {
  541. workflowRunArtifacts.mockResolvedValue({ artifacts: [markdownRecord()] });
  542. workflowRunArtifactRead.mockResolvedValue(textChunk("# hi", "text/markdown"));
  543. const view = renderPane({
  544. tab: tabOf({ artifactId: "notes" }),
  545. platform: { openExternalFile: vi.fn() },
  546. });
  547. await waitFor(() => expect(view.getByTestId("markdown-response")).toBeTruthy());
  548. expect(view.queryByTestId("workflow-artifact-open-as-file")).toBeNull();
  549. });
  550. it("预置看板没有字节,不出入口", async () => {
  551. workflowRunArtifacts.mockResolvedValue({
  552. artifacts: [
  553. record({
  554. id: "scores",
  555. kind: "table",
  556. contentType: undefined,
  557. sourcePath: undefined,
  558. versions: [{ version: 1, publishedAt: 1 }],
  559. spec: { columns: [{ field: "round" }] },
  560. }),
  561. ],
  562. });
  563. const view = renderPane({
  564. tab: tabOf({ artifactId: "scores" }),
  565. platform: desktopPlatform(),
  566. });
  567. await waitFor(() => expect(view.getByTestId("workflow-artifact-title")).toBeTruthy());
  568. expect(view.queryByTestId("workflow-artifact-open-as-file")).toBeNull();
  569. });
  570. it("markdown:把这一版的字节落成 <id>.md,用系统默认 App 打开", async () => {
  571. workflowRunArtifacts.mockResolvedValue({ artifacts: [markdownRecord()] });
  572. workflowRunArtifactRead.mockResolvedValue(textChunk("# hi", "text/markdown"));
  573. const platform = desktopPlatform();
  574. const view = renderPane({ tab: tabOf({ artifactId: "notes" }), platform });
  575. await waitFor(() => expect(view.getByTestId("markdown-response")).toBeTruthy());
  576. fireEvent.click(view.getByTestId("workflow-artifact-open-as-file"));
  577. await waitFor(() => expect(platform.openExternalFile).toHaveBeenCalledWith("/copies/notes.md"));
  578. const payload = platform.materializeWorkflowArtifactFile.mock.calls[0]?.[0] as unknown as {
  579. runId: string;
  580. artifactId: string;
  581. version: number;
  582. fileName: string;
  583. bytes: Uint8Array;
  584. };
  585. expect(payload).toMatchObject({
  586. runId: "dwfrun-1",
  587. artifactId: "notes",
  588. version: 1,
  589. fileName: "notes.md",
  590. });
  591. expect(decode(payload.bytes)).toBe("# hi");
  592. });
  593. it("file:文件名取所选版本的 sourcePath 基名,翻到旧版就落旧版的字节", async () => {
  594. workflowRunArtifacts.mockResolvedValue({
  595. artifacts: [
  596. record({
  597. version: 2,
  598. sourcePath: "out/book.pdf",
  599. versions: [
  600. { version: 1, publishedAt: 1, bytes: 5, sourcePath: "out/draft.pdf" },
  601. { version: 2, publishedAt: 2, bytes: 5, sourcePath: "out/book.pdf" },
  602. ],
  603. }),
  604. ],
  605. });
  606. workflowRunArtifactRead.mockImplementation(async (params) =>
  607. textChunk(`pdf-v${params.version}`, "application/pdf"),
  608. );
  609. const platform = desktopPlatform();
  610. const view = renderPane({ platform });
  611. await waitFor(() => expect(view.getByTestId("pdf-viewer")).toBeTruthy());
  612. fireEvent.click(view.getByTestId("workflow-artifact-open-as-file"));
  613. await waitFor(() => expect(platform.openExternalFile).toHaveBeenCalledWith("/copies/book.pdf"));
  614. expect(platform.materializeWorkflowArtifactFile.mock.calls[0]?.[0]).toMatchObject({
  615. version: 2,
  616. fileName: "book.pdf",
  617. });
  618. fireEvent.click(view.getByTestId("workflow-artifact-version-previous"));
  619. await waitFor(() =>
  620. expect(view.getByTestId("workflow-artifact-version").textContent).toBe("第 1 版 / 共 2 版"),
  621. );
  622. await waitFor(() =>
  623. expect(view.getByTestId("pdf-viewer").getAttribute("data-size")).toBe(
  624. String("pdf-v1".length),
  625. ),
  626. );
  627. fireEvent.click(view.getByTestId("workflow-artifact-open-as-file"));
  628. await waitFor(() =>
  629. expect(platform.openExternalFile).toHaveBeenLastCalledWith("/copies/draft.pdf"),
  630. );
  631. const second = platform.materializeWorkflowArtifactFile.mock.calls[1]?.[0] as unknown as {
  632. version: number;
  633. fileName: string;
  634. bytes: Uint8Array;
  635. };
  636. expect(second).toMatchObject({ version: 1, fileName: "draft.pdf" });
  637. expect(decode(second.bytes)).toBe("pdf-v1");
  638. });
  639. it("同一版再打开不再重传字节,直接开同一个副本", async () => {
  640. workflowRunArtifacts.mockResolvedValue({ artifacts: [markdownRecord()] });
  641. workflowRunArtifactRead.mockResolvedValue(textChunk("# hi", "text/markdown"));
  642. const platform = desktopPlatform();
  643. const view = renderPane({ tab: tabOf({ artifactId: "notes" }), platform });
  644. await waitFor(() => expect(view.getByTestId("markdown-response")).toBeTruthy());
  645. fireEvent.click(view.getByTestId("workflow-artifact-open-as-file"));
  646. await waitFor(() => expect(platform.openExternalFile).toHaveBeenCalledTimes(1));
  647. fireEvent.click(view.getByTestId("workflow-artifact-open-as-file"));
  648. await waitFor(() => expect(platform.openExternalFile).toHaveBeenCalledTimes(2));
  649. expect(platform.materializeWorkflowArtifactFile).toHaveBeenCalledTimes(1);
  650. });
  651. it("系统 App 打不开时给 toast,不静默", async () => {
  652. workflowRunArtifacts.mockResolvedValue({ artifacts: [markdownRecord()] });
  653. workflowRunArtifactRead.mockResolvedValue(textChunk("# hi", "text/markdown"));
  654. const platform = desktopPlatform({
  655. openExternalFile: vi.fn(async () => ({ success: false, error: "no app" })),
  656. });
  657. const view = renderPane({ tab: tabOf({ artifactId: "notes" }), platform });
  658. await waitFor(() => expect(view.getByTestId("markdown-response")).toBeTruthy());
  659. fireEvent.click(view.getByTestId("workflow-artifact-open-as-file"));
  660. await waitFor(() => expect(toast).toHaveBeenCalledWith("无法作为文件打开此产物"));
  661. });
  662. it("副本写失败时同样给 toast", async () => {
  663. workflowRunArtifacts.mockResolvedValue({ artifacts: [markdownRecord()] });
  664. workflowRunArtifactRead.mockResolvedValue(textChunk("# hi", "text/markdown"));
  665. const platform = desktopPlatform({
  666. materializeWorkflowArtifactFile: vi.fn(async () => {
  667. throw new Error("disk full");
  668. }),
  669. });
  670. const view = renderPane({ tab: tabOf({ artifactId: "notes" }), platform });
  671. await waitFor(() => expect(view.getByTestId("markdown-response")).toBeTruthy());
  672. fireEvent.click(view.getByTestId("workflow-artifact-open-as-file"));
  673. await waitFor(() => expect(toast).toHaveBeenCalledWith("无法作为文件打开此产物"));
  674. expect(platform.openExternalFile).not.toHaveBeenCalled();
  675. });
  676. it("选择打开方式:列出已装 App(文件管理器在前),选中即用它打开副本", async () => {
  677. workflowRunArtifacts.mockResolvedValue({ artifacts: [markdownRecord()] });
  678. workflowRunArtifactRead.mockResolvedValue(textChunk("# hi", "text/markdown"));
  679. const platform = desktopPlatform();
  680. const view = renderPane({ tab: tabOf({ artifactId: "notes" }), platform });
  681. await waitFor(() => expect(view.getByTestId("markdown-response")).toBeTruthy());
  682. fireEvent.pointerDown(view.getByTestId("workflow-artifact-open-as-file-menu"), {
  683. button: 0,
  684. ctrlKey: false,
  685. });
  686. await waitFor(() => expect(view.getByText("VS Code")).toBeTruthy());
  687. const names = view.getAllByRole("menuitem").map((item) => item.textContent);
  688. expect(names.slice(0, 2)).toEqual(["Finder", "VS Code"]);
  689. fireEvent.click(view.getByText("VS Code"));
  690. await waitFor(() =>
  691. expect(platform.openInEditor).toHaveBeenCalledWith("vscode", "/copies/notes.md", {
  692. pathKind: "file",
  693. }),
  694. );
  695. expect(platform.openExternalFile).not.toHaveBeenCalled();
  696. });
  697. it("有工作区出处时,「在工作区显示」收进菜单,头部只剩一个文件控件", async () => {
  698. const platform = desktopPlatform();
  699. const view = renderPane({ platform });
  700. await waitFor(() => expect(view.getByTestId("pdf-viewer")).toBeTruthy());
  701. expect(view.getByTestId("workflow-artifact-open-as-file")).toBeTruthy();
  702. expect(view.queryByTestId("workflow-artifact-reveal")).toBeNull();
  703. fireEvent.pointerDown(view.getByTestId("workflow-artifact-open-as-file-menu"), {
  704. button: 0,
  705. ctrlKey: false,
  706. });
  707. await waitFor(() =>
  708. expect(view.getByTestId("workflow-artifact-open-as-file-reveal")).toBeTruthy(),
  709. );
  710. const names = view.getAllByRole("menuitem").map((item) => item.textContent);
  711. // 位置类动作排在 App 之后:先「在工作区显示」,再「复制绝对路径」。
  712. expect(names.slice(-2)).toEqual(["在工作区显示", "复制绝对路径"]);
  713. fireEvent.click(view.getByTestId("workflow-artifact-open-as-file-reveal"));
  714. expect(onRevealFileInTree).toHaveBeenCalledWith("/workspace/out/book.pdf");
  715. // 显示位置不落副本。
  716. expect(platform.materializeWorkflowArtifactFile).not.toHaveBeenCalled();
  717. });
  718. it("没有工作区出处(markdown)或远程工作区时,菜单里没有「在工作区显示」", async () => {
  719. workflowRunArtifacts.mockResolvedValue({ artifacts: [markdownRecord()] });
  720. workflowRunArtifactRead.mockResolvedValue(textChunk("# hi", "text/markdown"));
  721. const markdownView = renderPane({
  722. tab: tabOf({ artifactId: "notes" }),
  723. platform: desktopPlatform(),
  724. });
  725. await waitFor(() => expect(markdownView.getByTestId("markdown-response")).toBeTruthy());
  726. fireEvent.pointerDown(markdownView.getByTestId("workflow-artifact-open-as-file-menu"), {
  727. button: 0,
  728. ctrlKey: false,
  729. });
  730. await waitFor(() => expect(markdownView.getByText("复制绝对路径")).toBeTruthy());
  731. expect(markdownView.queryByTestId("workflow-artifact-open-as-file-reveal")).toBeNull();
  732. cleanup();
  733. workflowRunArtifacts.mockResolvedValue({ artifacts: [record()] });
  734. const remoteView = renderPane({
  735. tab: tabOf({ remoteSessionId: "remote-1", workspaceIdentity: "ssh://host/workspace" }),
  736. platform: desktopPlatform(),
  737. });
  738. await waitFor(() => expect(remoteView.getByTestId("pdf-viewer")).toBeTruthy());
  739. expect(remoteView.queryByTestId("workflow-artifact-reveal")).toBeNull();
  740. fireEvent.pointerDown(remoteView.getByTestId("workflow-artifact-open-as-file-menu"), {
  741. button: 0,
  742. ctrlKey: false,
  743. });
  744. await waitFor(() => expect(remoteView.getByText("复制绝对路径")).toBeTruthy());
  745. expect(remoteView.queryByTestId("workflow-artifact-open-as-file-reveal")).toBeNull();
  746. });
  747. it("「复制路径」复制的是副本的绝对路径", async () => {
  748. const writeText = vi.fn(async () => undefined);
  749. Object.defineProperty(navigator, "clipboard", {
  750. configurable: true,
  751. value: { writeText },
  752. });
  753. workflowRunArtifacts.mockResolvedValue({ artifacts: [markdownRecord()] });
  754. workflowRunArtifactRead.mockResolvedValue(textChunk("# hi", "text/markdown"));
  755. const platform = desktopPlatform();
  756. const view = renderPane({ tab: tabOf({ artifactId: "notes" }), platform });
  757. await waitFor(() => expect(view.getByTestId("markdown-response")).toBeTruthy());
  758. fireEvent.pointerDown(view.getByTestId("workflow-artifact-open-as-file-menu"), {
  759. button: 0,
  760. ctrlKey: false,
  761. });
  762. await waitFor(() => expect(view.getByText("复制绝对路径")).toBeTruthy());
  763. fireEvent.click(view.getByText("复制绝对路径"));
  764. await waitFor(() => expect(writeText).toHaveBeenCalledWith("/copies/notes.md"));
  765. });
  766. });