updateStatusButton.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. import { describe, expect, it } from "vitest";
  2. import { createElement, isValidElement } from "react";
  3. import { renderToStaticMarkup } from "react-dom/server";
  4. import { UpdateStatusButton } from "@/UpdateStatusButton.js";
  5. import { UpdateStatusDialog } from "@/UpdateStatusDialog.js";
  6. import {
  7. deriveUpdateStatusViewModel,
  8. isUpdateActionCompleted,
  9. type UpdateStatusDialogPhase,
  10. } from "@/updateStatusModel.js";
  11. import { formatUpdateReleaseDate, getLocalizedUpdateReleaseNotes } from "@/updateReleaseNotes.js";
  12. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  13. import type { IntlInstance } from "@/i18n/IntlProvider.js";
  14. import { TooltipProvider } from "@/components/ui/tooltip.js";
  15. import { PlatformProvider } from "@/hooks/usePlatform.js";
  16. import { ServiceProvider } from "@/hooks/useServices.js";
  17. import type { IServiceAccessor } from "@zcode/services";
  18. import type { IPlatformService, UpdateStatePayload } from "@zcode/shared";
  19. const noopPlatform = {
  20. openExternal: () => undefined,
  21. downloadUpdate: async () => undefined,
  22. cancelUpdateDownload: async () => undefined,
  23. getAutoUpdatePreferences: async () => ({
  24. autoDownloadAndInstallUpdates: false,
  25. }),
  26. setAutoDownloadAndInstallUpdates: async () => undefined,
  27. skipUpdateVersion: async () => undefined,
  28. quitAndInstallUpdate: async () => undefined,
  29. } as unknown as IPlatformService;
  30. const noopServices = {
  31. settingService: {
  32. get: async () => ({}),
  33. update: async () => undefined,
  34. },
  35. } as unknown as IServiceAccessor;
  36. function renderUpdateStatusButton(
  37. updateState: UpdateStatePayload | null,
  38. version: string | null = null,
  39. ) {
  40. return renderToStaticMarkup(
  41. createElement(
  42. TooltipProvider,
  43. null,
  44. createElement(
  45. ServiceProvider,
  46. { services: noopServices },
  47. createElement(
  48. PlatformProvider,
  49. { platform: noopPlatform },
  50. createElement(
  51. ZCodeIntlProvider,
  52. { initialLocale: "zh-CN" },
  53. createElement(UpdateStatusButton, {
  54. platform: noopPlatform,
  55. version,
  56. updateState,
  57. }),
  58. ),
  59. ),
  60. ),
  61. ),
  62. );
  63. }
  64. const testIntl: IntlInstance = {
  65. formatMessage({ id }, values) {
  66. if (values?.version) {
  67. return `更新 ${values.version}`;
  68. }
  69. return id;
  70. },
  71. };
  72. function updateStatusDialogElementContainsText(
  73. phase: UpdateStatusDialogPhase,
  74. text: string,
  75. isUpdateActionPending = false,
  76. ) {
  77. return elementContainsText(renderUpdateStatusDialogElement(phase, isUpdateActionPending), text);
  78. }
  79. function updateStatusDialogElementContainsPropText(
  80. phase: UpdateStatusDialogPhase,
  81. text: string,
  82. edgeToEdge = false,
  83. ) {
  84. return elementContainsPropText(
  85. renderUpdateStatusDialogElement(phase, false, null, edgeToEdge),
  86. text,
  87. );
  88. }
  89. function updateStatusDialogElementContainsMatchingPropText(
  90. phase: UpdateStatusDialogPhase,
  91. matcher: (className: string) => boolean,
  92. edgeToEdge = false,
  93. ) {
  94. return elementContainsMatchingElement(
  95. renderUpdateStatusDialogElement(phase, false, null, edgeToEdge),
  96. (_type, props) => typeof props.className === "string" && matcher(props.className),
  97. );
  98. }
  99. function updateStatusDialogUsesStackedReleaseDate(phase: UpdateStatusDialogPhase) {
  100. return elementContainsMatchingElement(
  101. renderUpdateStatusDialogElement(phase, false, "2026-07-09"),
  102. (type, props) =>
  103. type === "div" &&
  104. typeof props.className === "string" &&
  105. props.className.includes("inline-flex") &&
  106. props.className.includes("max-w-full") &&
  107. !props.className.includes("ml-auto") &&
  108. !props.className.includes("text-right") &&
  109. elementContainsText(props.children, "2026-07-09"),
  110. );
  111. }
  112. function updateStatusDialogUsesCenteredLogoTitleLayout(phase: UpdateStatusDialogPhase) {
  113. return elementContainsMatchingElement(
  114. renderUpdateStatusDialogElement(phase, false, "2026-07-09"),
  115. (type, props) =>
  116. type === "div" &&
  117. typeof props.className === "string" &&
  118. props.className.includes("flex") &&
  119. props.className.includes("items-center") &&
  120. elementContainsMatchingElement(
  121. props.children,
  122. (childType, childProps) =>
  123. childType === "img" &&
  124. typeof childProps.className === "string" &&
  125. childProps.className.includes("size-12"),
  126. ) &&
  127. elementContainsText(props.children, "2026-07-09"),
  128. );
  129. }
  130. function updateStatusDialogUsesMacDockProductLogo(phase: UpdateStatusDialogPhase) {
  131. return elementContainsMatchingElement(
  132. renderUpdateStatusDialogElement(phase),
  133. (type, props) =>
  134. type === "img" &&
  135. typeof props.src === "string" &&
  136. props.src.includes("icon_512@2x.png") &&
  137. props.alt === "" &&
  138. props.draggable === false &&
  139. typeof props.className === "string" &&
  140. props.className.includes("size-12") &&
  141. props.className.includes("-ml-[5px]") &&
  142. props.className.includes("shadow-none") &&
  143. props.className.includes("drop-shadow-none"),
  144. );
  145. }
  146. function countUpdateStatusDialogBooleanProp(
  147. phase: UpdateStatusDialogPhase,
  148. propName: string,
  149. isUpdateActionPending = false,
  150. edgeToEdge = false,
  151. ) {
  152. return countElementBooleanProp(
  153. renderUpdateStatusDialogElement(phase, isUpdateActionPending, null, edgeToEdge),
  154. propName,
  155. );
  156. }
  157. function renderUpdateStatusDialogElement(
  158. phase: UpdateStatusDialogPhase,
  159. isUpdateActionPending = false,
  160. releaseDateLabel: string | null = null,
  161. edgeToEdge = false,
  162. ) {
  163. return UpdateStatusDialog({
  164. autoDownloadAndInstallUpdates: false,
  165. displayVersion: "3.3.3",
  166. edgeToEdge,
  167. intl: testIntl,
  168. isUpdateActionPending,
  169. localizedUpdateReleaseNotes: {
  170. markdown: "Visible before downloading",
  171. title: "Release v3.3.3",
  172. },
  173. onAutoDownloadAndInstallUpdatesChange: async () => undefined,
  174. onCancelDownload: async () => undefined,
  175. onDownloadUpdate: async () => undefined,
  176. onOpenChange: () => undefined,
  177. onOpenReleaseNotesExternalUrl: () => undefined,
  178. onRestartUpdate: async () => undefined,
  179. onSkipUpdate: async () => undefined,
  180. open: true,
  181. phase,
  182. progressLabel: "4.2MB / 10.0MB",
  183. progressValue: 42,
  184. releaseDateLabel,
  185. skippableVersion: phase === "downloaded" ? null : "3.3.3",
  186. });
  187. }
  188. function elementContainsText(node: unknown, text: string): boolean {
  189. if (node == null || typeof node === "boolean") {
  190. return false;
  191. }
  192. if (typeof node === "string" || typeof node === "number") {
  193. return String(node).includes(text);
  194. }
  195. if (Array.isArray(node)) {
  196. return node.some((child) => elementContainsText(child, text));
  197. }
  198. if (isValidElement(node)) {
  199. const props = node.props as { children?: unknown };
  200. return elementContainsText(props.children, text);
  201. }
  202. return false;
  203. }
  204. function countElementBooleanProp(node: unknown, propName: string): number {
  205. if (node == null || typeof node === "boolean") {
  206. return 0;
  207. }
  208. if (Array.isArray(node)) {
  209. return node.reduce((count, child) => count + countElementBooleanProp(child, propName), 0);
  210. }
  211. if (isValidElement(node)) {
  212. const props = node.props as Record<string, unknown>;
  213. const selfCount = props[propName] === true ? 1 : 0;
  214. return selfCount + countElementBooleanProp(props.children, propName);
  215. }
  216. return 0;
  217. }
  218. function elementContainsPropText(node: unknown, text: string): boolean {
  219. if (node == null || typeof node === "boolean") {
  220. return false;
  221. }
  222. if (Array.isArray(node)) {
  223. return node.some((child) => elementContainsPropText(child, text));
  224. }
  225. if (isValidElement(node)) {
  226. const props = node.props as Record<string, unknown>;
  227. const hasMatchingStringProp = Object.entries(props).some(
  228. ([key, value]) => key !== "children" && typeof value === "string" && value.includes(text),
  229. );
  230. return hasMatchingStringProp || elementContainsPropText(props.children, text);
  231. }
  232. return false;
  233. }
  234. function elementContainsMatchingElement(
  235. node: unknown,
  236. predicate: (type: unknown, props: Record<string, unknown>) => boolean,
  237. ): boolean {
  238. if (node == null || typeof node === "boolean") {
  239. return false;
  240. }
  241. if (Array.isArray(node)) {
  242. return node.some((child) => elementContainsMatchingElement(child, predicate));
  243. }
  244. if (isValidElement(node)) {
  245. const props = node.props as Record<string, unknown>;
  246. return predicate(node.type, props) || elementContainsMatchingElement(props.children, predicate);
  247. }
  248. return false;
  249. }
  250. describe("UpdateStatusButton release notes", () => {
  251. it("selects release notes by current locale", () => {
  252. const payload = {
  253. version: "3.1.3",
  254. title: "Release v3.1.3",
  255. markdown: "- 默认说明",
  256. releaseNotesByLocale: {
  257. "zh-CN": {
  258. title: "ZCode v3.1.3",
  259. markdown: "- 中文说明",
  260. },
  261. "en-US": {
  262. title: "ZCode v3.1.3",
  263. markdown: "- English notes",
  264. },
  265. },
  266. };
  267. expect(getLocalizedUpdateReleaseNotes(payload, "en-US")).toEqual({
  268. title: "ZCode v3.1.3",
  269. markdown: "- English notes",
  270. });
  271. expect(getLocalizedUpdateReleaseNotes(payload, "zh-CN")).toEqual({
  272. title: "ZCode v3.1.3",
  273. markdown: "- 中文说明",
  274. });
  275. });
  276. it("falls back to default release notes for legacy update feeds", () => {
  277. expect(
  278. getLocalizedUpdateReleaseNotes(
  279. {
  280. version: "3.1.3",
  281. title: "Release v3.1.3",
  282. markdown: "- default notes",
  283. },
  284. "en-US",
  285. ),
  286. ).toEqual({
  287. title: "Release v3.1.3",
  288. markdown: "- default notes",
  289. });
  290. });
  291. it("keeps default release notes for zh-CN when only an english sibling exists", () => {
  292. expect(
  293. getLocalizedUpdateReleaseNotes(
  294. {
  295. version: "3.1.4",
  296. title: "Release v3.1.4",
  297. markdown: "- 中文说明",
  298. releaseNotesByLocale: {
  299. "en-US": {
  300. title: "Release v3.1.4",
  301. markdown: "- English notes",
  302. },
  303. },
  304. },
  305. "zh-CN",
  306. ),
  307. ).toEqual({
  308. title: "Release v3.1.4",
  309. markdown: "- 中文说明",
  310. });
  311. });
  312. it("formats release dates by locale", () => {
  313. expect(formatUpdateReleaseDate("2026-06-23T13:48:54.438Z", "en-US")).toBe("June 23, 2026");
  314. expect(formatUpdateReleaseDate("2026-06-23T13:48:54.438Z", "zh-CN")).toBe("2026年6月23日");
  315. });
  316. it("formats UTC midnight release dates without shifting to local previous day", () => {
  317. expect(formatUpdateReleaseDate("2026-04-15T00:00:00.000Z", "en-US")).toBe("April 15, 2026");
  318. });
  319. it("shows the auto download checkbox before downloading", () => {
  320. expect(
  321. updateStatusDialogElementContainsText(
  322. "before-download",
  323. "updateDialog.autoDownloadAndInstall",
  324. ),
  325. ).toBe(true);
  326. expect(
  327. updateStatusDialogElementContainsText("downloading", "updateDialog.autoDownloadAndInstall"),
  328. ).toBe(false);
  329. });
  330. it("omits release notes from the update dialog", () => {
  331. expect(
  332. updateStatusDialogElementContainsText("before-download", "Visible before downloading"),
  333. ).toBe(false);
  334. expect(updateStatusDialogElementContainsText("downloading", "Visible before downloading")).toBe(
  335. false,
  336. );
  337. expect(updateStatusDialogElementContainsText("downloaded", "Visible before downloading")).toBe(
  338. false,
  339. );
  340. });
  341. it.each<UpdateStatusDialogPhase>(["before-download", "downloading", "downloaded"])(
  342. "shows the macOS Dock product logo in the %s title",
  343. (phase) => {
  344. expect(updateStatusDialogUsesMacDockProductLogo(phase)).toBe(true);
  345. expect(updateStatusDialogElementContainsPropText(phase, "scale-105")).toBe(false);
  346. expect(updateStatusDialogElementContainsPropText(phase, "rounded-xl")).toBe(false);
  347. },
  348. );
  349. it.each<UpdateStatusDialogPhase>(["before-download", "downloading", "downloaded"])(
  350. "centers the %s title metadata beside the logo",
  351. (phase) => {
  352. expect(updateStatusDialogUsesStackedReleaseDate(phase)).toBe(true);
  353. expect(updateStatusDialogUsesCenteredLogoTitleLayout(phase)).toBe(true);
  354. },
  355. );
  356. it("shows download size text", () => {
  357. expect(updateStatusDialogElementContainsText("downloading", "4.2MB / 10.0MB")).toBe(true);
  358. });
  359. it("hides skip and later actions while downloading", () => {
  360. expect(updateStatusDialogElementContainsText("downloading", "updateDialog.skipVersion")).toBe(
  361. false,
  362. );
  363. expect(updateStatusDialogElementContainsText("downloading", "updateDialog.later")).toBe(false);
  364. expect(
  365. updateStatusDialogElementContainsText("downloading", "updateDialog.cancelDownload"),
  366. ).toBe(true);
  367. });
  368. it("shows later and restart actions after download finishes", () => {
  369. expect(updateStatusDialogElementContainsText("downloaded", "updateDialog.skipVersion")).toBe(
  370. false,
  371. );
  372. expect(updateStatusDialogElementContainsText("downloaded", "updateDialog.later")).toBe(true);
  373. expect(
  374. updateStatusDialogElementContainsText("downloaded", "updateDialog.restartToUpdate"),
  375. ).toBe(true);
  376. });
  377. it("disables visible update actions while a command is in flight", () => {
  378. expect(countUpdateStatusDialogBooleanProp("before-download", "disabled", true)).toBe(4);
  379. expect(countUpdateStatusDialogBooleanProp("downloading", "disabled", true)).toBe(1);
  380. expect(countUpdateStatusDialogBooleanProp("downloaded", "disabled", true)).toBe(2);
  381. });
  382. it("can remove the dialog shell for the standalone update window", () => {
  383. expect(updateStatusDialogElementContainsPropText("before-download", "border-0", true)).toBe(
  384. true,
  385. );
  386. expect(updateStatusDialogElementContainsPropText("before-download", "shadow-none", true)).toBe(
  387. true,
  388. );
  389. expect(updateStatusDialogElementContainsPropText("before-download", "max-w-none", true)).toBe(
  390. true,
  391. );
  392. expect(
  393. updateStatusDialogElementContainsPropText("before-download", "data-open:animate-in", true),
  394. ).toBe(false);
  395. });
  396. it("keeps desktop footer action layout in the standalone update window", () => {
  397. expect(
  398. updateStatusDialogElementContainsPropText(
  399. "before-download",
  400. "flex-row items-center gap-3",
  401. true,
  402. ),
  403. ).toBe(true);
  404. expect(
  405. updateStatusDialogElementContainsPropText("before-download", "justify-between", true),
  406. ).toBe(true);
  407. expect(
  408. updateStatusDialogElementContainsPropText(
  409. "before-download",
  410. "w-auto flex-row justify-end",
  411. true,
  412. ),
  413. ).toBe(true);
  414. expect(updateStatusDialogElementContainsPropText("downloading", "justify-end", true)).toBe(
  415. true,
  416. );
  417. });
  418. it("does not reserve an empty content row in the standalone update window before download", () => {
  419. expect(
  420. updateStatusDialogElementContainsPropText("before-download", "grid-rows-[auto_auto]", true),
  421. ).toBe(true);
  422. expect(
  423. updateStatusDialogElementContainsPropText(
  424. "before-download",
  425. "grid-rows-[auto_minmax(0,1fr)_auto]",
  426. true,
  427. ),
  428. ).toBe(false);
  429. expect(
  430. updateStatusDialogElementContainsPropText(
  431. "downloading",
  432. "grid-rows-[auto_minmax(0,1fr)_auto]",
  433. true,
  434. ),
  435. ).toBe(true);
  436. });
  437. it("keeps the standalone update window titlebar area draggable", () => {
  438. expect(
  439. updateStatusDialogElementContainsMatchingPropText(
  440. "before-download",
  441. (className) =>
  442. className.includes("p-5") &&
  443. className.includes("pt-10") &&
  444. !className.includes("[app-region:no-drag]"),
  445. true,
  446. ),
  447. ).toBe(true);
  448. expect(
  449. updateStatusDialogElementContainsMatchingPropText(
  450. "before-download",
  451. (className) =>
  452. className.includes("items-center") && className.includes("[app-region:no-drag]"),
  453. true,
  454. ),
  455. ).toBe(true);
  456. });
  457. it("keeps the main update entry visible and interactive across update phases", () => {
  458. const availableHtml = renderUpdateStatusButton({
  459. kind: "update-available",
  460. version: "3.3.3",
  461. channel: "stable",
  462. } as UpdateStatePayload);
  463. const downloadingHtml = renderUpdateStatusButton({
  464. kind: "download-progress",
  465. version: "3.3.3",
  466. progress: "42",
  467. channel: "stable",
  468. } as UpdateStatePayload);
  469. const downloadedHtml = renderUpdateStatusButton({
  470. kind: "update-downloaded",
  471. version: "3.3.3",
  472. channel: "stable",
  473. } as UpdateStatePayload);
  474. expect(availableHtml).toContain("bg-success");
  475. expect(availableHtml).toContain("topoverlayer:w-auto");
  476. expect(downloadingHtml).toContain("bg-success");
  477. expect(downloadingHtml).toContain("animate-spin");
  478. expect(downloadingHtml).not.toContain('disabled=""');
  479. expect(downloadingHtml).not.toContain("下载中");
  480. expect(downloadingHtml).not.toContain("topoverlayer:w-auto");
  481. expect(downloadingHtml).not.toContain("topoverlayer:hidden");
  482. expect(downloadedHtml).toContain("bg-success");
  483. expect(downloadedHtml).toContain("topoverlayer:w-auto");
  484. });
  485. it("keeps the downloading entry visible when progress state omits version", () => {
  486. const html = renderUpdateStatusButton({
  487. kind: "download-progress",
  488. progress: "42",
  489. channel: "stable",
  490. } as UpdateStatePayload);
  491. // Bugfix: download-progress.version 是协议可选字段。不能因为某一帧缺少版本号
  492. // 就把更新入口卸载,否则用户打开的下载弹窗会跟着消失。
  493. expect(html).toContain("bg-success");
  494. expect(html).toContain("animate-spin");
  495. expect(html).not.toContain("topoverlayer:w-auto");
  496. });
  497. it("derives downloading dialog model from state kind instead of version", () => {
  498. const model = deriveUpdateStatusViewModel({
  499. legacyReadyVersion: "3.3.2",
  500. updateState: {
  501. kind: "download-progress",
  502. enabled: false,
  503. progress: "42",
  504. transferredBytes: 4.2 * 1024 * 1024,
  505. totalBytes: 10 * 1024 * 1024,
  506. },
  507. });
  508. expect(model.dialogPhase).toBe("downloading");
  509. expect(model.displayVersion).toBe("…");
  510. expect(model.progressLabel).toBe("4.2MB / 10.0MB");
  511. expect(model.progressValue).toBe(42);
  512. expect(model.skippableVersion).toBe(null);
  513. });
  514. it("keeps action completion rules in the update status model", () => {
  515. expect(isUpdateActionCompleted("download", { kind: "checking", enabled: true })).toBe(false);
  516. expect(isUpdateActionCompleted("download", { kind: "idle", enabled: true })).toBe(false);
  517. expect(
  518. isUpdateActionCompleted("download", {
  519. kind: "download-progress",
  520. enabled: false,
  521. progress: "1",
  522. }),
  523. ).toBe(true);
  524. expect(
  525. isUpdateActionCompleted("cancel", {
  526. kind: "download-progress",
  527. enabled: false,
  528. progress: "1",
  529. }),
  530. ).toBe(false);
  531. expect(isUpdateActionCompleted("skip", { kind: "idle", enabled: true })).toBe(true);
  532. });
  533. it("ignores stale legacy ready version after state reports idle", () => {
  534. const html = renderUpdateStatusButton({ kind: "idle", enabled: true }, "3.3.2");
  535. // Bugfix: main 侧 staging error 后会广播 idle,但旧 UpdateReady 缓存仍可能残留。
  536. // UI 此时不能继续展示“重启以更新”,否则点击只会命中一个已失效的安装上下文。
  537. expect(html).not.toContain("bg-success");
  538. expect(html).not.toContain("updateReady.shortTitle");
  539. });
  540. it("keeps legacy ready version when no update state API exists", () => {
  541. const html = renderUpdateStatusButton(null, "3.3.2");
  542. // 平滑迁移:旧包只会发 UpdateReady,不一定有持续状态流。
  543. // 只有新状态明确同步成 idle/error/checking 后,才清掉 legacy ready。
  544. expect(html).toContain("bg-success");
  545. expect(html).toContain("topoverlayer:w-auto");
  546. });
  547. });