v4ConversationDraftSuggestedPromptsContainer.test.ts 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  1. // @vitest-environment jsdom
  2. import { createElement, type ReactNode } from "react";
  3. import { SWRConfig } from "swr";
  4. import {
  5. act,
  6. cleanup,
  7. fireEvent,
  8. render as renderWithTestingLibrary,
  9. screen,
  10. waitFor,
  11. } from "@testing-library/react";
  12. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  13. import { useZCodeSessionStore } from "@/store/zcodeSessionStore.js";
  14. import { ConversationDraftSuggestedPromptsContainer } from "@/v4/ConversationDraftSuggestedPromptsContainer.js";
  15. import { advanceComposerDraftRevision } from "@/v4/composer/composerDraftRevision.js";
  16. const getPluginReferenceCatalog = vi.hoisted(() => vi.fn());
  17. const resolveSuggestedPluginReference = vi.hoisted(() => vi.fn());
  18. const installPlugin = vi.hoisted(() => vi.fn());
  19. const setPluginEnabled = vi.hoisted(() => vi.fn());
  20. const cancelPluginOperation = vi.hoisted(() => vi.fn());
  21. const onDynamicPluginOperationProgress = vi.hoisted(() => vi.fn());
  22. const invalidateDraftSession = vi.hoisted(() => vi.fn());
  23. const listClientScenes = vi.hoisted(() => vi.fn());
  24. const loggerWarn = vi.hoisted(() => vi.fn());
  25. const toast = vi.hoisted(() => vi.fn());
  26. const reportTelemetryEvent = vi.hoisted(() => vi.fn());
  27. const dismissToast = vi.hoisted(() => vi.fn());
  28. const pluginOperationProgressListeners = new Map<
  29. string,
  30. Set<(event: { operationId: string; state: "refreshing" }) => void>
  31. >();
  32. function emitPluginOperationProgress(operationId: string) {
  33. for (const listener of pluginOperationProgressListeners.get(operationId) ?? []) {
  34. listener({ operationId, state: "refreshing" });
  35. }
  36. }
  37. function render(ui: ReactNode) {
  38. return renderWithTestingLibrary(
  39. createElement(
  40. SWRConfig,
  41. {
  42. value: {
  43. provider: () => new Map(),
  44. revalidateOnFocus: false,
  45. revalidateOnReconnect: false,
  46. },
  47. },
  48. ui,
  49. ),
  50. );
  51. }
  52. vi.mock("@/components/ui/toast.js", () => ({ dismissToast, toast }));
  53. // 推荐容器新增共享偏好读取;单测沿用独立 hook mock,避免依赖真实 ServiceProvider。
  54. vi.mock("@/hooks/useSettingService.js", () => {
  55. const value = {
  56. settings: { proactiveSuggestionsEnabled: false, onboardingOccupation: null },
  57. update: vi.fn(),
  58. };
  59. return { useSettings: () => value };
  60. });
  61. vi.mock("@/hooks/usePlatform.js", () => ({
  62. usePlatform: () => ({ reportTelemetryEvent }),
  63. }));
  64. vi.mock("@/lib/zcodeDraftSkillInvalidation.js", () => ({
  65. invalidateDeferredDraftSessionForSkillChange: invalidateDraftSession,
  66. }));
  67. vi.mock("@/logger.js", () => ({
  68. logger: {
  69. warn: loggerWarn,
  70. },
  71. }));
  72. vi.mock("@/hooks/useWorkspaceServices.js", () => {
  73. // 生产 hook 会 memoize resolution/services;测试也必须保持引用稳定,否则 effect setState 后会被假服务引用反复触发。
  74. const services = {
  75. clientScenesService: { list: listClientScenes },
  76. pluginManagementService: {
  77. cancelPluginOperation,
  78. getPluginReferenceCatalog,
  79. installPlugin,
  80. onDynamicPluginOperationProgress,
  81. resolveSuggestedPluginReference,
  82. setPluginEnabled,
  83. },
  84. zcodeSessionService: {},
  85. };
  86. return {
  87. useWorkspaceServicesResolution: (
  88. _workspacePath: string,
  89. preferredRemoteSessionId?: string,
  90. ) => ({
  91. services,
  92. remoteSessionId: preferredRemoteSessionId ?? null,
  93. isRemoteTarget: false,
  94. connectionKind: "local-ready",
  95. rpcReady: true,
  96. }),
  97. };
  98. });
  99. vi.mock("@/i18n/IntlProvider.js", () => ({
  100. useZCodeIntl: () => ({
  101. locale: "zh-CN",
  102. intl: {
  103. formatMessage: ({ id }: { id: string }, values?: { pluginLabel?: string; error?: string }) =>
  104. id === "chat.draft.suggestedPrompt.pluginFlow.installConfirmation"
  105. ? `安装${values?.pluginLabel ?? ""}插件`
  106. : id === "chat.draft.suggestedPrompt.pluginFlow.enableConfirmation"
  107. ? `开启${values?.pluginLabel ?? ""}插件`
  108. : id === "chat.draft.suggestedPrompt.pluginFlow.installFailureToast"
  109. ? `${values?.pluginLabel ?? ""} 安装失败:${values?.error ?? ""}`
  110. : ({
  111. "chat.draft.suggestedPrompt.pluginFlow.installing": "正在安装插件…",
  112. "chat.draft.suggestedPrompt.pluginFlow.enabling": "正在启用插件…",
  113. "chat.draft.suggestedPrompt.pluginFlow.checking": "正在检查插件状态…",
  114. "chat.draft.suggestedPrompt.pluginFlow.confirm": "确认",
  115. "chat.draft.suggestedPrompt.pluginFlow.installSucceeded": "安装成功",
  116. "chat.draft.suggestedPrompt.pluginFlow.installFailed": "插件安装失败",
  117. "chat.draft.suggestedPrompt.pluginFlow.installTimedOut": "安装超时",
  118. "chat.draft.suggestedPrompt.pluginFlow.installReturnedEmpty": "未返回已安装插件",
  119. "chat.draft.suggestedPrompt.pluginFlow.enableSucceeded": "开启成功",
  120. "chat.draft.suggestedPrompt.pluginFlow.enableFailed": "插件开启失败",
  121. }[id] ?? id),
  122. },
  123. }),
  124. }));
  125. const plainPrompt = "检查当前工作区近 7 天的 Git commit,概括主要改动并指出潜在风险。";
  126. const pluginPrompt = "根据当前工作区内容制作一份 PDF 文档。";
  127. const automationsPrompt = "打开自动化面板。";
  128. const offPeakPrompt = "打开闲时任务面板。";
  129. const plainLabel = "检查 commit";
  130. const pluginLabel = "制作 PDF";
  131. const automationsLabel = "自动化";
  132. const offPeakLabel = "闲时任务";
  133. async function applyPendingComposerTextInsert(workspacePath: string, workspaceIdentity?: string) {
  134. const request = await waitFor(() => {
  135. const current = useZCodeSessionStore
  136. .getState()
  137. .getWorkspaceState(workspacePath, workspaceIdentity).composerTextInsertRequest;
  138. if (!current) throw new Error("Composer insert request is not ready");
  139. return current;
  140. });
  141. act(() => {
  142. useZCodeSessionStore
  143. .getState()
  144. .clearComposerTextInsertRequest(workspacePath, request.requestId, workspaceIdentity);
  145. });
  146. return request;
  147. }
  148. const clientScenesResponse = {
  149. code: 0,
  150. msg: "",
  151. data: [
  152. {
  153. namespace: "zcode",
  154. scene: "draft-suggestion",
  155. options: {
  156. prompts: {
  157. id: "prompt",
  158. type: "prompt",
  159. contents: { cn: "提示词", en: "Prompt" },
  160. prompts: { cn: "", en: "" },
  161. items: [
  162. {
  163. id: "recent-commits",
  164. type: "prompt",
  165. contents: { cn: plainPrompt, en: "Check the workspace commits." },
  166. descs: { cn: "", en: "" },
  167. labels: { cn: plainLabel, en: "Check commits" },
  168. on_finish: null,
  169. img: null,
  170. share_urls: {},
  171. },
  172. {
  173. id: "create-pdf",
  174. type: "prompt",
  175. contents: {
  176. cn: pluginPrompt,
  177. en: "Create a PDF from the workspace.",
  178. },
  179. descs: { cn: "", en: "" },
  180. labels: { cn: pluginLabel, en: "Create PDF" },
  181. on_finish: null,
  182. img: null,
  183. share_urls: {},
  184. defaults: { plugin: ["document-skills"] },
  185. },
  186. {
  187. id: "open-automations",
  188. type: "prompt",
  189. contents: {
  190. cn: automationsPrompt,
  191. en: "Open Automations.",
  192. },
  193. descs: { cn: "", en: "" },
  194. labels: { cn: automationsLabel, en: "Automations" },
  195. on_finish: "UNKNOWN:ACTION, NAVIGATE:AUTOMATIONS",
  196. img: null,
  197. share_urls: {},
  198. },
  199. {
  200. id: "open-offpeak",
  201. type: "prompt",
  202. contents: {
  203. cn: offPeakPrompt,
  204. en: "Open Idle-time automations.",
  205. },
  206. descs: { cn: "", en: "" },
  207. labels: { cn: offPeakLabel, en: "Idle-time" },
  208. on_finish: "NAVIGATE:AUTOMATIONS, NAVIGATE:AUTOMATIONS:OFFPEAK",
  209. img: null,
  210. share_urls: {},
  211. },
  212. ],
  213. refer: "",
  214. cascades: {},
  215. },
  216. plugin: {
  217. id: "plugin",
  218. type: "plugin",
  219. contents: { cn: "插件", en: "Plugin" },
  220. prompts: { cn: "", en: "" },
  221. items: [
  222. {
  223. id: "document-skills",
  224. type: "plugin",
  225. contents: {
  226. cn: "document-skills@zcode-plugins-official",
  227. en: "document-skills@zcode-plugins-official",
  228. },
  229. descs: { cn: "", en: "" },
  230. labels: { cn: "文档技能", en: "Document skills" },
  231. on_finish: null,
  232. img: null,
  233. share_urls: {},
  234. },
  235. ],
  236. refer: "",
  237. cascades: {},
  238. },
  239. },
  240. created_at: 1,
  241. updated_at: 2,
  242. },
  243. ],
  244. };
  245. describe("ConversationDraftSuggestedPromptsContainer", () => {
  246. beforeEach(() => {
  247. getPluginReferenceCatalog.mockReset();
  248. getPluginReferenceCatalog.mockResolvedValue({ authority: "workspace", plugins: [] });
  249. resolveSuggestedPluginReference.mockReset();
  250. resolveSuggestedPluginReference.mockResolvedValue({
  251. stableId: "document-skills@zcode-plugins-official",
  252. status: "unavailable",
  253. diagnostics: [],
  254. });
  255. installPlugin.mockReset();
  256. installPlugin.mockResolvedValue({
  257. dependencyClosure: ["document-skills@zcode-plugins-official"],
  258. installedPlugins: [
  259. {
  260. id: "document-skills@zcode-plugins-official",
  261. name: "document-skills",
  262. marketplace: "zcode-plugins-official",
  263. enabled: true,
  264. scope: "user",
  265. },
  266. ],
  267. diagnostics: [],
  268. });
  269. setPluginEnabled.mockReset();
  270. setPluginEnabled.mockResolvedValue({ enabled: true, plugin: {} });
  271. cancelPluginOperation.mockReset();
  272. cancelPluginOperation.mockResolvedValue({ operationId: "operation", cancelled: true });
  273. pluginOperationProgressListeners.clear();
  274. onDynamicPluginOperationProgress.mockReset();
  275. onDynamicPluginOperationProgress.mockImplementation(
  276. (operationId: string) =>
  277. (listener: (event: { operationId: string; state: "refreshing" }) => void) => {
  278. const listeners =
  279. pluginOperationProgressListeners.get(operationId) ??
  280. new Set<(event: { operationId: string; state: "refreshing" }) => void>();
  281. listeners.add(listener);
  282. pluginOperationProgressListeners.set(operationId, listeners);
  283. return {
  284. dispose() {
  285. listeners.delete(listener);
  286. if (listeners.size === 0) pluginOperationProgressListeners.delete(operationId);
  287. },
  288. };
  289. },
  290. );
  291. invalidateDraftSession.mockReset();
  292. invalidateDraftSession.mockResolvedValue(undefined);
  293. listClientScenes.mockReset();
  294. listClientScenes.mockResolvedValue(clientScenesResponse);
  295. loggerWarn.mockReset();
  296. toast.mockReset();
  297. let nextToastId = 1;
  298. toast.mockImplementation(() => nextToastId++);
  299. dismissToast.mockReset();
  300. reportTelemetryEvent.mockReset();
  301. reportTelemetryEvent.mockResolvedValue(undefined);
  302. });
  303. afterEach(() => {
  304. cleanup();
  305. });
  306. it("reserves an in-flow slot for the async list below the composer", async () => {
  307. const view = render(
  308. createElement(ConversationDraftSuggestedPromptsContainer, {
  309. className: "mt-3",
  310. workspacePath: "/tmp/suggested-prompt-layout",
  311. }),
  312. );
  313. await screen.findByRole("button", { name: plainLabel });
  314. const slot = view.container.firstElementChild;
  315. expect(slot?.getAttribute("data-v4-draft-suggested-prompts-slot")).toBe("true");
  316. expect(slot?.classList.contains("h-8")).toBe(true);
  317. expect(slot?.classList.contains("mt-3")).toBe(true);
  318. expect(slot?.classList.contains("absolute")).toBe(false);
  319. expect(slot?.classList.contains("top-full")).toBe(false);
  320. });
  321. it("keeps the in-flow slot mounted while the async list is empty", () => {
  322. listClientScenes.mockImplementation(() => new Promise(() => {}));
  323. const view = render(
  324. createElement(ConversationDraftSuggestedPromptsContainer, {
  325. workspacePath: "/tmp/suggested-prompt-empty-slot",
  326. }),
  327. );
  328. const slot = view.container.firstElementChild;
  329. expect(slot?.getAttribute("data-v4-draft-suggested-prompts-slot")).toBe("true");
  330. expect(slot?.classList.contains("h-8")).toBe(true);
  331. expect(slot?.childElementCount).toBe(0);
  332. });
  333. it("keeps the list empty when client scenes only has the legacy ai-writing scene", async () => {
  334. listClientScenes.mockResolvedValue({
  335. code: 0,
  336. msg: "",
  337. data: [{ ...clientScenesResponse.data[0], scene: "ai-writing" }],
  338. });
  339. render(
  340. createElement(ConversationDraftSuggestedPromptsContainer, {
  341. workspacePath: "/tmp/suggested-prompt-scenes",
  342. }),
  343. );
  344. await waitFor(() => expect(listClientScenes).toHaveBeenCalledOnce());
  345. expect(screen.queryAllByRole("button")).toHaveLength(0);
  346. });
  347. it("keeps the list empty and logs a warning when client scenes fails", async () => {
  348. listClientScenes.mockRejectedValue(new Error("offline"));
  349. render(
  350. createElement(ConversationDraftSuggestedPromptsContainer, {
  351. workspacePath: "/tmp/suggested-prompt-scenes-error",
  352. }),
  353. );
  354. await waitFor(() => expect(loggerWarn).toHaveBeenCalledOnce());
  355. expect(screen.queryAllByRole("button")).toHaveLength(0);
  356. });
  357. it("filters Automations navigation prompts when the navigation capability is absent", async () => {
  358. render(
  359. createElement(ConversationDraftSuggestedPromptsContainer, {
  360. workspacePath: "/tmp/suggested-prompt-no-automations",
  361. }),
  362. );
  363. await screen.findByRole("button", { name: plainLabel });
  364. expect(screen.queryByRole("button", { name: automationsLabel })).toBeNull();
  365. expect(screen.queryByRole("button", { name: offPeakLabel })).toBeNull();
  366. });
  367. it("opens Automations without prefilling or sending", async () => {
  368. const workspacePath = "/tmp/suggested-prompt-automations";
  369. const onOpenAutomations = vi.fn();
  370. render(
  371. createElement(ConversationDraftSuggestedPromptsContainer, {
  372. workspacePath,
  373. onOpenAutomations,
  374. }),
  375. );
  376. fireEvent.click(await screen.findByRole("button", { name: automationsLabel }));
  377. expect(onOpenAutomations).toHaveBeenCalledOnce();
  378. expect(
  379. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  380. ).toBeNull();
  381. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  382. });
  383. it("reports a Desktop template click before plugin resolution", async () => {
  384. const workspacePath = "/tmp/suggested-prompt-desktop-telemetry";
  385. render(
  386. createElement(ConversationDraftSuggestedPromptsContainer, {
  387. workspacePath,
  388. isDesktop: true,
  389. }),
  390. );
  391. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  392. expect(reportTelemetryEvent).toHaveBeenCalledOnce();
  393. expect(reportTelemetryEvent).toHaveBeenCalledWith(
  394. expect.objectContaining({
  395. elementName: "prompt_template_ck",
  396. eventRegion: "app.session",
  397. eventType: "ck",
  398. eventText: pluginLabel,
  399. eventExtraDetail: {
  400. template_id: "create-pdf",
  401. template_prompt: pluginPrompt,
  402. },
  403. }),
  404. );
  405. });
  406. it("does not report template clicks on non-Desktop surfaces", async () => {
  407. const workspacePath = "/tmp/suggested-prompt-web-telemetry";
  408. render(
  409. createElement(ConversationDraftSuggestedPromptsContainer, {
  410. workspacePath,
  411. isDesktop: false,
  412. }),
  413. );
  414. fireEvent.click(await screen.findByRole("button", { name: plainLabel }));
  415. expect(reportTelemetryEvent).not.toHaveBeenCalled();
  416. await waitFor(() =>
  417. expect(
  418. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest
  419. ?.text,
  420. ).toBe(plainPrompt),
  421. );
  422. });
  423. it("opens the Idle-time Automations tab without prefilling or navigating twice", async () => {
  424. const workspacePath = "/tmp/suggested-prompt-offpeak";
  425. const onOpenAutomations = vi.fn();
  426. render(
  427. createElement(ConversationDraftSuggestedPromptsContainer, {
  428. workspacePath,
  429. onOpenAutomations,
  430. }),
  431. );
  432. fireEvent.click(await screen.findByRole("button", { name: offPeakLabel }));
  433. expect(onOpenAutomations).toHaveBeenCalledOnce();
  434. expect(onOpenAutomations).toHaveBeenCalledWith("idle");
  435. expect(
  436. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  437. ).toBeNull();
  438. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  439. });
  440. it("replaces the workspace draft with the plain commit prompt without sending", async () => {
  441. const workspacePath = "/tmp/suggested-prompt-plain";
  442. render(
  443. createElement(ConversationDraftSuggestedPromptsContainer, {
  444. workspacePath,
  445. }),
  446. );
  447. fireEvent.click(await screen.findByRole("button", { name: plainLabel }));
  448. await waitFor(() =>
  449. expect(
  450. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  451. ).toEqual({
  452. requestId: 1,
  453. text: plainPrompt,
  454. }),
  455. );
  456. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  457. });
  458. it("waits for trusted resolution, then inserts Plugin and prompt together once", async () => {
  459. const workspacePath = "/tmp/suggested-prompt-plugin";
  460. const workspaceIdentity = "ssh://host/tmp/suggested-prompt-plugin";
  461. let settleResolution!: (value: Record<string, unknown>) => void;
  462. resolveSuggestedPluginReference.mockReturnValue(
  463. new Promise((resolve) => {
  464. settleResolution = resolve;
  465. }),
  466. );
  467. const insertSpy = vi.spyOn(useZCodeSessionStore.getState(), "requestComposerTextInsert");
  468. render(
  469. createElement(ConversationDraftSuggestedPromptsContainer, {
  470. workspacePath,
  471. workspaceIdentity,
  472. remoteSessionId: "remote-runtime",
  473. }),
  474. );
  475. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  476. await waitFor(() => expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce());
  477. expect(
  478. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  479. .composerTextInsertRequest,
  480. ).toBeNull();
  481. expect(insertSpy).not.toHaveBeenCalled();
  482. expect(toast).not.toHaveBeenCalled();
  483. expect(screen.queryByText("正在检查插件状态…")).toBeNull();
  484. expect(document.querySelector('[data-draft-suggested-plugin-popover="progress"]')).toBeNull();
  485. act(() => {
  486. settleResolution({
  487. stableId: "document-skills@zcode-plugins-official",
  488. status: "ready",
  489. marketplace: "zcode-plugins-official",
  490. pluginName: "document-skills",
  491. sourceTrust: "official",
  492. icon: "https://cdn.example/document-skills.svg",
  493. diagnostics: [],
  494. });
  495. });
  496. await waitFor(() =>
  497. expect(
  498. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  499. .composerTextInsertRequest,
  500. ).toEqual({
  501. requestId: 1,
  502. text: `[@文档技能](plugin://document-skills@zcode-plugins-official) ${pluginPrompt}`,
  503. mention: expect.objectContaining({
  504. id: "plugin:document-skills@zcode-plugins-official",
  505. category: "plugins",
  506. value: "document-skills@zcode-plugins-official",
  507. data: {
  508. pluginId: "document-skills@zcode-plugins-official",
  509. icon: "https://cdn.example/document-skills.svg",
  510. },
  511. }),
  512. }),
  513. );
  514. expect(insertSpy).toHaveBeenCalledOnce();
  515. expect(resolveSuggestedPluginReference).toHaveBeenCalledWith({
  516. workspacePath,
  517. workspaceIdentity,
  518. remoteSessionId: "remote-runtime",
  519. stableId: "document-skills@zcode-plugins-official",
  520. operationId: expect.any(String),
  521. clientMode: "desktop-continuous",
  522. deliveryKind: "desktop-continuous",
  523. });
  524. expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce();
  525. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  526. expect(invalidateDraftSession).not.toHaveBeenCalled();
  527. expect(toast).not.toHaveBeenCalled();
  528. });
  529. it("uses the default Plugin icon when trusted resolution has no listing icon", async () => {
  530. const workspacePath = "/tmp/suggested-prompt-plugin-icon-fallback";
  531. resolveSuggestedPluginReference.mockResolvedValue({
  532. stableId: "document-skills@zcode-plugins-official",
  533. status: "ready",
  534. marketplace: "zcode-plugins-official",
  535. pluginName: "document-skills",
  536. sourceTrust: "official",
  537. diagnostics: [],
  538. });
  539. render(createElement(ConversationDraftSuggestedPromptsContainer, { workspacePath }));
  540. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  541. await waitFor(() =>
  542. expect(
  543. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest
  544. ?.mention?.data,
  545. ).toEqual({ pluginId: "document-skills@zcode-plugins-official" }),
  546. );
  547. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  548. });
  549. it("keeps the plain PDF prompt when trusted resolution fails", async () => {
  550. const workspacePath = "/tmp/suggested-prompt-fallback";
  551. resolveSuggestedPluginReference.mockRejectedValue(new Error("disconnected"));
  552. render(
  553. createElement(ConversationDraftSuggestedPromptsContainer, {
  554. workspacePath,
  555. }),
  556. );
  557. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  558. await waitFor(() =>
  559. expect(
  560. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  561. ).toEqual({
  562. requestId: 1,
  563. text: pluginPrompt,
  564. }),
  565. );
  566. expect(toast).not.toHaveBeenCalled();
  567. });
  568. it("rejects an actionable result that does not attest the canonical official source", async () => {
  569. const workspacePath = "/tmp/suggested-prompt-untrusted-result";
  570. resolveSuggestedPluginReference.mockResolvedValue({
  571. stableId: "document-skills@zcode-plugins-official",
  572. status: "ready",
  573. marketplace: "personal",
  574. pluginName: "document-skills",
  575. diagnostics: [],
  576. });
  577. render(
  578. createElement(ConversationDraftSuggestedPromptsContainer, {
  579. workspacePath,
  580. }),
  581. );
  582. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  583. await waitFor(() => expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce());
  584. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  585. expect(
  586. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  587. ).toEqual({ requestId: 1, text: pluginPrompt });
  588. expect(toast).not.toHaveBeenCalled();
  589. });
  590. it("drops delayed Plugin resolution after the Composer revision changes", async () => {
  591. const workspacePath = "/tmp/suggested-prompt-plugin-user-edit";
  592. let settleResolution!: (value: Record<string, unknown>) => void;
  593. resolveSuggestedPluginReference.mockReturnValue(
  594. new Promise((resolve) => {
  595. settleResolution = resolve;
  596. }),
  597. );
  598. render(createElement(ConversationDraftSuggestedPromptsContainer, { workspacePath }));
  599. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  600. await waitFor(() => expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce());
  601. expect(toast).not.toHaveBeenCalled();
  602. await act(async () => {
  603. advanceComposerDraftRevision(workspacePath);
  604. settleResolution({
  605. stableId: "document-skills@zcode-plugins-official",
  606. status: "missing",
  607. marketplace: "zcode-plugins-official",
  608. pluginName: "document-skills",
  609. sourceTrust: "official",
  610. diagnostics: [],
  611. });
  612. });
  613. expect(
  614. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  615. ).toBeNull();
  616. expect(toast).not.toHaveBeenCalled();
  617. expect(dismissToast).not.toHaveBeenCalled();
  618. });
  619. it("installs a refreshed missing candidate in User scope, then prepends the chip", async () => {
  620. const workspacePath = "/tmp/suggested-prompt-missing";
  621. const workspaceIdentity = "ssh://host/tmp/suggested-prompt-missing";
  622. resolveSuggestedPluginReference
  623. .mockResolvedValueOnce({
  624. stableId: "document-skills@zcode-plugins-official",
  625. status: "missing",
  626. marketplace: "zcode-plugins-official",
  627. pluginName: "document-skills",
  628. sourceTrust: "official",
  629. diagnostics: [],
  630. })
  631. .mockResolvedValueOnce({
  632. stableId: "document-skills@zcode-plugins-official",
  633. status: "ready",
  634. marketplace: "zcode-plugins-official",
  635. pluginName: "document-skills",
  636. sourceTrust: "official",
  637. icon: "https://cdn.example/document-skills.svg",
  638. diagnostics: [],
  639. });
  640. render(
  641. createElement(ConversationDraftSuggestedPromptsContainer, {
  642. workspacePath,
  643. workspaceIdentity,
  644. remoteSessionId: "remote-runtime",
  645. }),
  646. );
  647. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  648. expect(
  649. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  650. .composerTextInsertRequest,
  651. ).toBeNull();
  652. expect(await applyPendingComposerTextInsert(workspacePath, workspaceIdentity)).toEqual({
  653. requestId: 1,
  654. text: pluginPrompt,
  655. });
  656. const installAction = await screen.findByRole("button", { name: "确认" });
  657. const confirmationPopover = document.querySelector<HTMLElement>(
  658. '[data-draft-suggested-plugin-popover="confirmation"]',
  659. );
  660. expect(confirmationPopover?.getAttribute("data-anchor-item-id")).toBe("create-pdf");
  661. expect(confirmationPopover?.textContent).toContain("安装文档技能插件");
  662. expect(installPlugin).not.toHaveBeenCalled();
  663. expect(toast).not.toHaveBeenCalled();
  664. fireEvent.click(installAction);
  665. await waitFor(() =>
  666. expect(installPlugin).toHaveBeenCalledWith({
  667. workspacePath,
  668. workspaceIdentity,
  669. remoteSessionId: "remote-runtime",
  670. pluginName: "document-skills",
  671. marketplace: "zcode-plugins-official",
  672. scope: "user",
  673. operationId: expect.any(String),
  674. }),
  675. );
  676. expect(await screen.findByText("正在安装插件…")).not.toBeNull();
  677. expect(
  678. document.querySelector('[data-draft-suggested-plugin-popover="progress"]'),
  679. ).not.toBeNull();
  680. await waitFor(() =>
  681. expect(
  682. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  683. .composerTextInsertRequest,
  684. ).toEqual(
  685. expect.objectContaining({
  686. requestId: 2,
  687. mode: "prepend-if-missing",
  688. }),
  689. ),
  690. );
  691. expect(
  692. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  693. .composerTextInsertRequest?.mention?.data,
  694. ).toEqual({
  695. pluginId: "document-skills@zcode-plugins-official",
  696. icon: "https://cdn.example/document-skills.svg",
  697. });
  698. expect(screen.queryByText("安装成功")).toBeNull();
  699. vi.useFakeTimers();
  700. try {
  701. await act(async () => {
  702. useZCodeSessionStore
  703. .getState()
  704. .clearComposerTextInsertRequest(workspacePath, 2, workspaceIdentity);
  705. await Promise.resolve();
  706. await Promise.resolve();
  707. await Promise.resolve();
  708. });
  709. expect(screen.getByText("安装成功")).not.toBeNull();
  710. expect(
  711. document.querySelector('[data-draft-suggested-plugin-popover="success"]'),
  712. ).not.toBeNull();
  713. await act(async () => {
  714. vi.advanceTimersByTime(1_999);
  715. await Promise.resolve();
  716. });
  717. expect(screen.getByText("安装成功")).not.toBeNull();
  718. await act(async () => {
  719. vi.advanceTimersByTime(1);
  720. await Promise.resolve();
  721. });
  722. expect(screen.queryByText("安装成功")).toBeNull();
  723. expect(toast).not.toHaveBeenCalled();
  724. } finally {
  725. vi.useRealTimers();
  726. }
  727. expect(invalidateDraftSession).toHaveBeenCalledOnce();
  728. expect(resolveSuggestedPluginReference).toHaveBeenCalledTimes(2);
  729. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  730. });
  731. it("keeps one Popover from missing-plugin refresh loading through confirmation", async () => {
  732. const workspacePath = "/tmp/suggested-prompt-stable-popover-anchor";
  733. let settleResolution!: (value: Record<string, unknown>) => void;
  734. resolveSuggestedPluginReference.mockReturnValue(
  735. new Promise((resolve) => {
  736. settleResolution = resolve;
  737. }),
  738. );
  739. render(
  740. createElement(ConversationDraftSuggestedPromptsContainer, {
  741. workspacePath,
  742. }),
  743. );
  744. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  745. await waitFor(() => expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce());
  746. const operationId = resolveSuggestedPluginReference.mock.calls[0]?.[0].operationId as string;
  747. act(() => emitPluginOperationProgress(operationId));
  748. expect(await screen.findByText("正在检查插件状态…")).not.toBeNull();
  749. const loadingPopover = document.querySelector<HTMLElement>(
  750. '[data-draft-suggested-plugin-popover="progress"]',
  751. );
  752. expect(loadingPopover?.getAttribute("data-anchor-item-id")).toBe("create-pdf");
  753. expect(document.querySelectorAll("[data-draft-suggested-plugin-popover]")).toHaveLength(1);
  754. act(() => {
  755. settleResolution({
  756. stableId: "document-skills@zcode-plugins-official",
  757. status: "missing",
  758. marketplace: "zcode-plugins-official",
  759. pluginName: "document-skills",
  760. sourceTrust: "official",
  761. diagnostics: [],
  762. });
  763. });
  764. await waitFor(() =>
  765. expect(
  766. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  767. ).toEqual({ requestId: 1, text: pluginPrompt }),
  768. );
  769. expect(screen.queryByRole("button", { name: "确认" })).toBeNull();
  770. act(() => {
  771. useZCodeSessionStore.getState().clearComposerTextInsertRequest(workspacePath, 1);
  772. });
  773. expect(await screen.findByRole("button", { name: "确认" })).not.toBeNull();
  774. const confirmationPopover = document.querySelector<HTMLElement>(
  775. '[data-draft-suggested-plugin-popover="confirmation"]',
  776. );
  777. expect(confirmationPopover).toBe(loadingPopover);
  778. expect(document.querySelectorAll("[data-draft-suggested-plugin-popover]")).toHaveLength(1);
  779. });
  780. it("enables an installed disabled Plugin before inserting the chip", async () => {
  781. const workspacePath = "/tmp/suggested-prompt-disabled";
  782. resolveSuggestedPluginReference
  783. .mockResolvedValueOnce({
  784. stableId: "document-skills@zcode-plugins-official",
  785. status: "disabled",
  786. marketplace: "zcode-plugins-official",
  787. pluginName: "document-skills",
  788. sourceTrust: "official",
  789. diagnostics: [],
  790. })
  791. .mockResolvedValueOnce({
  792. stableId: "document-skills@zcode-plugins-official",
  793. status: "ready",
  794. marketplace: "zcode-plugins-official",
  795. pluginName: "document-skills",
  796. sourceTrust: "official",
  797. icon: "https://cdn.example/document-skills.svg",
  798. diagnostics: [],
  799. });
  800. render(
  801. createElement(ConversationDraftSuggestedPromptsContainer, {
  802. workspacePath,
  803. }),
  804. );
  805. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  806. await waitFor(() =>
  807. expect(
  808. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  809. ).toEqual({ requestId: 1, text: pluginPrompt }),
  810. );
  811. expect(await screen.findByText("正在检查插件状态…")).not.toBeNull();
  812. const checkingPopover = document.querySelector<HTMLElement>(
  813. '[data-draft-suggested-plugin-popover="progress"]',
  814. );
  815. expect(document.querySelectorAll("[data-draft-suggested-plugin-popover]")).toHaveLength(1);
  816. expect(screen.queryByRole("button", { name: "确认" })).toBeNull();
  817. act(() => {
  818. useZCodeSessionStore.getState().clearComposerTextInsertRequest(workspacePath, 1);
  819. });
  820. const enableAction = await screen.findByRole("button", { name: "确认" });
  821. const confirmationPopover = document.querySelector<HTMLElement>(
  822. '[data-draft-suggested-plugin-popover="confirmation"]',
  823. );
  824. expect(confirmationPopover).toBe(checkingPopover);
  825. expect(confirmationPopover?.getAttribute("data-anchor-item-id")).toBe("create-pdf");
  826. expect(confirmationPopover?.textContent).toContain("开启文档技能插件");
  827. expect(toast).not.toHaveBeenCalled();
  828. fireEvent.click(enableAction);
  829. await waitFor(() =>
  830. expect(setPluginEnabled).toHaveBeenCalledWith({
  831. workspacePath,
  832. pluginId: "document-skills@zcode-plugins-official",
  833. enabled: true,
  834. operationId: expect.any(String),
  835. }),
  836. );
  837. expect(await screen.findByText("正在启用插件…")).not.toBeNull();
  838. expect(
  839. document.querySelector('[data-draft-suggested-plugin-popover="progress"]'),
  840. ).not.toBeNull();
  841. await waitFor(() =>
  842. expect(
  843. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest
  844. ?.requestId,
  845. ).toBe(2),
  846. );
  847. expect(screen.queryByText("安装成功")).toBeNull();
  848. act(() => {
  849. useZCodeSessionStore.getState().clearComposerTextInsertRequest(workspacePath, 2);
  850. });
  851. expect(screen.queryByText("安装成功")).toBeNull();
  852. expect(await screen.findByText("开启成功")).not.toBeNull();
  853. expect(
  854. document.querySelector('[data-draft-suggested-plugin-popover="success"]'),
  855. ).not.toBeNull();
  856. expect(toast).not.toHaveBeenCalled();
  857. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  858. });
  859. it("replaces the persistent enablement Popover with failure and never calls toast", async () => {
  860. const workspacePath = "/tmp/suggested-prompt-enable-failed";
  861. resolveSuggestedPluginReference.mockResolvedValue({
  862. stableId: "document-skills@zcode-plugins-official",
  863. status: "disabled",
  864. marketplace: "zcode-plugins-official",
  865. pluginName: "document-skills",
  866. sourceTrust: "official",
  867. diagnostics: [],
  868. });
  869. setPluginEnabled.mockRejectedValue(new Error("enable failed"));
  870. render(createElement(ConversationDraftSuggestedPromptsContainer, { workspacePath }));
  871. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  872. await applyPendingComposerTextInsert(workspacePath);
  873. fireEvent.click(await screen.findByRole("button", { name: "确认" }));
  874. expect(await screen.findByText("正在启用插件…")).not.toBeNull();
  875. expect(await screen.findByText("插件开启失败")).not.toBeNull();
  876. expect(document.querySelector('[data-draft-suggested-plugin-popover="error"]')).not.toBeNull();
  877. expect(toast).not.toHaveBeenCalled();
  878. });
  879. it.each(["missing", "disabled"] as const)(
  880. "keeps a %s Plugin confirmation open without a timeout and cancels it on outside pointer down",
  881. async (status) => {
  882. const workspacePath = `/tmp/suggested-prompt-${status}-confirmation-outside`;
  883. resolveSuggestedPluginReference.mockResolvedValue({
  884. stableId: "document-skills@zcode-plugins-official",
  885. status,
  886. marketplace: "zcode-plugins-official",
  887. pluginName: "document-skills",
  888. sourceTrust: "official",
  889. diagnostics: [],
  890. });
  891. render(
  892. createElement(ConversationDraftSuggestedPromptsContainer, {
  893. workspacePath,
  894. }),
  895. );
  896. await screen.findByRole("button", { name: pluginLabel });
  897. vi.useFakeTimers();
  898. try {
  899. fireEvent.click(screen.getByRole("button", { name: pluginLabel }));
  900. await act(async () => {
  901. await Promise.resolve();
  902. await Promise.resolve();
  903. });
  904. const plainRequest = useZCodeSessionStore
  905. .getState()
  906. .getWorkspaceState(workspacePath).composerTextInsertRequest;
  907. expect(plainRequest).toEqual({ requestId: 1, text: pluginPrompt });
  908. act(() => {
  909. useZCodeSessionStore
  910. .getState()
  911. .clearComposerTextInsertRequest(workspacePath, plainRequest!.requestId);
  912. });
  913. await act(async () => {
  914. await Promise.resolve();
  915. });
  916. expect(screen.getByRole("button", { name: "确认" })).not.toBeNull();
  917. await act(async () => {
  918. vi.advanceTimersByTime(60_000);
  919. await Promise.resolve();
  920. await Promise.resolve();
  921. });
  922. expect(installPlugin).not.toHaveBeenCalled();
  923. expect(setPluginEnabled).not.toHaveBeenCalled();
  924. expect(cancelPluginOperation).not.toHaveBeenCalled();
  925. expect(screen.getByRole("button", { name: "确认" })).not.toBeNull();
  926. fireEvent.pointerDown(document.body);
  927. await act(async () => {
  928. await Promise.resolve();
  929. await Promise.resolve();
  930. });
  931. expect(cancelPluginOperation).toHaveBeenCalledOnce();
  932. expect(screen.queryByRole("button", { name: "确认" })).toBeNull();
  933. expect(toast).not.toHaveBeenCalled();
  934. expect(
  935. useZCodeSessionStore.getState().getWorkspaceState(workspacePath)
  936. .composerTextInsertRequest,
  937. ).toBeNull();
  938. } finally {
  939. vi.useRealTimers();
  940. }
  941. },
  942. );
  943. it("closes a confirmation and still applies the recommendation clicked outside it", async () => {
  944. const workspacePath = "/tmp/suggested-prompt-confirmation-outside-recommendation";
  945. resolveSuggestedPluginReference.mockResolvedValue({
  946. stableId: "document-skills@zcode-plugins-official",
  947. status: "missing",
  948. marketplace: "zcode-plugins-official",
  949. pluginName: "document-skills",
  950. sourceTrust: "official",
  951. diagnostics: [],
  952. });
  953. render(createElement(ConversationDraftSuggestedPromptsContainer, { workspacePath }));
  954. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  955. await applyPendingComposerTextInsert(workspacePath);
  956. expect(await screen.findByRole("button", { name: "确认" })).not.toBeNull();
  957. const plainRecommendation = screen.getByRole("button", { name: plainLabel });
  958. fireEvent.pointerDown(plainRecommendation);
  959. fireEvent.click(plainRecommendation);
  960. await waitFor(() => expect(cancelPluginOperation).toHaveBeenCalledOnce());
  961. await waitFor(() =>
  962. expect(
  963. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  964. ).toEqual({ requestId: 2, text: plainPrompt }),
  965. );
  966. expect(screen.queryByRole("button", { name: "确认" })).toBeNull();
  967. expect(installPlugin).not.toHaveBeenCalled();
  968. });
  969. it("restores the same confirmation Popover after installation failure and retries with a new operation", async () => {
  970. const workspacePath = "/tmp/suggested-prompt-install-failed";
  971. let settleInstall!: (value: Record<string, unknown>) => void;
  972. resolveSuggestedPluginReference.mockResolvedValue({
  973. stableId: "document-skills@zcode-plugins-official",
  974. status: "missing",
  975. marketplace: "zcode-plugins-official",
  976. pluginName: "document-skills",
  977. sourceTrust: "official",
  978. diagnostics: [],
  979. });
  980. installPlugin
  981. .mockReturnValueOnce(
  982. new Promise((resolve) => {
  983. settleInstall = resolve;
  984. }),
  985. )
  986. .mockReturnValueOnce(
  987. new Promise(() => {
  988. // 第二次安装保持 pending,用于验证恢复后的确认按钮确实可重试。
  989. }),
  990. );
  991. render(
  992. createElement(ConversationDraftSuggestedPromptsContainer, {
  993. workspacePath,
  994. }),
  995. );
  996. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  997. expect(await applyPendingComposerTextInsert(workspacePath)).toEqual({
  998. requestId: 1,
  999. text: pluginPrompt,
  1000. });
  1001. fireEvent.click(await screen.findByRole("button", { name: "确认" }));
  1002. expect(await screen.findByText("正在安装插件…")).not.toBeNull();
  1003. const progressPopover = document.querySelector(
  1004. '[data-draft-suggested-plugin-popover="progress"]',
  1005. );
  1006. act(() => {
  1007. settleInstall({
  1008. dependencyClosure: [],
  1009. installedPlugins: [],
  1010. diagnostics: [{ code: "install_failed", message: "offline", severity: "error" }],
  1011. });
  1012. });
  1013. const retryAction = await screen.findByRole("button", { name: "确认" });
  1014. const retryPopover = document.querySelector(
  1015. '[data-draft-suggested-plugin-popover="confirmation"]',
  1016. );
  1017. expect(retryPopover).toBe(progressPopover);
  1018. expect(screen.queryByText("插件安装失败")).toBeNull();
  1019. expect(document.querySelector('[data-draft-suggested-plugin-popover="error"]')).toBeNull();
  1020. expect(toast).toHaveBeenCalledWith("文档技能 安装失败:offline", {
  1021. variant: "warning",
  1022. });
  1023. expect(loggerWarn).toHaveBeenCalledWith(
  1024. "[v4-suggested-prompts] 推荐插件安装失败,恢复确认态以便重试",
  1025. expect.objectContaining({
  1026. error: "offline",
  1027. operationId: expect.any(String),
  1028. pluginId: "document-skills@zcode-plugins-official",
  1029. workspaceKey: workspacePath,
  1030. }),
  1031. );
  1032. const firstOperationId = installPlugin.mock.calls[0]?.[0]?.operationId;
  1033. fireEvent.click(retryAction);
  1034. await waitFor(() => expect(installPlugin).toHaveBeenCalledTimes(2));
  1035. expect(installPlugin.mock.calls[1]?.[0]?.operationId).not.toBe(firstOperationId);
  1036. expect(await screen.findByText("正在安装插件…")).not.toBeNull();
  1037. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  1038. expect(
  1039. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  1040. ).toBeNull();
  1041. });
  1042. it("fails a plugin installation at ten seconds, cancels it, and keeps the plain prompt", async () => {
  1043. const workspacePath = "/tmp/suggested-prompt-install-timeout";
  1044. let settleLateInstall!: (value: Record<string, unknown>) => void;
  1045. resolveSuggestedPluginReference.mockResolvedValue({
  1046. stableId: "document-skills@zcode-plugins-official",
  1047. status: "missing",
  1048. marketplace: "zcode-plugins-official",
  1049. pluginName: "document-skills",
  1050. sourceTrust: "official",
  1051. diagnostics: [],
  1052. });
  1053. installPlugin.mockReturnValue(
  1054. new Promise((resolve) => {
  1055. settleLateInstall = resolve;
  1056. }),
  1057. );
  1058. render(
  1059. createElement(ConversationDraftSuggestedPromptsContainer, {
  1060. workspacePath,
  1061. }),
  1062. );
  1063. await screen.findByRole("button", { name: pluginLabel });
  1064. vi.useFakeTimers();
  1065. try {
  1066. fireEvent.click(screen.getByRole("button", { name: pluginLabel }));
  1067. await act(async () => {
  1068. await Promise.resolve();
  1069. await Promise.resolve();
  1070. });
  1071. const plainRequest = useZCodeSessionStore
  1072. .getState()
  1073. .getWorkspaceState(workspacePath).composerTextInsertRequest;
  1074. expect(plainRequest).toEqual({ requestId: 1, text: pluginPrompt });
  1075. act(() => {
  1076. useZCodeSessionStore
  1077. .getState()
  1078. .clearComposerTextInsertRequest(workspacePath, plainRequest!.requestId);
  1079. });
  1080. await act(async () => {
  1081. await Promise.resolve();
  1082. });
  1083. await vi.waitFor(() => expect(screen.getByRole("button", { name: "确认" })).not.toBeNull());
  1084. fireEvent.click(screen.getByRole("button", { name: "确认" }));
  1085. expect(installPlugin).toHaveBeenCalledOnce();
  1086. expect(screen.getByText("正在安装插件…")).not.toBeNull();
  1087. await act(async () => {
  1088. vi.advanceTimersByTime(9_999);
  1089. await Promise.resolve();
  1090. });
  1091. expect(cancelPluginOperation).not.toHaveBeenCalled();
  1092. expect(screen.queryByRole("button", { name: "确认" })).toBeNull();
  1093. await act(async () => {
  1094. vi.advanceTimersByTime(1);
  1095. await Promise.resolve();
  1096. await Promise.resolve();
  1097. await Promise.resolve();
  1098. });
  1099. expect(cancelPluginOperation).toHaveBeenCalledWith({ operationId: expect.any(String) });
  1100. expect(screen.getByRole("button", { name: "确认" })).not.toBeNull();
  1101. expect(
  1102. document.querySelector('[data-draft-suggested-plugin-popover="confirmation"]'),
  1103. ).not.toBeNull();
  1104. expect(document.querySelector('[data-draft-suggested-plugin-popover="error"]')).toBeNull();
  1105. expect(toast).toHaveBeenCalledWith("文档技能 安装失败:安装超时", {
  1106. variant: "warning",
  1107. });
  1108. expect(loggerWarn).toHaveBeenCalledWith(
  1109. "[v4-suggested-prompts] 推荐插件安装失败,恢复确认态以便重试",
  1110. expect.objectContaining({
  1111. error: "安装超时",
  1112. operationId: expect.any(String),
  1113. pluginId: "document-skills@zcode-plugins-official",
  1114. workspaceKey: workspacePath,
  1115. }),
  1116. );
  1117. expect(
  1118. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  1119. ).toBeNull();
  1120. await act(async () => {
  1121. settleLateInstall({
  1122. dependencyClosure: ["document-skills@zcode-plugins-official"],
  1123. installedPlugins: [
  1124. {
  1125. id: "document-skills@zcode-plugins-official",
  1126. name: "document-skills",
  1127. marketplace: "zcode-plugins-official",
  1128. enabled: true,
  1129. scope: "user",
  1130. },
  1131. ],
  1132. diagnostics: [],
  1133. });
  1134. await Promise.resolve();
  1135. await Promise.resolve();
  1136. });
  1137. expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce();
  1138. expect(
  1139. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  1140. ).toBeNull();
  1141. expect(screen.queryByText("安装成功")).toBeNull();
  1142. expect(screen.getByRole("button", { name: "确认" })).not.toBeNull();
  1143. } finally {
  1144. vi.useRealTimers();
  1145. }
  1146. });
  1147. it("keeps the pure prompt and does not offer installation when refresh fails closed", async () => {
  1148. const workspacePath = "/tmp/suggested-prompt-refresh-failed";
  1149. resolveSuggestedPluginReference.mockResolvedValue({
  1150. stableId: "document-skills@zcode-plugins-official",
  1151. status: "unavailable",
  1152. diagnostics: [
  1153. {
  1154. code: "marketplace_refresh_failed",
  1155. message: "offline",
  1156. severity: "error",
  1157. },
  1158. ],
  1159. });
  1160. render(
  1161. createElement(ConversationDraftSuggestedPromptsContainer, {
  1162. workspacePath,
  1163. isWebRemoteControl: true,
  1164. }),
  1165. );
  1166. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  1167. await waitFor(() => expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce());
  1168. expect(
  1169. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  1170. ).toEqual({ requestId: 1, text: pluginPrompt });
  1171. expect(toast).not.toHaveBeenCalled();
  1172. expect(resolveSuggestedPluginReference).toHaveBeenCalledWith(
  1173. expect.objectContaining({
  1174. clientMode: "web-remote-replayable",
  1175. deliveryKind: "web-remote-replayable",
  1176. }),
  1177. );
  1178. });
  1179. it("cancels the older operation, disables recommendations until cancellation settles, and drops late results", async () => {
  1180. const workspacePath = "/tmp/suggested-prompt-cancel";
  1181. let resolveOld!: (value: Record<string, unknown>) => void;
  1182. let resolveCancel!: (value: Record<string, unknown>) => void;
  1183. resolveSuggestedPluginReference.mockResolvedValue({
  1184. stableId: "document-skills@zcode-plugins-official",
  1185. status: "missing",
  1186. marketplace: "zcode-plugins-official",
  1187. pluginName: "document-skills",
  1188. sourceTrust: "official",
  1189. diagnostics: [],
  1190. });
  1191. installPlugin.mockReturnValue(
  1192. new Promise((resolve) => {
  1193. resolveOld = resolve;
  1194. }),
  1195. );
  1196. cancelPluginOperation.mockReturnValue(
  1197. new Promise((resolve) => {
  1198. resolveCancel = resolve;
  1199. }),
  1200. );
  1201. render(
  1202. createElement(ConversationDraftSuggestedPromptsContainer, {
  1203. workspacePath,
  1204. }),
  1205. );
  1206. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  1207. expect(await applyPendingComposerTextInsert(workspacePath)).toEqual({
  1208. requestId: 1,
  1209. text: pluginPrompt,
  1210. });
  1211. fireEvent.click(await screen.findByRole("button", { name: "确认" }));
  1212. await waitFor(() => expect(installPlugin).toHaveBeenCalledOnce());
  1213. expect(await screen.findByText("正在安装插件…")).not.toBeNull();
  1214. fireEvent.click(
  1215. screen.getByRole("button", {
  1216. name: plainLabel,
  1217. }),
  1218. );
  1219. await waitFor(() =>
  1220. expect(
  1221. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest
  1222. ?.text,
  1223. ).toBe(plainPrompt),
  1224. );
  1225. await waitFor(() => expect(cancelPluginOperation).toHaveBeenCalledOnce());
  1226. expect(screen.queryByText("正在安装插件…")).toBeNull();
  1227. expect((screen.getByRole("button", { name: pluginLabel }) as HTMLButtonElement).disabled).toBe(
  1228. true,
  1229. );
  1230. expect((screen.getByRole("button", { name: plainLabel }) as HTMLButtonElement).disabled).toBe(
  1231. true,
  1232. );
  1233. await act(async () => {
  1234. resolveCancel({ operationId: "old", cancelled: true });
  1235. await Promise.resolve();
  1236. });
  1237. expect((screen.getByRole("button", { name: pluginLabel }) as HTMLButtonElement).disabled).toBe(
  1238. true,
  1239. );
  1240. expect((screen.getByRole("button", { name: plainLabel }) as HTMLButtonElement).disabled).toBe(
  1241. true,
  1242. );
  1243. await act(async () => {
  1244. resolveOld({
  1245. dependencyClosure: ["document-skills@zcode-plugins-official"],
  1246. installedPlugins: [
  1247. {
  1248. id: "document-skills@zcode-plugins-official",
  1249. name: "document-skills",
  1250. marketplace: "zcode-plugins-official",
  1251. enabled: true,
  1252. scope: "user",
  1253. },
  1254. ],
  1255. diagnostics: [],
  1256. });
  1257. await Promise.resolve();
  1258. });
  1259. await waitFor(() =>
  1260. expect(
  1261. (screen.getByRole("button", { name: pluginLabel }) as HTMLButtonElement).disabled,
  1262. ).toBe(false),
  1263. );
  1264. expect(
  1265. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  1266. ).toEqual({
  1267. requestId: 2,
  1268. text: plainPrompt,
  1269. });
  1270. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  1271. expect(
  1272. toast.mock.calls.some(
  1273. ([message]) => String(message).includes("取消") || String(message).includes("中断"),
  1274. ),
  1275. ).toBe(false);
  1276. expect(document.querySelector("[data-draft-suggested-plugin-popover]")).toBeNull();
  1277. });
  1278. it("invalidates an older Plugin prefill when a later click navigates to Automations", async () => {
  1279. const workspacePath = "/tmp/suggested-prompt-navigation-latest-wins";
  1280. const onOpenAutomations = vi.fn();
  1281. let resolveCatalog!: (value: { authority: "workspace"; plugins: [] }) => void;
  1282. getPluginReferenceCatalog.mockReturnValue(
  1283. new Promise((resolve) => {
  1284. resolveCatalog = resolve;
  1285. }),
  1286. );
  1287. render(
  1288. createElement(ConversationDraftSuggestedPromptsContainer, {
  1289. workspacePath,
  1290. onOpenAutomations,
  1291. }),
  1292. );
  1293. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  1294. fireEvent.click(screen.getByRole("button", { name: automationsLabel }));
  1295. expect(onOpenAutomations).toHaveBeenCalledOnce();
  1296. await act(async () => {
  1297. resolveCatalog({ authority: "workspace", plugins: [] });
  1298. await Promise.resolve();
  1299. });
  1300. expect(
  1301. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  1302. ).toBeNull();
  1303. expect(toast).not.toHaveBeenCalled();
  1304. });
  1305. });