v4ConversationDraftSuggestedPromptsContainer.test.ts 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  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("keeps the recommendation slot after the async list arrives", 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. });
  317. it("keeps the slot mounted while the async list is pending", () => {
  318. listClientScenes.mockImplementation(() => new Promise(() => {}));
  319. const view = render(
  320. createElement(ConversationDraftSuggestedPromptsContainer, {
  321. workspacePath: "/tmp/suggested-prompt-empty-slot",
  322. }),
  323. );
  324. const slot = view.container.firstElementChild;
  325. expect(slot?.getAttribute("data-v4-draft-suggested-prompts-slot")).toBe("true");
  326. expect(slot?.childElementCount).toBe(0);
  327. });
  328. it("keeps the list empty when client scenes only has the legacy ai-writing scene", async () => {
  329. listClientScenes.mockResolvedValue({
  330. code: 0,
  331. msg: "",
  332. data: [{ ...clientScenesResponse.data[0], scene: "ai-writing" }],
  333. });
  334. render(
  335. createElement(ConversationDraftSuggestedPromptsContainer, {
  336. workspacePath: "/tmp/suggested-prompt-scenes",
  337. }),
  338. );
  339. await waitFor(() => expect(listClientScenes).toHaveBeenCalledOnce());
  340. expect(screen.queryAllByRole("button")).toHaveLength(0);
  341. });
  342. it("keeps the list empty and logs a warning when client scenes fails", async () => {
  343. listClientScenes.mockRejectedValue(new Error("offline"));
  344. render(
  345. createElement(ConversationDraftSuggestedPromptsContainer, {
  346. workspacePath: "/tmp/suggested-prompt-scenes-error",
  347. }),
  348. );
  349. await waitFor(() => expect(loggerWarn).toHaveBeenCalledOnce());
  350. expect(screen.queryAllByRole("button")).toHaveLength(0);
  351. });
  352. it("filters Automations navigation prompts when the navigation capability is absent", async () => {
  353. render(
  354. createElement(ConversationDraftSuggestedPromptsContainer, {
  355. workspacePath: "/tmp/suggested-prompt-no-automations",
  356. }),
  357. );
  358. await screen.findByRole("button", { name: plainLabel });
  359. expect(screen.queryByRole("button", { name: automationsLabel })).toBeNull();
  360. expect(screen.queryByRole("button", { name: offPeakLabel })).toBeNull();
  361. });
  362. it("opens Automations without prefilling or sending", async () => {
  363. const workspacePath = "/tmp/suggested-prompt-automations";
  364. const onOpenAutomations = vi.fn();
  365. render(
  366. createElement(ConversationDraftSuggestedPromptsContainer, {
  367. workspacePath,
  368. onOpenAutomations,
  369. }),
  370. );
  371. fireEvent.click(await screen.findByRole("button", { name: automationsLabel }));
  372. expect(onOpenAutomations).toHaveBeenCalledOnce();
  373. expect(
  374. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  375. ).toBeNull();
  376. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  377. });
  378. it("reports a Desktop template click before plugin resolution", async () => {
  379. const workspacePath = "/tmp/suggested-prompt-desktop-telemetry";
  380. render(
  381. createElement(ConversationDraftSuggestedPromptsContainer, {
  382. workspacePath,
  383. isDesktop: true,
  384. }),
  385. );
  386. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  387. expect(reportTelemetryEvent).toHaveBeenCalledOnce();
  388. expect(reportTelemetryEvent).toHaveBeenCalledWith(
  389. expect.objectContaining({
  390. elementName: "prompt_template_ck",
  391. eventRegion: "app.session",
  392. eventType: "ck",
  393. eventText: pluginLabel,
  394. eventExtraDetail: {
  395. template_id: "create-pdf",
  396. template_prompt: pluginPrompt,
  397. },
  398. }),
  399. );
  400. });
  401. it("does not report template clicks on non-Desktop surfaces", async () => {
  402. const workspacePath = "/tmp/suggested-prompt-web-telemetry";
  403. render(
  404. createElement(ConversationDraftSuggestedPromptsContainer, {
  405. workspacePath,
  406. isDesktop: false,
  407. }),
  408. );
  409. fireEvent.click(await screen.findByRole("button", { name: plainLabel }));
  410. expect(reportTelemetryEvent).not.toHaveBeenCalled();
  411. await waitFor(() =>
  412. expect(
  413. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest
  414. ?.text,
  415. ).toBe(plainPrompt),
  416. );
  417. });
  418. it("opens the Idle-time Automations tab without prefilling or navigating twice", async () => {
  419. const workspacePath = "/tmp/suggested-prompt-offpeak";
  420. const onOpenAutomations = vi.fn();
  421. render(
  422. createElement(ConversationDraftSuggestedPromptsContainer, {
  423. workspacePath,
  424. onOpenAutomations,
  425. }),
  426. );
  427. fireEvent.click(await screen.findByRole("button", { name: offPeakLabel }));
  428. expect(onOpenAutomations).toHaveBeenCalledOnce();
  429. expect(onOpenAutomations).toHaveBeenCalledWith("idle");
  430. expect(
  431. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  432. ).toBeNull();
  433. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  434. });
  435. it("replaces the workspace draft with the plain commit prompt without sending", async () => {
  436. const workspacePath = "/tmp/suggested-prompt-plain";
  437. render(
  438. createElement(ConversationDraftSuggestedPromptsContainer, {
  439. workspacePath,
  440. }),
  441. );
  442. fireEvent.click(await screen.findByRole("button", { name: plainLabel }));
  443. await waitFor(() =>
  444. expect(
  445. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  446. ).toEqual({
  447. requestId: 1,
  448. text: plainPrompt,
  449. }),
  450. );
  451. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  452. });
  453. it("waits for trusted resolution, then inserts Plugin and prompt together once", async () => {
  454. const workspacePath = "/tmp/suggested-prompt-plugin";
  455. const workspaceIdentity = "ssh://host/tmp/suggested-prompt-plugin";
  456. let settleResolution!: (value: Record<string, unknown>) => void;
  457. resolveSuggestedPluginReference.mockReturnValue(
  458. new Promise((resolve) => {
  459. settleResolution = resolve;
  460. }),
  461. );
  462. const insertSpy = vi.spyOn(useZCodeSessionStore.getState(), "requestComposerTextInsert");
  463. render(
  464. createElement(ConversationDraftSuggestedPromptsContainer, {
  465. workspacePath,
  466. workspaceIdentity,
  467. remoteSessionId: "remote-runtime",
  468. }),
  469. );
  470. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  471. await waitFor(() => expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce());
  472. expect(
  473. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  474. .composerTextInsertRequest,
  475. ).toBeNull();
  476. expect(insertSpy).not.toHaveBeenCalled();
  477. expect(toast).not.toHaveBeenCalled();
  478. expect(screen.queryByText("正在检查插件状态…")).toBeNull();
  479. expect(document.querySelector('[data-draft-suggested-plugin-popover="progress"]')).toBeNull();
  480. act(() => {
  481. settleResolution({
  482. stableId: "document-skills@zcode-plugins-official",
  483. status: "ready",
  484. marketplace: "zcode-plugins-official",
  485. pluginName: "document-skills",
  486. sourceTrust: "official",
  487. icon: "https://cdn.example/document-skills.svg",
  488. diagnostics: [],
  489. });
  490. });
  491. await waitFor(() =>
  492. expect(
  493. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  494. .composerTextInsertRequest,
  495. ).toEqual({
  496. requestId: 1,
  497. text: `[@文档技能](plugin://document-skills@zcode-plugins-official) ${pluginPrompt}`,
  498. mention: expect.objectContaining({
  499. id: "plugin:document-skills@zcode-plugins-official",
  500. category: "plugins",
  501. value: "document-skills@zcode-plugins-official",
  502. data: {
  503. pluginId: "document-skills@zcode-plugins-official",
  504. icon: "https://cdn.example/document-skills.svg",
  505. },
  506. }),
  507. }),
  508. );
  509. expect(insertSpy).toHaveBeenCalledOnce();
  510. expect(resolveSuggestedPluginReference).toHaveBeenCalledWith({
  511. workspacePath,
  512. workspaceIdentity,
  513. remoteSessionId: "remote-runtime",
  514. stableId: "document-skills@zcode-plugins-official",
  515. operationId: expect.any(String),
  516. clientMode: "desktop-continuous",
  517. deliveryKind: "desktop-continuous",
  518. });
  519. expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce();
  520. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  521. expect(invalidateDraftSession).not.toHaveBeenCalled();
  522. expect(toast).not.toHaveBeenCalled();
  523. });
  524. it("uses the default Plugin icon when trusted resolution has no listing icon", async () => {
  525. const workspacePath = "/tmp/suggested-prompt-plugin-icon-fallback";
  526. resolveSuggestedPluginReference.mockResolvedValue({
  527. stableId: "document-skills@zcode-plugins-official",
  528. status: "ready",
  529. marketplace: "zcode-plugins-official",
  530. pluginName: "document-skills",
  531. sourceTrust: "official",
  532. diagnostics: [],
  533. });
  534. render(createElement(ConversationDraftSuggestedPromptsContainer, { workspacePath }));
  535. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  536. await waitFor(() =>
  537. expect(
  538. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest
  539. ?.mention?.data,
  540. ).toEqual({ pluginId: "document-skills@zcode-plugins-official" }),
  541. );
  542. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  543. });
  544. it("keeps the plain PDF prompt when trusted resolution fails", async () => {
  545. const workspacePath = "/tmp/suggested-prompt-fallback";
  546. resolveSuggestedPluginReference.mockRejectedValue(new Error("disconnected"));
  547. render(
  548. createElement(ConversationDraftSuggestedPromptsContainer, {
  549. workspacePath,
  550. }),
  551. );
  552. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  553. await waitFor(() =>
  554. expect(
  555. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  556. ).toEqual({
  557. requestId: 1,
  558. text: pluginPrompt,
  559. }),
  560. );
  561. expect(toast).not.toHaveBeenCalled();
  562. });
  563. it("rejects an actionable result that does not attest the canonical official source", async () => {
  564. const workspacePath = "/tmp/suggested-prompt-untrusted-result";
  565. resolveSuggestedPluginReference.mockResolvedValue({
  566. stableId: "document-skills@zcode-plugins-official",
  567. status: "ready",
  568. marketplace: "personal",
  569. pluginName: "document-skills",
  570. diagnostics: [],
  571. });
  572. render(
  573. createElement(ConversationDraftSuggestedPromptsContainer, {
  574. workspacePath,
  575. }),
  576. );
  577. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  578. await waitFor(() => expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce());
  579. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  580. expect(
  581. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  582. ).toEqual({ requestId: 1, text: pluginPrompt });
  583. expect(toast).not.toHaveBeenCalled();
  584. });
  585. it("drops delayed Plugin resolution after the Composer revision changes", async () => {
  586. const workspacePath = "/tmp/suggested-prompt-plugin-user-edit";
  587. let settleResolution!: (value: Record<string, unknown>) => void;
  588. resolveSuggestedPluginReference.mockReturnValue(
  589. new Promise((resolve) => {
  590. settleResolution = resolve;
  591. }),
  592. );
  593. render(createElement(ConversationDraftSuggestedPromptsContainer, { workspacePath }));
  594. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  595. await waitFor(() => expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce());
  596. expect(toast).not.toHaveBeenCalled();
  597. await act(async () => {
  598. advanceComposerDraftRevision(workspacePath);
  599. settleResolution({
  600. stableId: "document-skills@zcode-plugins-official",
  601. status: "missing",
  602. marketplace: "zcode-plugins-official",
  603. pluginName: "document-skills",
  604. sourceTrust: "official",
  605. diagnostics: [],
  606. });
  607. });
  608. expect(
  609. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  610. ).toBeNull();
  611. expect(toast).not.toHaveBeenCalled();
  612. expect(dismissToast).not.toHaveBeenCalled();
  613. });
  614. it("installs a refreshed missing candidate in User scope, then prepends the chip", async () => {
  615. const workspacePath = "/tmp/suggested-prompt-missing";
  616. const workspaceIdentity = "ssh://host/tmp/suggested-prompt-missing";
  617. resolveSuggestedPluginReference
  618. .mockResolvedValueOnce({
  619. stableId: "document-skills@zcode-plugins-official",
  620. status: "missing",
  621. marketplace: "zcode-plugins-official",
  622. pluginName: "document-skills",
  623. sourceTrust: "official",
  624. diagnostics: [],
  625. })
  626. .mockResolvedValueOnce({
  627. stableId: "document-skills@zcode-plugins-official",
  628. status: "ready",
  629. marketplace: "zcode-plugins-official",
  630. pluginName: "document-skills",
  631. sourceTrust: "official",
  632. icon: "https://cdn.example/document-skills.svg",
  633. diagnostics: [],
  634. });
  635. render(
  636. createElement(ConversationDraftSuggestedPromptsContainer, {
  637. workspacePath,
  638. workspaceIdentity,
  639. remoteSessionId: "remote-runtime",
  640. }),
  641. );
  642. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  643. expect(
  644. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  645. .composerTextInsertRequest,
  646. ).toBeNull();
  647. expect(await applyPendingComposerTextInsert(workspacePath, workspaceIdentity)).toEqual({
  648. requestId: 1,
  649. text: pluginPrompt,
  650. });
  651. const installAction = await screen.findByRole("button", { name: "确认" });
  652. const confirmationPopover = document.querySelector<HTMLElement>(
  653. '[data-draft-suggested-plugin-popover="confirmation"]',
  654. );
  655. expect(confirmationPopover?.getAttribute("data-anchor-item-id")).toBe("create-pdf");
  656. expect(confirmationPopover?.textContent).toContain("安装文档技能插件");
  657. expect(installPlugin).not.toHaveBeenCalled();
  658. expect(toast).not.toHaveBeenCalled();
  659. fireEvent.click(installAction);
  660. await waitFor(() =>
  661. expect(installPlugin).toHaveBeenCalledWith({
  662. telemetry: { entry: "recommended_prompt", client_kind: "desktop" },
  663. workspacePath,
  664. workspaceIdentity,
  665. remoteSessionId: "remote-runtime",
  666. pluginName: "document-skills",
  667. marketplace: "zcode-plugins-official",
  668. scope: "user",
  669. operationId: expect.any(String),
  670. }),
  671. );
  672. expect(await screen.findByText("正在安装插件…")).not.toBeNull();
  673. expect(
  674. document.querySelector('[data-draft-suggested-plugin-popover="progress"]'),
  675. ).not.toBeNull();
  676. await waitFor(() =>
  677. expect(
  678. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  679. .composerTextInsertRequest,
  680. ).toEqual(
  681. expect.objectContaining({
  682. requestId: 2,
  683. mode: "prepend-if-missing",
  684. }),
  685. ),
  686. );
  687. expect(
  688. useZCodeSessionStore.getState().getWorkspaceState(workspacePath, workspaceIdentity)
  689. .composerTextInsertRequest?.mention?.data,
  690. ).toEqual({
  691. pluginId: "document-skills@zcode-plugins-official",
  692. icon: "https://cdn.example/document-skills.svg",
  693. });
  694. expect(screen.queryByText("安装成功")).toBeNull();
  695. vi.useFakeTimers();
  696. try {
  697. await act(async () => {
  698. useZCodeSessionStore
  699. .getState()
  700. .clearComposerTextInsertRequest(workspacePath, 2, workspaceIdentity);
  701. await Promise.resolve();
  702. await Promise.resolve();
  703. await Promise.resolve();
  704. });
  705. expect(screen.getByText("安装成功")).not.toBeNull();
  706. expect(
  707. document.querySelector('[data-draft-suggested-plugin-popover="success"]'),
  708. ).not.toBeNull();
  709. await act(async () => {
  710. vi.advanceTimersByTime(1_999);
  711. await Promise.resolve();
  712. });
  713. expect(screen.getByText("安装成功")).not.toBeNull();
  714. await act(async () => {
  715. vi.advanceTimersByTime(1);
  716. await Promise.resolve();
  717. });
  718. expect(screen.queryByText("安装成功")).toBeNull();
  719. expect(toast).not.toHaveBeenCalled();
  720. } finally {
  721. vi.useRealTimers();
  722. }
  723. expect(invalidateDraftSession).toHaveBeenCalledOnce();
  724. expect(resolveSuggestedPluginReference).toHaveBeenCalledTimes(2);
  725. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  726. });
  727. it("keeps one Popover from missing-plugin refresh loading through confirmation", async () => {
  728. const workspacePath = "/tmp/suggested-prompt-stable-popover-anchor";
  729. let settleResolution!: (value: Record<string, unknown>) => void;
  730. resolveSuggestedPluginReference.mockReturnValue(
  731. new Promise((resolve) => {
  732. settleResolution = resolve;
  733. }),
  734. );
  735. render(
  736. createElement(ConversationDraftSuggestedPromptsContainer, {
  737. workspacePath,
  738. }),
  739. );
  740. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  741. await waitFor(() => expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce());
  742. const operationId = resolveSuggestedPluginReference.mock.calls[0]?.[0].operationId as string;
  743. act(() => emitPluginOperationProgress(operationId));
  744. expect(await screen.findByText("正在检查插件状态…")).not.toBeNull();
  745. const loadingPopover = document.querySelector<HTMLElement>(
  746. '[data-draft-suggested-plugin-popover="progress"]',
  747. );
  748. expect(loadingPopover?.getAttribute("data-anchor-item-id")).toBe("create-pdf");
  749. expect(document.querySelectorAll("[data-draft-suggested-plugin-popover]")).toHaveLength(1);
  750. act(() => {
  751. settleResolution({
  752. stableId: "document-skills@zcode-plugins-official",
  753. status: "missing",
  754. marketplace: "zcode-plugins-official",
  755. pluginName: "document-skills",
  756. sourceTrust: "official",
  757. diagnostics: [],
  758. });
  759. });
  760. await waitFor(() =>
  761. expect(
  762. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  763. ).toEqual({ requestId: 1, text: pluginPrompt }),
  764. );
  765. expect(screen.queryByRole("button", { name: "确认" })).toBeNull();
  766. act(() => {
  767. useZCodeSessionStore.getState().clearComposerTextInsertRequest(workspacePath, 1);
  768. });
  769. expect(await screen.findByRole("button", { name: "确认" })).not.toBeNull();
  770. const confirmationPopover = document.querySelector<HTMLElement>(
  771. '[data-draft-suggested-plugin-popover="confirmation"]',
  772. );
  773. expect(confirmationPopover).toBe(loadingPopover);
  774. expect(document.querySelectorAll("[data-draft-suggested-plugin-popover]")).toHaveLength(1);
  775. });
  776. it("enables an installed disabled Plugin before inserting the chip", async () => {
  777. const workspacePath = "/tmp/suggested-prompt-disabled";
  778. resolveSuggestedPluginReference
  779. .mockResolvedValueOnce({
  780. stableId: "document-skills@zcode-plugins-official",
  781. status: "disabled",
  782. marketplace: "zcode-plugins-official",
  783. pluginName: "document-skills",
  784. sourceTrust: "official",
  785. diagnostics: [],
  786. })
  787. .mockResolvedValueOnce({
  788. stableId: "document-skills@zcode-plugins-official",
  789. status: "ready",
  790. marketplace: "zcode-plugins-official",
  791. pluginName: "document-skills",
  792. sourceTrust: "official",
  793. icon: "https://cdn.example/document-skills.svg",
  794. diagnostics: [],
  795. });
  796. render(
  797. createElement(ConversationDraftSuggestedPromptsContainer, {
  798. workspacePath,
  799. }),
  800. );
  801. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  802. await waitFor(() =>
  803. expect(
  804. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  805. ).toEqual({ requestId: 1, text: pluginPrompt }),
  806. );
  807. expect(await screen.findByText("正在检查插件状态…")).not.toBeNull();
  808. const checkingPopover = document.querySelector<HTMLElement>(
  809. '[data-draft-suggested-plugin-popover="progress"]',
  810. );
  811. expect(document.querySelectorAll("[data-draft-suggested-plugin-popover]")).toHaveLength(1);
  812. expect(screen.queryByRole("button", { name: "确认" })).toBeNull();
  813. act(() => {
  814. useZCodeSessionStore.getState().clearComposerTextInsertRequest(workspacePath, 1);
  815. });
  816. const enableAction = await screen.findByRole("button", { name: "确认" });
  817. const confirmationPopover = document.querySelector<HTMLElement>(
  818. '[data-draft-suggested-plugin-popover="confirmation"]',
  819. );
  820. expect(confirmationPopover).toBe(checkingPopover);
  821. expect(confirmationPopover?.getAttribute("data-anchor-item-id")).toBe("create-pdf");
  822. expect(confirmationPopover?.textContent).toContain("开启文档技能插件");
  823. expect(toast).not.toHaveBeenCalled();
  824. fireEvent.click(enableAction);
  825. await waitFor(() =>
  826. expect(setPluginEnabled).toHaveBeenCalledWith({
  827. telemetry: { entry: "recommended_prompt", client_kind: "desktop" },
  828. workspacePath,
  829. pluginId: "document-skills@zcode-plugins-official",
  830. enabled: true,
  831. operationId: expect.any(String),
  832. }),
  833. );
  834. expect(await screen.findByText("正在启用插件…")).not.toBeNull();
  835. expect(
  836. document.querySelector('[data-draft-suggested-plugin-popover="progress"]'),
  837. ).not.toBeNull();
  838. await waitFor(() =>
  839. expect(
  840. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest
  841. ?.requestId,
  842. ).toBe(2),
  843. );
  844. expect(screen.queryByText("安装成功")).toBeNull();
  845. act(() => {
  846. useZCodeSessionStore.getState().clearComposerTextInsertRequest(workspacePath, 2);
  847. });
  848. expect(screen.queryByText("安装成功")).toBeNull();
  849. expect(await screen.findByText("开启成功")).not.toBeNull();
  850. expect(
  851. document.querySelector('[data-draft-suggested-plugin-popover="success"]'),
  852. ).not.toBeNull();
  853. expect(toast).not.toHaveBeenCalled();
  854. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  855. });
  856. it("replaces the persistent enablement Popover with failure and never calls toast", async () => {
  857. const workspacePath = "/tmp/suggested-prompt-enable-failed";
  858. resolveSuggestedPluginReference.mockResolvedValue({
  859. stableId: "document-skills@zcode-plugins-official",
  860. status: "disabled",
  861. marketplace: "zcode-plugins-official",
  862. pluginName: "document-skills",
  863. sourceTrust: "official",
  864. diagnostics: [],
  865. });
  866. setPluginEnabled.mockRejectedValue(new Error("enable failed"));
  867. render(createElement(ConversationDraftSuggestedPromptsContainer, { workspacePath }));
  868. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  869. await applyPendingComposerTextInsert(workspacePath);
  870. fireEvent.click(await screen.findByRole("button", { name: "确认" }));
  871. expect(await screen.findByText("正在启用插件…")).not.toBeNull();
  872. expect(await screen.findByText("插件开启失败")).not.toBeNull();
  873. expect(document.querySelector('[data-draft-suggested-plugin-popover="error"]')).not.toBeNull();
  874. expect(toast).not.toHaveBeenCalled();
  875. });
  876. it.each(["missing", "disabled"] as const)(
  877. "keeps a %s Plugin confirmation open without a timeout and cancels it on outside pointer down",
  878. async (status) => {
  879. const workspacePath = `/tmp/suggested-prompt-${status}-confirmation-outside`;
  880. resolveSuggestedPluginReference.mockResolvedValue({
  881. stableId: "document-skills@zcode-plugins-official",
  882. status,
  883. marketplace: "zcode-plugins-official",
  884. pluginName: "document-skills",
  885. sourceTrust: "official",
  886. diagnostics: [],
  887. });
  888. render(
  889. createElement(ConversationDraftSuggestedPromptsContainer, {
  890. workspacePath,
  891. }),
  892. );
  893. await screen.findByRole("button", { name: pluginLabel });
  894. vi.useFakeTimers();
  895. try {
  896. fireEvent.click(screen.getByRole("button", { name: pluginLabel }));
  897. await act(async () => {
  898. await Promise.resolve();
  899. await Promise.resolve();
  900. });
  901. const plainRequest = useZCodeSessionStore
  902. .getState()
  903. .getWorkspaceState(workspacePath).composerTextInsertRequest;
  904. expect(plainRequest).toEqual({ requestId: 1, text: pluginPrompt });
  905. act(() => {
  906. useZCodeSessionStore
  907. .getState()
  908. .clearComposerTextInsertRequest(workspacePath, plainRequest!.requestId);
  909. });
  910. await act(async () => {
  911. await Promise.resolve();
  912. });
  913. expect(screen.getByRole("button", { name: "确认" })).not.toBeNull();
  914. await act(async () => {
  915. vi.advanceTimersByTime(60_000);
  916. await Promise.resolve();
  917. await Promise.resolve();
  918. });
  919. expect(installPlugin).not.toHaveBeenCalled();
  920. expect(setPluginEnabled).not.toHaveBeenCalled();
  921. expect(cancelPluginOperation).not.toHaveBeenCalled();
  922. expect(screen.getByRole("button", { name: "确认" })).not.toBeNull();
  923. fireEvent.pointerDown(document.body);
  924. await act(async () => {
  925. await Promise.resolve();
  926. await Promise.resolve();
  927. });
  928. expect(cancelPluginOperation).toHaveBeenCalledOnce();
  929. expect(screen.queryByRole("button", { name: "确认" })).toBeNull();
  930. expect(toast).not.toHaveBeenCalled();
  931. expect(
  932. useZCodeSessionStore.getState().getWorkspaceState(workspacePath)
  933. .composerTextInsertRequest,
  934. ).toBeNull();
  935. } finally {
  936. vi.useRealTimers();
  937. }
  938. },
  939. );
  940. it("closes a confirmation and still applies the recommendation clicked outside it", async () => {
  941. const workspacePath = "/tmp/suggested-prompt-confirmation-outside-recommendation";
  942. resolveSuggestedPluginReference.mockResolvedValue({
  943. stableId: "document-skills@zcode-plugins-official",
  944. status: "missing",
  945. marketplace: "zcode-plugins-official",
  946. pluginName: "document-skills",
  947. sourceTrust: "official",
  948. diagnostics: [],
  949. });
  950. render(createElement(ConversationDraftSuggestedPromptsContainer, { workspacePath }));
  951. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  952. await applyPendingComposerTextInsert(workspacePath);
  953. expect(await screen.findByRole("button", { name: "确认" })).not.toBeNull();
  954. const plainRecommendation = screen.getByRole("button", { name: plainLabel });
  955. fireEvent.pointerDown(plainRecommendation);
  956. fireEvent.click(plainRecommendation);
  957. await waitFor(() => expect(cancelPluginOperation).toHaveBeenCalledOnce());
  958. await waitFor(() =>
  959. expect(
  960. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  961. ).toEqual({ requestId: 2, text: plainPrompt }),
  962. );
  963. expect(screen.queryByRole("button", { name: "确认" })).toBeNull();
  964. expect(installPlugin).not.toHaveBeenCalled();
  965. });
  966. it("restores the same confirmation Popover after installation failure and retries with a new operation", async () => {
  967. const workspacePath = "/tmp/suggested-prompt-install-failed";
  968. let settleInstall!: (value: Record<string, unknown>) => void;
  969. resolveSuggestedPluginReference.mockResolvedValue({
  970. stableId: "document-skills@zcode-plugins-official",
  971. status: "missing",
  972. marketplace: "zcode-plugins-official",
  973. pluginName: "document-skills",
  974. sourceTrust: "official",
  975. diagnostics: [],
  976. });
  977. installPlugin
  978. .mockReturnValueOnce(
  979. new Promise((resolve) => {
  980. settleInstall = resolve;
  981. }),
  982. )
  983. .mockReturnValueOnce(
  984. new Promise(() => {
  985. // 第二次安装保持 pending,用于验证恢复后的确认按钮确实可重试。
  986. }),
  987. );
  988. render(
  989. createElement(ConversationDraftSuggestedPromptsContainer, {
  990. workspacePath,
  991. }),
  992. );
  993. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  994. expect(await applyPendingComposerTextInsert(workspacePath)).toEqual({
  995. requestId: 1,
  996. text: pluginPrompt,
  997. });
  998. fireEvent.click(await screen.findByRole("button", { name: "确认" }));
  999. expect(await screen.findByText("正在安装插件…")).not.toBeNull();
  1000. const progressPopover = document.querySelector(
  1001. '[data-draft-suggested-plugin-popover="progress"]',
  1002. );
  1003. act(() => {
  1004. settleInstall({
  1005. dependencyClosure: [],
  1006. installedPlugins: [],
  1007. diagnostics: [{ code: "install_failed", message: "offline", severity: "error" }],
  1008. });
  1009. });
  1010. const retryAction = await screen.findByRole("button", { name: "确认" });
  1011. const retryPopover = document.querySelector(
  1012. '[data-draft-suggested-plugin-popover="confirmation"]',
  1013. );
  1014. expect(retryPopover).toBe(progressPopover);
  1015. expect(screen.queryByText("插件安装失败")).toBeNull();
  1016. expect(document.querySelector('[data-draft-suggested-plugin-popover="error"]')).toBeNull();
  1017. expect(toast).toHaveBeenCalledWith("文档技能 安装失败:offline", {
  1018. variant: "warning",
  1019. });
  1020. expect(loggerWarn).toHaveBeenCalledWith(
  1021. "[v4-suggested-prompts] 推荐插件安装失败,恢复确认态以便重试",
  1022. expect.objectContaining({
  1023. error: "offline",
  1024. operationId: expect.any(String),
  1025. pluginId: "document-skills@zcode-plugins-official",
  1026. workspaceKey: workspacePath,
  1027. }),
  1028. );
  1029. const firstOperationId = installPlugin.mock.calls[0]?.[0]?.operationId;
  1030. fireEvent.click(retryAction);
  1031. await waitFor(() => expect(installPlugin).toHaveBeenCalledTimes(2));
  1032. expect(installPlugin.mock.calls[1]?.[0]?.operationId).not.toBe(firstOperationId);
  1033. expect(await screen.findByText("正在安装插件…")).not.toBeNull();
  1034. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  1035. expect(
  1036. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  1037. ).toBeNull();
  1038. });
  1039. it("fails a plugin installation at ten seconds, cancels it, and keeps the plain prompt", async () => {
  1040. const workspacePath = "/tmp/suggested-prompt-install-timeout";
  1041. let settleLateInstall!: (value: Record<string, unknown>) => void;
  1042. resolveSuggestedPluginReference.mockResolvedValue({
  1043. stableId: "document-skills@zcode-plugins-official",
  1044. status: "missing",
  1045. marketplace: "zcode-plugins-official",
  1046. pluginName: "document-skills",
  1047. sourceTrust: "official",
  1048. diagnostics: [],
  1049. });
  1050. installPlugin.mockReturnValue(
  1051. new Promise((resolve) => {
  1052. settleLateInstall = resolve;
  1053. }),
  1054. );
  1055. render(
  1056. createElement(ConversationDraftSuggestedPromptsContainer, {
  1057. workspacePath,
  1058. }),
  1059. );
  1060. await screen.findByRole("button", { name: pluginLabel });
  1061. vi.useFakeTimers();
  1062. try {
  1063. fireEvent.click(screen.getByRole("button", { name: pluginLabel }));
  1064. await act(async () => {
  1065. await Promise.resolve();
  1066. await Promise.resolve();
  1067. });
  1068. const plainRequest = useZCodeSessionStore
  1069. .getState()
  1070. .getWorkspaceState(workspacePath).composerTextInsertRequest;
  1071. expect(plainRequest).toEqual({ requestId: 1, text: pluginPrompt });
  1072. act(() => {
  1073. useZCodeSessionStore
  1074. .getState()
  1075. .clearComposerTextInsertRequest(workspacePath, plainRequest!.requestId);
  1076. });
  1077. await act(async () => {
  1078. await Promise.resolve();
  1079. });
  1080. await vi.waitFor(() => expect(screen.getByRole("button", { name: "确认" })).not.toBeNull());
  1081. fireEvent.click(screen.getByRole("button", { name: "确认" }));
  1082. expect(installPlugin).toHaveBeenCalledOnce();
  1083. expect(screen.getByText("正在安装插件…")).not.toBeNull();
  1084. await act(async () => {
  1085. vi.advanceTimersByTime(9_999);
  1086. await Promise.resolve();
  1087. });
  1088. expect(cancelPluginOperation).not.toHaveBeenCalled();
  1089. expect(screen.queryByRole("button", { name: "确认" })).toBeNull();
  1090. await act(async () => {
  1091. vi.advanceTimersByTime(1);
  1092. await Promise.resolve();
  1093. await Promise.resolve();
  1094. await Promise.resolve();
  1095. });
  1096. expect(cancelPluginOperation).toHaveBeenCalledWith({ operationId: expect.any(String) });
  1097. expect(screen.getByRole("button", { name: "确认" })).not.toBeNull();
  1098. expect(
  1099. document.querySelector('[data-draft-suggested-plugin-popover="confirmation"]'),
  1100. ).not.toBeNull();
  1101. expect(document.querySelector('[data-draft-suggested-plugin-popover="error"]')).toBeNull();
  1102. expect(toast).toHaveBeenCalledWith("文档技能 安装失败:安装超时", {
  1103. variant: "warning",
  1104. });
  1105. expect(loggerWarn).toHaveBeenCalledWith(
  1106. "[v4-suggested-prompts] 推荐插件安装失败,恢复确认态以便重试",
  1107. expect.objectContaining({
  1108. error: "安装超时",
  1109. operationId: expect.any(String),
  1110. pluginId: "document-skills@zcode-plugins-official",
  1111. workspaceKey: workspacePath,
  1112. }),
  1113. );
  1114. expect(
  1115. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  1116. ).toBeNull();
  1117. await act(async () => {
  1118. settleLateInstall({
  1119. dependencyClosure: ["document-skills@zcode-plugins-official"],
  1120. installedPlugins: [
  1121. {
  1122. id: "document-skills@zcode-plugins-official",
  1123. name: "document-skills",
  1124. marketplace: "zcode-plugins-official",
  1125. enabled: true,
  1126. scope: "user",
  1127. },
  1128. ],
  1129. diagnostics: [],
  1130. });
  1131. await Promise.resolve();
  1132. await Promise.resolve();
  1133. });
  1134. expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce();
  1135. expect(
  1136. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  1137. ).toBeNull();
  1138. expect(screen.queryByText("安装成功")).toBeNull();
  1139. expect(screen.getByRole("button", { name: "确认" })).not.toBeNull();
  1140. } finally {
  1141. vi.useRealTimers();
  1142. }
  1143. });
  1144. it("keeps the pure prompt and does not offer installation when refresh fails closed", async () => {
  1145. const workspacePath = "/tmp/suggested-prompt-refresh-failed";
  1146. resolveSuggestedPluginReference.mockResolvedValue({
  1147. stableId: "document-skills@zcode-plugins-official",
  1148. status: "unavailable",
  1149. diagnostics: [
  1150. {
  1151. code: "marketplace_refresh_failed",
  1152. message: "offline",
  1153. severity: "error",
  1154. },
  1155. ],
  1156. });
  1157. render(
  1158. createElement(ConversationDraftSuggestedPromptsContainer, {
  1159. workspacePath,
  1160. isWebRemoteControl: true,
  1161. }),
  1162. );
  1163. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  1164. await waitFor(() => expect(resolveSuggestedPluginReference).toHaveBeenCalledOnce());
  1165. expect(
  1166. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  1167. ).toEqual({ requestId: 1, text: pluginPrompt });
  1168. expect(toast).not.toHaveBeenCalled();
  1169. expect(resolveSuggestedPluginReference).toHaveBeenCalledWith(
  1170. expect.objectContaining({
  1171. clientMode: "web-remote-replayable",
  1172. deliveryKind: "web-remote-replayable",
  1173. }),
  1174. );
  1175. });
  1176. it("cancels the older operation, disables recommendations until cancellation settles, and drops late results", async () => {
  1177. const workspacePath = "/tmp/suggested-prompt-cancel";
  1178. let resolveOld!: (value: Record<string, unknown>) => void;
  1179. let resolveCancel!: (value: Record<string, unknown>) => void;
  1180. resolveSuggestedPluginReference.mockResolvedValue({
  1181. stableId: "document-skills@zcode-plugins-official",
  1182. status: "missing",
  1183. marketplace: "zcode-plugins-official",
  1184. pluginName: "document-skills",
  1185. sourceTrust: "official",
  1186. diagnostics: [],
  1187. });
  1188. installPlugin.mockReturnValue(
  1189. new Promise((resolve) => {
  1190. resolveOld = resolve;
  1191. }),
  1192. );
  1193. cancelPluginOperation.mockReturnValue(
  1194. new Promise((resolve) => {
  1195. resolveCancel = resolve;
  1196. }),
  1197. );
  1198. render(
  1199. createElement(ConversationDraftSuggestedPromptsContainer, {
  1200. workspacePath,
  1201. }),
  1202. );
  1203. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  1204. expect(await applyPendingComposerTextInsert(workspacePath)).toEqual({
  1205. requestId: 1,
  1206. text: pluginPrompt,
  1207. });
  1208. fireEvent.click(await screen.findByRole("button", { name: "确认" }));
  1209. await waitFor(() => expect(installPlugin).toHaveBeenCalledOnce());
  1210. expect(await screen.findByText("正在安装插件…")).not.toBeNull();
  1211. fireEvent.click(
  1212. screen.getByRole("button", {
  1213. name: plainLabel,
  1214. }),
  1215. );
  1216. await waitFor(() =>
  1217. expect(
  1218. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest
  1219. ?.text,
  1220. ).toBe(plainPrompt),
  1221. );
  1222. await waitFor(() => expect(cancelPluginOperation).toHaveBeenCalledOnce());
  1223. expect(screen.queryByText("正在安装插件…")).toBeNull();
  1224. expect((screen.getByRole("button", { name: pluginLabel }) as HTMLButtonElement).disabled).toBe(
  1225. true,
  1226. );
  1227. expect((screen.getByRole("button", { name: plainLabel }) as HTMLButtonElement).disabled).toBe(
  1228. true,
  1229. );
  1230. await act(async () => {
  1231. resolveCancel({ operationId: "old", cancelled: true });
  1232. await Promise.resolve();
  1233. });
  1234. expect((screen.getByRole("button", { name: pluginLabel }) as HTMLButtonElement).disabled).toBe(
  1235. true,
  1236. );
  1237. expect((screen.getByRole("button", { name: plainLabel }) as HTMLButtonElement).disabled).toBe(
  1238. true,
  1239. );
  1240. await act(async () => {
  1241. resolveOld({
  1242. dependencyClosure: ["document-skills@zcode-plugins-official"],
  1243. installedPlugins: [
  1244. {
  1245. id: "document-skills@zcode-plugins-official",
  1246. name: "document-skills",
  1247. marketplace: "zcode-plugins-official",
  1248. enabled: true,
  1249. scope: "user",
  1250. },
  1251. ],
  1252. diagnostics: [],
  1253. });
  1254. await Promise.resolve();
  1255. });
  1256. await waitFor(() =>
  1257. expect(
  1258. (screen.getByRole("button", { name: pluginLabel }) as HTMLButtonElement).disabled,
  1259. ).toBe(false),
  1260. );
  1261. expect(
  1262. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  1263. ).toEqual({
  1264. requestId: 2,
  1265. text: plainPrompt,
  1266. });
  1267. expect(getPluginReferenceCatalog).not.toHaveBeenCalled();
  1268. expect(
  1269. toast.mock.calls.some(
  1270. ([message]) => String(message).includes("取消") || String(message).includes("中断"),
  1271. ),
  1272. ).toBe(false);
  1273. expect(document.querySelector("[data-draft-suggested-plugin-popover]")).toBeNull();
  1274. });
  1275. it("invalidates an older Plugin prefill when a later click navigates to Automations", async () => {
  1276. const workspacePath = "/tmp/suggested-prompt-navigation-latest-wins";
  1277. const onOpenAutomations = vi.fn();
  1278. let resolveCatalog!: (value: { authority: "workspace"; plugins: [] }) => void;
  1279. getPluginReferenceCatalog.mockReturnValue(
  1280. new Promise((resolve) => {
  1281. resolveCatalog = resolve;
  1282. }),
  1283. );
  1284. render(
  1285. createElement(ConversationDraftSuggestedPromptsContainer, {
  1286. workspacePath,
  1287. onOpenAutomations,
  1288. }),
  1289. );
  1290. fireEvent.click(await screen.findByRole("button", { name: pluginLabel }));
  1291. fireEvent.click(screen.getByRole("button", { name: automationsLabel }));
  1292. expect(onOpenAutomations).toHaveBeenCalledOnce();
  1293. await act(async () => {
  1294. resolveCatalog({ authority: "workspace", plugins: [] });
  1295. await Promise.resolve();
  1296. });
  1297. expect(
  1298. useZCodeSessionStore.getState().getWorkspaceState(workspacePath).composerTextInsertRequest,
  1299. ).toBeNull();
  1300. expect(toast).not.toHaveBeenCalled();
  1301. });
  1302. });