offPeakNewTaskEntry.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. // @vitest-environment jsdom
  2. import { createElement } from "react";
  3. import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import { BUILTIN_MODEL_PROVIDER_IDS } from "@zcode/shared";
  6. const h = vi.hoisted(() => {
  7. const initialize = vi.fn(async () => {});
  8. const dismissNewTaskBanner = vi.fn();
  9. const setPendingCreateDraft = vi.fn();
  10. const refreshCodingPlanSupport = vi.fn(async () => {});
  11. const openCodingPlanUpgrade = vi.fn();
  12. const inventory = { status: "ready" as "ready" | "loading" | "error", retry: vi.fn() };
  13. const loggerDebug = vi.fn();
  14. const toast = vi.fn();
  15. const messages: { current: Record<string, string> } = { current: {} };
  16. const locale = { current: "en-US" };
  17. const offPeakTemplateIds = {
  18. current: ["standupGitSummary", "ciFlakyReport", "customize"] as string[],
  19. };
  20. const remoteTemplateCopy = {
  21. standupGitSummary: {
  22. en: {
  23. title: "Remote standup summary",
  24. description: "Remote Friday summary",
  25. prompt: "Summarize the remote standup.",
  26. },
  27. cn: { title: "远程站会摘要", description: "远程周五摘要", prompt: "汇总远程站会。" },
  28. },
  29. ciFlakyReport: {
  30. en: {
  31. title: "Remote CI report",
  32. description: "Remote CI failures",
  33. prompt: "Review the remote CI report.",
  34. },
  35. cn: { title: "远程 CI 报告", description: "远程 CI 失败", prompt: "检查远程 CI 报告。" },
  36. },
  37. documentationSyncCheck: {
  38. en: {
  39. title: "Remote docs check",
  40. description: "Remote documentation sync",
  41. prompt: "Review remote documentation.",
  42. },
  43. cn: { title: "远程文档检查", description: "远程文档同步", prompt: "检查远程文档。" },
  44. },
  45. };
  46. const providerSettingsState = {
  47. view: null as import("@zcode/services").ProviderSettingsView | null,
  48. };
  49. const state = {
  50. loading: false,
  51. grayConfig: {
  52. enabled: true,
  53. modelSelectionView: { revision: 1, providers: [] },
  54. },
  55. codingPlanSupport: {
  56. supported: false,
  57. reason: "connection_unselected",
  58. },
  59. newTaskBannerDismissed: false,
  60. initialize,
  61. refreshCodingPlanSupport,
  62. dismissNewTaskBanner,
  63. setPendingCreateDraft,
  64. };
  65. const settings = {
  66. providerFamilyDomain: undefined as "zai" | "bigmodel" | undefined,
  67. modelProviderFamilyModes: {} as Record<string, "oauth" | "apiKey">,
  68. modelProviderFamilySelectedKeys: {} as Record<string, string>,
  69. };
  70. // 真实 useServices 返回的是稳定的 Context 值;mock 若每次调用都新建对象,
  71. // 组件任何一次重渲染都会让 initialize 的依赖变化并重复拉取灰度配置。
  72. const services = {
  73. offPeakTaskService: {},
  74. codingPlanSubscriptionService: {},
  75. };
  76. return {
  77. initialize,
  78. loggerDebug,
  79. locale,
  80. messages,
  81. offPeakTemplateIds,
  82. providerSettingsState,
  83. openCodingPlanUpgrade,
  84. inventory,
  85. refreshCodingPlanSupport,
  86. services,
  87. setPendingCreateDraft,
  88. settings,
  89. state,
  90. toast,
  91. remoteTemplateCopy,
  92. };
  93. });
  94. vi.mock("@/components/ui/toast.js", () => ({ toast: h.toast }));
  95. vi.mock("@/hooks/useServices.js", () => ({
  96. useServices: () => h.services,
  97. }));
  98. vi.mock("@/hooks/useProviderSettingsView.js", () => ({
  99. useProviderSettingsView: () => ({
  100. state: h.providerSettingsState.view
  101. ? { status: "ready", view: h.providerSettingsState.view }
  102. : { status: "loading" },
  103. reload: vi.fn(),
  104. }),
  105. }));
  106. vi.mock("@/hooks/useSettingService.js", () => ({
  107. useSettings: () => ({ settings: h.settings }),
  108. }));
  109. vi.mock("@/i18n/IntlProvider.js", () => ({
  110. useZCodeIntl: () => ({
  111. locale: h.locale.current,
  112. intl: {
  113. formatMessage: ({ id }: { id: string }) => h.messages.current[id] ?? id,
  114. },
  115. }),
  116. }));
  117. vi.mock("@/settings/useAutomationTemplates.js", () => ({
  118. useAutomationTemplates: () => ({
  119. scheduled: [],
  120. rejectedScheduledTemplateIds: [],
  121. offPeak: h.offPeakTemplateIds.current.map((id) => {
  122. const customize = id === "customize" || id === "item-customize";
  123. const copy = customize
  124. ? null
  125. : h.remoteTemplateCopy[
  126. id as "standupGitSummary" | "ciFlakyReport" | "documentationSyncCheck"
  127. ];
  128. return {
  129. id,
  130. title: copy ? { en: copy.en.title, cn: copy.cn.title } : {},
  131. // Automations 仍展示 contents;首页必须显式读取 homepageDescription(descs 映射结果)。
  132. description: copy
  133. ? { en: `contents:${copy.en.description}`, cn: `contents:${copy.cn.description}` }
  134. : {},
  135. homepageDescription: copy ? { en: copy.en.description, cn: copy.cn.description } : {},
  136. prompt: copy ? { en: copy.en.prompt, cn: copy.cn.prompt } : { en: "", cn: "" },
  137. customize,
  138. icon: customize ? "customize" : id,
  139. ...(customize
  140. ? {}
  141. : {
  142. iconName:
  143. id === "standupGitSummary"
  144. ? "git-commit-horizontal"
  145. : id === "ciFlakyReport"
  146. ? "activity"
  147. : "file-text",
  148. }),
  149. };
  150. }),
  151. }),
  152. }));
  153. vi.mock("@/logger.js", () => ({
  154. logger: { debug: h.loggerDebug },
  155. }));
  156. vi.mock("@/settings/CodingPlanUpgradeDialogProvider.js", () => ({
  157. useOptionalCodingPlanUpgradeDialog: () => ({
  158. openCodingPlanUpgrade: h.openCodingPlanUpgrade,
  159. inventory: h.inventory,
  160. }),
  161. }));
  162. vi.mock("@/store/offPeakTaskStore.js", async (importOriginal) => {
  163. const actual = await importOriginal<typeof import("@/store/offPeakTaskStore.js")>();
  164. return {
  165. ...actual,
  166. useOffPeakTaskStore: (selector: (state: typeof h.state) => unknown) => selector(h.state),
  167. };
  168. });
  169. import { OffPeakNewTaskEntry } from "@/v4/OffPeakNewTaskEntry.js";
  170. import enUS from "@/i18n/locales/en-US.js";
  171. import zhCN from "@/i18n/locales/zh-CN.js";
  172. function renderEntry(props: { onOpenAutomations?: () => void } = {}) {
  173. return render(createElement(OffPeakNewTaskEntry, props));
  174. }
  175. function clickStandupTemplate(onOpenAutomations = vi.fn()) {
  176. renderEntry({ onOpenAutomations });
  177. fireEvent.click(
  178. screen.getByRole("button", {
  179. name: /Remote standup summary Remote Friday summary/,
  180. }),
  181. );
  182. return onOpenAutomations;
  183. }
  184. beforeEach(() => {
  185. vi.clearAllMocks();
  186. h.inventory.status = "ready";
  187. h.state.loading = false;
  188. h.state.grayConfig = {
  189. enabled: true,
  190. modelSelectionView: { revision: 1, providers: [] },
  191. };
  192. h.state.codingPlanSupport = {
  193. supported: false,
  194. reason: "connection_unselected",
  195. };
  196. h.providerSettingsState.view = {
  197. revision: 1,
  198. addableProviders: [],
  199. providerOrder: [],
  200. providers: [],
  201. };
  202. h.messages.current = {};
  203. h.locale.current = "en-US";
  204. h.offPeakTemplateIds.current = ["standupGitSummary", "ciFlakyReport", "customize"];
  205. h.settings.providerFamilyDomain = undefined;
  206. h.settings.modelProviderFamilyModes = {};
  207. h.settings.modelProviderFamilySelectedKeys = {};
  208. });
  209. afterEach(() => {
  210. cleanup();
  211. vi.restoreAllMocks();
  212. });
  213. describe("OffPeakNewTaskEntry", () => {
  214. it.each(["loading", "error"] as const)(
  215. "purchase inventory %s does not enter purchase from the blocked template",
  216. (status) => {
  217. h.inventory.status = status;
  218. const onOpenAutomations = clickStandupTemplate();
  219. const options = h.toast.mock.calls[0]?.[1];
  220. expect(h.setPendingCreateDraft).not.toHaveBeenCalled();
  221. expect(onOpenAutomations).not.toHaveBeenCalled();
  222. if (status === "loading") {
  223. expect(options?.actionLabel).toBeUndefined();
  224. } else {
  225. expect(options?.actionLabel).toBe("purchase.entry.retry");
  226. options?.onAction?.();
  227. expect(h.inventory.retry).toHaveBeenCalledOnce();
  228. }
  229. expect(h.openCodingPlanUpgrade).not.toHaveBeenCalled();
  230. },
  231. );
  232. it("远程目录为空时显示本地 Customize 入口", () => {
  233. h.offPeakTemplateIds.current = [];
  234. renderEntry();
  235. expect(screen.getByRole("button", { name: /Customize/i })).not.toBeNull();
  236. });
  237. it("首页只展示前两条普通远程模板,并把本地 Customize 固定放在最后", () => {
  238. h.offPeakTemplateIds.current = [
  239. "standupGitSummary",
  240. "item-customize",
  241. "ciFlakyReport",
  242. "documentationSyncCheck",
  243. ];
  244. const view = renderEntry();
  245. const cards = view.container.querySelectorAll<HTMLElement>(
  246. "[data-off-peak-template-grid] > button",
  247. );
  248. expect(cards).toHaveLength(3);
  249. expect(Array.from(cards, (card) => card.textContent)).toEqual([
  250. "Remote standup summaryRemote Friday summary",
  251. "Remote CI reportRemote CI failures",
  252. "offPeak.newTask.template.customize.titleoffPeak.newTask.template.customize.description",
  253. ]);
  254. expect(view.container.textContent).not.toContain("Remote docs check");
  255. });
  256. it("远端模板图标和本地 Customize 图标接线", async () => {
  257. const view = renderEntry();
  258. const templateGrid = view.container.querySelector<HTMLElement>("[data-off-peak-template-grid]");
  259. const cards = templateGrid?.querySelectorAll<HTMLElement>("button") ?? [];
  260. expect(cards).toHaveLength(3);
  261. await waitFor(() => {
  262. expect(
  263. cards[0]?.querySelector('[data-client-scene-lucide-icon="git-commit-horizontal"]'),
  264. ).not.toBeNull();
  265. expect(cards[1]?.querySelector('[data-client-scene-lucide-icon="activity"]')).not.toBeNull();
  266. });
  267. expect(cards[2]?.querySelector('[data-off-peak-homepage-template-icon="moon"]')).not.toBeNull();
  268. });
  269. it("keeps the dismiss control implemented but hidden in this design round", () => {
  270. const view = renderEntry();
  271. const closeButton = view.container.querySelector<HTMLElement>(
  272. "[data-off-peak-new-task-dismiss]",
  273. );
  274. expect(closeButton).not.toBeNull();
  275. expect(closeButton?.classList.contains("hidden")).toBe(true);
  276. });
  277. it("横幅文案可聚焦并承接 Tooltip", () => {
  278. renderEntry();
  279. const copy = screen.getByText("offPeak.newTask.bannerText");
  280. expect(copy.getAttribute("data-slot")).toBe("tooltip-trigger");
  281. expect(copy.tabIndex).toBe(0);
  282. });
  283. it("首次挂载交由共享机制初始化和登记 freshness,连接变化后刷新", () => {
  284. const view = renderEntry();
  285. expect(h.initialize).toHaveBeenCalledOnce();
  286. // 去重归 Store 所有;这里验证组件交付通知,不再要求它自行跳过首次通知。
  287. expect(h.refreshCodingPlanSupport).toHaveBeenCalledOnce();
  288. view.rerender(createElement(OffPeakNewTaskEntry));
  289. expect(h.refreshCodingPlanSupport).toHaveBeenCalledOnce();
  290. h.settings.providerFamilyDomain = "zai";
  291. h.settings.modelProviderFamilyModes = { zai: "oauth" };
  292. h.settings.modelProviderFamilySelectedKeys = { zai: "zai-coding-plan" };
  293. view.rerender(createElement(OffPeakNewTaskEntry));
  294. expect(h.refreshCodingPlanSupport).toHaveBeenCalledTimes(2);
  295. });
  296. it("非 Coding Plan 用户点击模板时直接弹升级 toast,并拦截草稿与导航", () => {
  297. vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue("idle-funnel-home");
  298. h.messages.current["settings.modelProvider.codingPlan.upgrade"] = "升级";
  299. const onOpenAutomations = clickStandupTemplate();
  300. expect(h.toast).toHaveBeenCalledWith("offPeak.create.codingPlanToast", {
  301. durationMs: 8000,
  302. position: "top-center",
  303. variant: "info",
  304. actionLabel: "升级",
  305. onAction: expect.any(Function),
  306. dismissible: true,
  307. dismissLabel: "common.close",
  308. });
  309. expect(h.setPendingCreateDraft).not.toHaveBeenCalled();
  310. expect(onOpenAutomations).not.toHaveBeenCalled();
  311. expect(h.loggerDebug).toHaveBeenCalledWith(
  312. "[off-peak] blocked home template without any Coding Plan",
  313. { templateId: "standupGitSummary" },
  314. );
  315. const toastOptions = h.toast.mock.calls[0]?.[1];
  316. toastOptions?.onAction?.();
  317. expect(h.openCodingPlanUpgrade).toHaveBeenCalledWith({
  318. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  319. initialAudience: "personal",
  320. funnelContext: {
  321. purchaseFunnelId: "idle-funnel-home",
  322. upgradeSource: "session_idle_time",
  323. eventRegion: "app.session",
  324. eventText: "升级",
  325. entryPlanStatus: "no_plan",
  326. entryPlanLevel: "",
  327. entryPlanList: "",
  328. purchaseAudience: "personal",
  329. providerFamily: "zai",
  330. channel: "Z_AI",
  331. },
  332. });
  333. });
  334. it("Account Overlay 确认 Coding Plan 可用时放行闲时任务导航", () => {
  335. h.providerSettingsState.view = {
  336. revision: 2,
  337. addableProviders: [],
  338. providerOrder: [],
  339. providers: [
  340. {
  341. providerId: BUILTIN_MODEL_PROVIDER_IDS.bigmodelIndividualCodingPlan,
  342. enabled: true,
  343. executable: true,
  344. effectiveConfig: {
  345. label: "BigModel Coding Plan",
  346. access: {
  347. type: "zhipu-account",
  348. family: "bigmodel",
  349. mode: "individual-coding-plan",
  350. entitled: true,
  351. },
  352. api: {
  353. type: "anthropic-messages",
  354. baseUrl: "https://example.com",
  355. },
  356. builtinModelIds: ["glm-5"],
  357. enabled: true,
  358. },
  359. issues: [],
  360. models: [],
  361. },
  362. ],
  363. };
  364. const onOpenAutomations = clickStandupTemplate();
  365. expect(h.toast).not.toHaveBeenCalled();
  366. expect(h.setPendingCreateDraft).toHaveBeenCalledOnce();
  367. expect(onOpenAutomations).toHaveBeenCalledOnce();
  368. });
  369. it("Provider Settings 尚未水合时不把未知状态误判为无套餐", () => {
  370. h.providerSettingsState.view = null;
  371. const onOpenAutomations = clickStandupTemplate();
  372. expect(h.toast).not.toHaveBeenCalled();
  373. expect(h.setPendingCreateDraft).toHaveBeenCalledOnce();
  374. expect(onOpenAutomations).toHaveBeenCalledOnce();
  375. });
  376. it("uses the visible English Upgrade copy as the idle-time event text", () => {
  377. vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue("idle-funnel-en");
  378. h.messages.current["settings.modelProvider.codingPlan.upgrade"] = "Upgrade";
  379. clickStandupTemplate();
  380. const toastOptions = h.toast.mock.calls[0]?.[1];
  381. toastOptions?.onAction?.();
  382. expect(h.openCodingPlanUpgrade.mock.calls[0]?.[0]?.funnelContext?.eventText).toBe("Upgrade");
  383. });
  384. it.each([
  385. {
  386. locale: "zh-CN",
  387. messages: zhCN,
  388. bannerText: "订阅用户新功能体验:创建“闲时任务”,我们将免费在算力富余时段为你完成指派任务。",
  389. bannerTipText: "本功能不消耗订阅用户套餐额度、本功能仅面向订阅用户开放",
  390. },
  391. {
  392. locale: "en-US",
  393. messages: enUS,
  394. bannerText:
  395. 'New feature for subscribers: Create "Idle-time task" , We will complete your assigned task for free during periods of surplus computing power.',
  396. bannerTipText:
  397. "This feature does not consume your subscription plan quota and is available exclusively to subscribers.",
  398. },
  399. ])(
  400. "$locale 首页展示、提示与模板预填使用同一种语言",
  401. ({ locale, messages, bannerText, bannerTipText }) => {
  402. h.messages.current = messages;
  403. h.locale.current = locale;
  404. h.providerSettingsState.view = {
  405. revision: 2,
  406. addableProviders: [],
  407. providerOrder: [],
  408. providers: [
  409. {
  410. providerId: BUILTIN_MODEL_PROVIDER_IDS.zaiIndividualCodingPlan,
  411. enabled: true,
  412. executable: true,
  413. effectiveConfig: {
  414. label: "Z.ai Coding Plan",
  415. access: {
  416. type: "zhipu-account",
  417. family: "zai",
  418. mode: "individual-coding-plan",
  419. entitled: true,
  420. },
  421. api: {
  422. type: "anthropic-messages",
  423. baseUrl: "https://example.com",
  424. },
  425. builtinModelIds: ["glm-5"],
  426. },
  427. issues: [],
  428. models: [],
  429. },
  430. ],
  431. };
  432. const copy = h.remoteTemplateCopy.standupGitSummary[locale === "zh-CN" ? "cn" : "en"];
  433. const { title, description, prompt } = copy;
  434. const onOpenAutomations = vi.fn();
  435. render(createElement(OffPeakNewTaskEntry, { onOpenAutomations }));
  436. const bannerCopy = screen.getByText(bannerText);
  437. fireEvent.focus(bannerCopy);
  438. const tipCopies = screen.getAllByText(bannerTipText);
  439. expect(tipCopies.length).toBeGreaterThan(0);
  440. const templateCard = screen.getByRole("button", {
  441. name: `${title} ${description}`,
  442. });
  443. fireEvent.click(templateCard);
  444. expect(h.toast).not.toHaveBeenCalled();
  445. expect(h.setPendingCreateDraft).toHaveBeenCalledWith({
  446. title,
  447. prompt,
  448. telemetrySource: {
  449. eventRegion: "app.session",
  450. templateId: "standupGitSummary",
  451. },
  452. });
  453. expect(onOpenAutomations).toHaveBeenCalledOnce();
  454. },
  455. );
  456. });