useAppPanelsWorkflowArtifactOpen.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. // @vitest-environment jsdom
  2. // 产物点击的落点裁决(docs/dynamic-workflow/authoring.md「How the user sees them」)。
  3. //
  4. // ⚠ 术语:artifact = 脚本经 `artifact.*` 交付给**用户**的产出,不是引擎内部那个「脚本顶层
  5. // 返回值」的同名词。
  6. //
  7. // 钉三件事:
  8. // 1. html + 本地 workspace + 有内嵌浏览器 ⇒ 直接开 browser tab,不再经过产物 tab;
  9. // 2. 同一枚产物再点一次 ⇒ 复用那一个 tab,并**重新**发导航请求(v2 必须显示新字节);
  10. // 3. 任何一条判据不成立、出处查不到、查询本身失败 ⇒ 退回产物 tab,点击绝不落空。
  11. import { act, renderHook } from "@testing-library/react";
  12. import { beforeEach, describe, expect, it, vi } from "vitest";
  13. import type { V4ConversationWorkflowRunArtifactsResult } from "@zcode/shared/zcode-protocol-v4";
  14. import { useAppPanels } from "@/hooks/useAppPanels.js";
  15. import { shouldOpenWorkflowArtifactInBrowser } from "@/lib/workflowArtifactOpen.js";
  16. import { clearTaskSidePaneMemoryStateForTest } from "@/lib/taskSidePaneMemory.js";
  17. import { getVisibleSidePaneTabs } from "@/lib/workspaceSidePane.js";
  18. import type {
  19. OpenScopedWorkflowArtifactSideTabRequest,
  20. WorkspaceSidePaneTab,
  21. } from "@/lib/workspaceSidePane.js";
  22. const { conversationWorkflowRunArtifactsV4 } = vi.hoisted(() => ({
  23. conversationWorkflowRunArtifactsV4:
  24. vi.fn<() => Promise<V4ConversationWorkflowRunArtifactsResult>>(),
  25. }));
  26. vi.mock("@/hooks/useServices.js", () => ({
  27. useServices: () => ({
  28. zcodeAgentService: { conversationWorkflowRunArtifactsV4 },
  29. zcodeSessionService: { closeSession: vi.fn(async () => {}) },
  30. }),
  31. }));
  32. vi.mock("@/logger.js", () => ({
  33. logger: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() },
  34. }));
  35. const WORKSPACE_PATH = "/repo";
  36. const SESSION_ID = "sess-a";
  37. const REPORT_URL = "file:///repo/.zcode/workflow-runs/run-1/report.html";
  38. function renderPanels(options?: { supportsEmbeddedBrowser?: boolean; sidePaneOwnerId?: string }) {
  39. return renderHook(() =>
  40. useAppPanels({
  41. workspaceAbsPath: WORKSPACE_PATH,
  42. activeTaskId: options?.sidePaneOwnerId ?? SESSION_ID,
  43. sidePaneOwnerId: options?.sidePaneOwnerId ?? SESSION_ID,
  44. isDesktop: true,
  45. isWorkspaceVisible: true,
  46. supportsEmbeddedBrowser: options?.supportsEmbeddedBrowser ?? true,
  47. defaultWhiteboardNamePrefix: "Whiteboard",
  48. }),
  49. );
  50. }
  51. function artifactRequest(
  52. overrides: Partial<OpenScopedWorkflowArtifactSideTabRequest> = {},
  53. ): OpenScopedWorkflowArtifactSideTabRequest {
  54. return {
  55. workspacePath: WORKSPACE_PATH,
  56. parentSessionId: SESSION_ID,
  57. runId: "run-1",
  58. artifactId: "report",
  59. contentType: "text/html",
  60. ...overrides,
  61. };
  62. }
  63. function journalResult(sourcePath?: string): V4ConversationWorkflowRunArtifactsResult {
  64. return {
  65. artifacts: [
  66. {
  67. id: "report",
  68. kind: "file",
  69. contentType: "text/html",
  70. version: 1,
  71. versions: [{ version: 1, publishedAt: 1, ...(sourcePath ? { sourcePath } : {}) }],
  72. itemCount: 0,
  73. ...(sourcePath ? { sourcePath } : {}),
  74. },
  75. ],
  76. };
  77. }
  78. function tabTypes(tabs: WorkspaceSidePaneTab[] | undefined): string[] {
  79. return (tabs ?? []).map((tab) => tab.type);
  80. }
  81. /** hook 内部的 journal 查询是 fire-and-forget 的 async IIFE,要把微任务跑干净。 */
  82. async function flush() {
  83. await act(async () => {
  84. await Promise.resolve();
  85. await Promise.resolve();
  86. });
  87. }
  88. describe("产物落点判据", () => {
  89. it("只有 html + 本地 workspace + 有内嵌浏览器三条同时成立才直开", () => {
  90. const base = { contentType: "text/html", supportsEmbeddedBrowser: true };
  91. expect(shouldOpenWorkflowArtifactInBrowser(base)).toBe(true);
  92. expect(shouldOpenWorkflowArtifactInBrowser({ ...base, contentType: "text/markdown" })).toBe(
  93. false,
  94. );
  95. // 参数化的 content type 走产物 tab:与画 html 卡那道门同一个严格判据。
  96. expect(
  97. shouldOpenWorkflowArtifactInBrowser({ ...base, contentType: "text/html; charset=utf-8" }),
  98. ).toBe(false);
  99. expect(shouldOpenWorkflowArtifactInBrowser({ supportsEmbeddedBrowser: true })).toBe(false);
  100. expect(shouldOpenWorkflowArtifactInBrowser({ ...base, supportsEmbeddedBrowser: false })).toBe(
  101. false,
  102. );
  103. expect(
  104. shouldOpenWorkflowArtifactInBrowser({ ...base, workspaceIdentity: "ssh://host/repo" }),
  105. ).toBe(false);
  106. // 空白 identity 不算远程(与 canRevealArtifactInWorkspace 同源)。
  107. expect(shouldOpenWorkflowArtifactInBrowser({ ...base, workspaceIdentity: " " })).toBe(true);
  108. expect(shouldOpenWorkflowArtifactInBrowser({ ...base, remoteSessionId: "remote-a" })).toBe(
  109. false,
  110. );
  111. });
  112. });
  113. describe("useAppPanels 打开工作流产物", () => {
  114. beforeEach(() => {
  115. clearTaskSidePaneMemoryStateForTest();
  116. conversationWorkflowRunArtifactsV4.mockReset();
  117. });
  118. it("html 产物直接开 browser tab,不再开产物 tab", async () => {
  119. conversationWorkflowRunArtifactsV4.mockResolvedValue(
  120. journalResult(".zcode/workflow-runs/run-1/report.html"),
  121. );
  122. const { result, unmount } = renderPanels();
  123. act(() => {
  124. result.current.handleOpenWorkflowArtifact(artifactRequest());
  125. });
  126. await flush();
  127. const tabs = result.current.sidePaneState?.tabs ?? [];
  128. expect(tabTypes(tabs)).toEqual(["browser"]);
  129. const tab = tabs[0];
  130. expect(tab?.type === "browser" ? tab.initialUrl : null).toBe(REPORT_URL);
  131. expect(result.current.sidePaneState?.activeTabId).toBe(tab?.id);
  132. expect(result.current.isSidePaneCollapsed).toBe(false);
  133. expect(result.current.browserNavigationRequest).toMatchObject({
  134. targetTabId: tab?.id,
  135. url: REPORT_URL,
  136. });
  137. expect(conversationWorkflowRunArtifactsV4).toHaveBeenCalledWith({
  138. workspacePath: WORKSPACE_PATH,
  139. sessionId: SESSION_ID,
  140. runId: "run-1",
  141. });
  142. unmount();
  143. });
  144. it("再点一次复用同一个 browser tab,并重新发导航请求", async () => {
  145. conversationWorkflowRunArtifactsV4.mockResolvedValue(
  146. journalResult(".zcode/workflow-runs/run-1/report.html"),
  147. );
  148. const { result, unmount } = renderPanels();
  149. act(() => {
  150. result.current.handleOpenWorkflowArtifact(artifactRequest());
  151. });
  152. await flush();
  153. const firstTabId = result.current.sidePaneState?.tabs[0]?.id;
  154. const firstRequestId = result.current.browserNavigationRequest?.id;
  155. // 中间切走,确认第二次点击会把它重新激活。
  156. act(() => {
  157. result.current.handleOpenGit();
  158. });
  159. act(() => {
  160. result.current.handleOpenWorkflowArtifact(artifactRequest());
  161. });
  162. await flush();
  163. const tabs = result.current.sidePaneState?.tabs ?? [];
  164. expect(tabs.filter((tab) => tab.type === "browser")).toHaveLength(1);
  165. expect(tabs[0]?.id).toBe(firstTabId);
  166. expect(result.current.sidePaneState?.activeTabId).toBe(firstTabId);
  167. // 同一个落点、新的请求 id:v2 重新发布后 webview 必须重新取字节。
  168. expect(result.current.browserNavigationRequest?.targetTabId).toBe(firstTabId);
  169. expect(result.current.browserNavigationRequest?.id).not.toBe(firstRequestId);
  170. expect(result.current.browserNavigationRequest?.url).toBe(REPORT_URL);
  171. unmount();
  172. });
  173. it("远程 workspace 的 html 产物仍开产物 tab", async () => {
  174. const { result, unmount } = renderPanels();
  175. act(() => {
  176. result.current.handleOpenWorkflowArtifact(
  177. artifactRequest({ workspaceIdentity: "ssh://host/repo" }),
  178. );
  179. });
  180. await flush();
  181. expect(tabTypes(result.current.sidePaneState?.tabs)).toEqual(["workflow-artifact"]);
  182. expect(conversationWorkflowRunArtifactsV4).not.toHaveBeenCalled();
  183. unmount();
  184. });
  185. it("手机远控(remoteSessionId)的 html 产物仍开产物 tab", async () => {
  186. const { result, unmount } = renderPanels();
  187. act(() => {
  188. result.current.handleOpenWorkflowArtifact(artifactRequest({ remoteSessionId: "remote-a" }));
  189. });
  190. await flush();
  191. expect(tabTypes(result.current.sidePaneState?.tabs)).toEqual(["workflow-artifact"]);
  192. expect(conversationWorkflowRunArtifactsV4).not.toHaveBeenCalled();
  193. unmount();
  194. });
  195. it("没有内嵌浏览器的壳层仍开产物 tab", async () => {
  196. const { result, unmount } = renderPanels({ supportsEmbeddedBrowser: false });
  197. act(() => {
  198. result.current.handleOpenWorkflowArtifact(artifactRequest());
  199. });
  200. await flush();
  201. expect(tabTypes(result.current.sidePaneState?.tabs)).toEqual(["workflow-artifact"]);
  202. expect(conversationWorkflowRunArtifactsV4).not.toHaveBeenCalled();
  203. unmount();
  204. });
  205. it("非 html 与 contentType 缺席都开产物 tab,且不查 journal", async () => {
  206. const { result, unmount } = renderPanels();
  207. act(() => {
  208. result.current.handleOpenWorkflowArtifact(
  209. artifactRequest({ artifactId: "notes", contentType: "text/markdown" }),
  210. );
  211. });
  212. act(() => {
  213. result.current.handleOpenWorkflowArtifact(
  214. artifactRequest({ artifactId: "legacy", contentType: undefined }),
  215. );
  216. });
  217. await flush();
  218. expect(tabTypes(result.current.sidePaneState?.tabs)).toEqual([
  219. "workflow-artifact",
  220. "workflow-artifact",
  221. ]);
  222. expect(conversationWorkflowRunArtifactsV4).not.toHaveBeenCalled();
  223. unmount();
  224. });
  225. it("journal 查询失败时退回产物 tab", async () => {
  226. conversationWorkflowRunArtifactsV4.mockRejectedValue(new Error("capabilityUnsupported"));
  227. const { result, unmount } = renderPanels();
  228. act(() => {
  229. result.current.handleOpenWorkflowArtifact(artifactRequest());
  230. });
  231. await flush();
  232. expect(tabTypes(result.current.sidePaneState?.tabs)).toEqual(["workflow-artifact"]);
  233. expect(result.current.browserNavigationRequest).toBeNull();
  234. unmount();
  235. });
  236. it("产物没有工作区出处时退回产物 tab", async () => {
  237. conversationWorkflowRunArtifactsV4.mockResolvedValue(journalResult(undefined));
  238. const { result, unmount } = renderPanels();
  239. act(() => {
  240. result.current.handleOpenWorkflowArtifact(artifactRequest());
  241. });
  242. await flush();
  243. expect(tabTypes(result.current.sidePaneState?.tabs)).toEqual(["workflow-artifact"]);
  244. expect(result.current.browserNavigationRequest).toBeNull();
  245. unmount();
  246. });
  247. it("中枢那条路径上 owner ref 还没追上时,browser tab 仍归属目标会话", async () => {
  248. // handleOpenSavedWorkflowArtifact 在同一个同步块里先 handleSelectTaskInChat 再开产物,
  249. // 所以点击时 sidePaneOwnerId 还停在上一条会话上。browser tab 的可见性按 ownerTaskId
  250. // 收窄,盖成旧会话的话切换落定后这个 tab 就消失了。
  251. const { result, unmount } = renderPanels({ sidePaneOwnerId: "sess-previous" });
  252. act(() => {
  253. result.current.handleOpenWorkflowArtifact(
  254. artifactRequest({ sourcePath: ".zcode/workflow-runs/run-1/report.html" }),
  255. );
  256. });
  257. await flush();
  258. const tabs = result.current.sidePaneState?.tabs ?? [];
  259. expect(tabTypes(tabs)).toEqual(["browser"]);
  260. expect(tabs[0]).toMatchObject({ ownerTaskId: SESSION_ID, workspaceKey: WORKSPACE_PATH });
  261. // 切换落定后(scope = 目标会话)这个 tab 必须还在可见集合里。
  262. expect(
  263. getVisibleSidePaneTabs(tabs, {
  264. workspaceKey: WORKSPACE_PATH,
  265. ownerTaskId: SESSION_ID,
  266. }).map((tab) => tab.id),
  267. ).toEqual([tabs[0]?.id]);
  268. expect(result.current.sidePaneState?.activeTabId).toBe(tabs[0]?.id);
  269. unmount();
  270. });
  271. it("请求自带 sourcePath 时不查 journal", async () => {
  272. const { result, unmount } = renderPanels();
  273. act(() => {
  274. result.current.handleOpenWorkflowArtifact(
  275. artifactRequest({ sourcePath: ".zcode/workflow-runs/run-1/report.html" }),
  276. );
  277. });
  278. await flush();
  279. expect(tabTypes(result.current.sidePaneState?.tabs)).toEqual(["browser"]);
  280. const tab = result.current.sidePaneState?.tabs[0];
  281. expect(tab?.type === "browser" ? tab.initialUrl : null).toBe(REPORT_URL);
  282. expect(conversationWorkflowRunArtifactsV4).not.toHaveBeenCalled();
  283. unmount();
  284. });
  285. });