useAppChromeStateAutoUpdate.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import { act, createElement } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import type {
  5. DesktopWindowChromeState,
  6. IPlatformService,
  7. UpdateStatePayload,
  8. } from "@zcode/shared";
  9. vi.mock("@/i18n/IntlProvider.js", () => ({
  10. useZCodeIntl: () => ({
  11. intl: {
  12. formatMessage: ({ id }: { id: string }) => id,
  13. },
  14. }),
  15. }));
  16. vi.mock("@/components/ui/toast.js", () => ({
  17. toast: vi.fn(),
  18. }));
  19. vi.mock("@/logger.js", () => ({
  20. logger: {
  21. info: vi.fn(),
  22. warn: vi.fn(),
  23. },
  24. }));
  25. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  26. const element = {
  27. addEventListener: () => {},
  28. appendChild: (child: { parentNode?: unknown }) => {
  29. child.parentNode = element;
  30. return child;
  31. },
  32. childNodes: [] as unknown[],
  33. getAttribute: () => null,
  34. insertBefore: (child: { parentNode?: unknown }) => {
  35. child.parentNode = element;
  36. return child;
  37. },
  38. nodeName: tagName.toUpperCase(),
  39. nodeType: 1,
  40. ownerDocument,
  41. parentNode: null as unknown,
  42. removeAttribute: () => {},
  43. removeChild: (child: { parentNode?: unknown }) => {
  44. child.parentNode = null;
  45. return child;
  46. },
  47. removeEventListener: () => {},
  48. setAttribute: () => {},
  49. style: {},
  50. tagName: tagName.toUpperCase(),
  51. };
  52. return element as unknown as Element;
  53. }
  54. function installMinimalDom() {
  55. const documentMock = {
  56. addEventListener: () => {},
  57. createElement: (tagName: string) =>
  58. createMinimalElement(documentMock as unknown as Document, tagName),
  59. createElementNS: (_namespace: string, tagName: string) =>
  60. createMinimalElement(documentMock as unknown as Document, tagName),
  61. createTextNode: (nodeValue: string) => ({
  62. nodeType: 3,
  63. nodeValue,
  64. ownerDocument: documentMock,
  65. parentNode: null,
  66. }),
  67. nodeType: 9,
  68. removeEventListener: () => {},
  69. } as unknown as Document;
  70. const windowMock = {
  71. addEventListener: () => {},
  72. document: documentMock,
  73. HTMLIFrameElement: function HTMLIFrameElement() {},
  74. HTMLElement: function HTMLElement() {},
  75. Node: function Node() {},
  76. removeEventListener: () => {},
  77. };
  78. Object.defineProperty(globalThis, "document", {
  79. configurable: true,
  80. value: documentMock,
  81. });
  82. Object.defineProperty(globalThis, "window", {
  83. configurable: true,
  84. value: windowMock,
  85. });
  86. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  87. configurable: true,
  88. value: true,
  89. });
  90. return createMinimalElement(documentMock);
  91. }
  92. describe("useAppChromeState auto update state", () => {
  93. afterEach(() => {
  94. delete (globalThis as { document?: unknown }).document;
  95. delete (globalThis as { window?: unknown }).window;
  96. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  97. });
  98. it("clears legacy ready version when update state leaves downloaded", async () => {
  99. const { useAppChromeState } = await import("@/app-shell/useAppChromeState.js");
  100. let readyCallback: ((version: string) => void) | null = null;
  101. let stateCallback: ((payload: UpdateStatePayload) => void) | null = null;
  102. let latestChromeState: { updateReadyVersion: string | null } | null = null;
  103. const platform = {
  104. getUpdateState: vi.fn(async () => ({ kind: "idle", enabled: true })),
  105. onUpdateReady: vi.fn((callback: (version: string) => void) => {
  106. readyCallback = callback;
  107. return () => {};
  108. }),
  109. onUpdateStateChanged: vi.fn((callback: (payload: UpdateStatePayload) => void) => {
  110. stateCallback = callback;
  111. return () => {};
  112. }),
  113. } as unknown as IPlatformService;
  114. const root: Root = createRoot(installMinimalDom());
  115. const Harness = () => {
  116. latestChromeState = useAppChromeState({
  117. isDesktop: false,
  118. isMacDesktop: false,
  119. isWindowsDesktop: false,
  120. platform,
  121. workspaceAbsPath: "/repo/demo",
  122. });
  123. return null;
  124. };
  125. await act(async () => {
  126. root.render(createElement(Harness));
  127. });
  128. await act(async () => {
  129. await Promise.resolve();
  130. });
  131. act(() => {
  132. readyCallback?.("3.3.2");
  133. });
  134. expect(latestChromeState?.updateReadyVersion).toBe("3.3.2");
  135. act(() => {
  136. stateCallback?.({
  137. kind: "update-downloaded",
  138. enabled: true,
  139. version: "3.3.2",
  140. });
  141. });
  142. expect(latestChromeState?.updateReadyVersion).toBe("3.3.2");
  143. act(() => {
  144. stateCallback?.({ kind: "idle", enabled: true });
  145. });
  146. // Bugfix: staging error 会让 main 广播 idle;旧 ready 版本必须同步清掉,
  147. // 否则顶部按钮会继续展示“重启以更新”并触发一个无效安装请求。
  148. expect(latestChromeState?.updateReadyVersion).toBeNull();
  149. act(() => {
  150. root.unmount();
  151. });
  152. });
  153. it("does not let an initial stale snapshot hide a later available update event", async () => {
  154. const { useAppChromeState } = await import("@/app-shell/useAppChromeState.js");
  155. let resolveInitialSnapshot:
  156. | ((payload: UpdateStatePayload) => void)
  157. | null = null;
  158. let stateCallback: ((payload: UpdateStatePayload) => void) | null = null;
  159. let latestChromeState: {
  160. updateReadyVersion: string | null;
  161. updateState: UpdateStatePayload | null;
  162. } | null = null;
  163. const platform = {
  164. getUpdateState: vi.fn(
  165. () =>
  166. new Promise<UpdateStatePayload>((resolve) => {
  167. resolveInitialSnapshot = resolve;
  168. }),
  169. ),
  170. onUpdateStateChanged: vi.fn((callback: (payload: UpdateStatePayload) => void) => {
  171. stateCallback = callback;
  172. return () => {};
  173. }),
  174. } as unknown as IPlatformService;
  175. const root: Root = createRoot(installMinimalDom());
  176. const Harness = () => {
  177. latestChromeState = useAppChromeState({
  178. isDesktop: false,
  179. isMacDesktop: false,
  180. isWindowsDesktop: false,
  181. platform,
  182. workspaceAbsPath: "/repo/demo",
  183. });
  184. return null;
  185. };
  186. await act(async () => {
  187. root.render(createElement(Harness));
  188. });
  189. act(() => {
  190. stateCallback?.({
  191. kind: "update-available",
  192. enabled: true,
  193. version: "3.3.3",
  194. });
  195. });
  196. expect(latestChromeState?.updateState?.kind).toBe("update-available");
  197. await act(async () => {
  198. resolveInitialSnapshot?.({ kind: "idle", enabled: true });
  199. await Promise.resolve();
  200. });
  201. // Bugfix: 初始 getUpdateState 可能晚于状态事件返回旧 idle。
  202. // 旧快照不能覆盖已经收到的 update-available,否则主页更新按钮会消失。
  203. expect(latestChromeState?.updateState?.kind).toBe("update-available");
  204. act(() => {
  205. root.unmount();
  206. });
  207. });
  208. });
  209. describe("useAppChromeState desktop chrome state", () => {
  210. afterEach(() => {
  211. delete (globalThis as { document?: unknown }).document;
  212. delete (globalThis as { window?: unknown }).window;
  213. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  214. });
  215. it.each([
  216. [15, 6],
  217. [26, 12],
  218. ])("loads macOS %i from the platform before resolving radius %i", async (version, radius) => {
  219. const { useAppChromeState } = await import("@/app-shell/useAppChromeState.js");
  220. const { resolveWorkspaceShellPanelRadiusPx } = await import("@/app-shell/workspaceShellWindowChrome.js");
  221. const dispose = vi.fn();
  222. const platform = {
  223. onWindowFullscreenChanged: vi.fn(() => () => {}),
  224. getDesktopWindowChromeState: vi.fn(async () => ({
  225. isMaximized: false,
  226. supportsNativeRoundedCorners: false,
  227. macOSMajorVersion: version,
  228. })),
  229. onDesktopWindowChromeStateChanged: vi.fn(() => dispose),
  230. } as unknown as IPlatformService;
  231. let actualRadius: number | undefined;
  232. const root = createRoot(installMinimalDom());
  233. const Harness = () => {
  234. const { desktopWindowChromeState } = useAppChromeState({
  235. isDesktop: true,
  236. isMacDesktop: true,
  237. platform,
  238. workspaceAbsPath: "/repo/demo",
  239. });
  240. actualRadius = resolveWorkspaceShellPanelRadiusPx({
  241. isMacDesktop: true,
  242. macOSMajorVersion: desktopWindowChromeState?.macOSMajorVersion,
  243. });
  244. return null;
  245. };
  246. try {
  247. await act(async () => root.render(createElement(Harness)));
  248. expect(platform.getDesktopWindowChromeState).toHaveBeenCalledOnce();
  249. expect(actualRadius).toBe(radius);
  250. } finally {
  251. act(() => root.unmount());
  252. }
  253. expect(dispose).toHaveBeenCalledOnce();
  254. });
  255. it("keeps capability unknown when the desktop bridge is unavailable", async () => {
  256. const { useAppChromeState } = await import("@/app-shell/useAppChromeState.js");
  257. let latestState: DesktopWindowChromeState | null | undefined;
  258. const root: Root = createRoot(installMinimalDom());
  259. const Harness = () => {
  260. latestState = useAppChromeState({
  261. isDesktop: true,
  262. isMacDesktop: false,
  263. isWindowsDesktop: true,
  264. platform: {} as IPlatformService,
  265. workspaceAbsPath: "/repo/demo",
  266. }).desktopWindowChromeState;
  267. return null;
  268. };
  269. await act(async () => {
  270. root.render(createElement(Harness));
  271. });
  272. expect(latestState).toBeNull();
  273. act(() => root.unmount());
  274. });
  275. it("does not let the initial query overwrite a newer maximize event", async () => {
  276. const { useAppChromeState } = await import("@/app-shell/useAppChromeState.js");
  277. let resolveInitialState: ((state: DesktopWindowChromeState) => void) | null = null;
  278. let stateCallback: ((state: DesktopWindowChromeState) => void) | null = null;
  279. let latestState: DesktopWindowChromeState | null | undefined;
  280. const platform = {
  281. getDesktopWindowChromeState: vi.fn(
  282. () =>
  283. new Promise<DesktopWindowChromeState>((resolve) => {
  284. resolveInitialState = resolve;
  285. }),
  286. ),
  287. onDesktopWindowChromeStateChanged: vi.fn(
  288. (callback: (state: DesktopWindowChromeState) => void) => {
  289. stateCallback = callback;
  290. return () => {};
  291. },
  292. ),
  293. } as unknown as IPlatformService;
  294. const root: Root = createRoot(installMinimalDom());
  295. const Harness = () => {
  296. latestState = useAppChromeState({
  297. isDesktop: true,
  298. isMacDesktop: false,
  299. isWindowsDesktop: true,
  300. platform,
  301. workspaceAbsPath: "/repo/demo",
  302. }).desktopWindowChromeState;
  303. return null;
  304. };
  305. await act(async () => {
  306. root.render(createElement(Harness));
  307. });
  308. act(() => {
  309. stateCallback?.({ isMaximized: true, supportsNativeRoundedCorners: true });
  310. });
  311. await act(async () => {
  312. resolveInitialState?.({ isMaximized: false, supportsNativeRoundedCorners: true });
  313. await Promise.resolve();
  314. });
  315. expect(latestState).toEqual({ isMaximized: true, supportsNativeRoundedCorners: true });
  316. act(() => root.unmount());
  317. });
  318. });