UpdateStatusDialogController.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import type { IPlatformService, UpdateStatePayload } from "@zcode/shared";
  2. import { useCallback, useEffect, useRef, useState } from "react";
  3. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  4. import { useConfirmDialog } from "@/hooks/useConfirmDialog.js";
  5. import { UpdateStatusDialog } from "@/UpdateStatusDialog.js";
  6. import { formatUpdateReleaseDate, getLocalizedUpdateReleaseNotes } from "@/updateReleaseNotes.js";
  7. import {
  8. deriveUpdateStatusViewModel,
  9. isUpdateActionCompleted,
  10. type UpdateActionInFlight,
  11. type UpdateStatusViewModel,
  12. } from "@/updateStatusModel.js";
  13. export function UpdateStatusDialogController({
  14. platform,
  15. version,
  16. updateState,
  17. open,
  18. onOpenChange,
  19. edgeToEdge = false,
  20. showOverlay = true,
  21. }: {
  22. platform: IPlatformService;
  23. version: string | null;
  24. updateState: UpdateStatePayload | null;
  25. open: boolean;
  26. onOpenChange: (open: boolean) => void;
  27. edgeToEdge?: boolean;
  28. showOverlay?: boolean;
  29. }) {
  30. const { intl, locale } = useZCodeIntl();
  31. const requestConfirmation = useConfirmDialog();
  32. const [autoDownloadAndInstallUpdates, setAutoDownloadAndInstallUpdates] = useState(false);
  33. const [updateActionInFlight, setUpdateActionInFlightState] = useState<UpdateActionInFlight>(null);
  34. const updateActionInFlightRef = useRef<typeof updateActionInFlight>(null);
  35. const releaseNotesCacheRef = useRef(
  36. new Map<
  37. string,
  38. {
  39. releaseDateLabel: string | null;
  40. releaseNotes: { title: string; markdown: string };
  41. }
  42. >(),
  43. );
  44. const setUpdateActionInFlight = useCallback((nextAction: typeof updateActionInFlight) => {
  45. updateActionInFlightRef.current = nextAction;
  46. setUpdateActionInFlightState(nextAction);
  47. }, []);
  48. const updateStatusViewModel = deriveUpdateStatusViewModel({
  49. legacyReadyVersion: version,
  50. updateState,
  51. });
  52. const lastVisibleUpdateStatusViewModelSelection = useRef<UpdateStatusViewModel | null>(null);
  53. const renderedUpdateStatusViewModel =
  54. updateStatusViewModel.displayVersion || updateActionInFlight === null
  55. ? updateStatusViewModel
  56. : (lastVisibleUpdateStatusViewModelSelection.current ?? updateStatusViewModel);
  57. const {
  58. dialogPhase,
  59. displayVersion,
  60. progressLabel,
  61. progressValue,
  62. releaseNotesPayload: updateReleaseNotesPayload,
  63. skippableVersion,
  64. } = renderedUpdateStatusViewModel;
  65. const localizedUpdateReleaseNotes = getLocalizedUpdateReleaseNotes(
  66. updateReleaseNotesPayload,
  67. locale,
  68. );
  69. const formattedReleaseDate = formatUpdateReleaseDate(
  70. updateReleaseNotesPayload?.releaseDate,
  71. locale,
  72. );
  73. const releaseNotesCacheKey = displayVersion ? `${locale}:${displayVersion}` : null;
  74. useEffect(() => {
  75. if (!updateStatusViewModel.displayVersion) {
  76. return;
  77. }
  78. // 点击“下载更新”后,真实下载进度依赖 main 侧异步广播。
  79. // 中间若短暂收到 checking/idle 等不带版本的过渡状态,不能让入口 return null
  80. // 连带卸载已打开的弹窗;命令进行中复用上一帧可见模型,等进度态收口。
  81. lastVisibleUpdateStatusViewModelSelection.current = updateStatusViewModel;
  82. }, [updateStatusViewModel]);
  83. useEffect(() => {
  84. let disposed = false;
  85. const refreshAutoUpdatePreferences = () => {
  86. void platform
  87. .getAutoUpdatePreferences?.()
  88. .then((preferences) => {
  89. if (!disposed) {
  90. setAutoDownloadAndInstallUpdates(preferences.autoDownloadAndInstallUpdates);
  91. }
  92. })
  93. .catch(() => {
  94. if (!disposed) {
  95. setAutoDownloadAndInstallUpdates(false);
  96. }
  97. });
  98. };
  99. refreshAutoUpdatePreferences();
  100. const disposeSettingsChanged =
  101. platform.onSettingsChanged?.(refreshAutoUpdatePreferences) ?? (() => {});
  102. return () => {
  103. disposed = true;
  104. disposeSettingsChanged();
  105. };
  106. }, [platform]);
  107. useEffect(() => {
  108. if (!releaseNotesCacheKey || !localizedUpdateReleaseNotes) {
  109. return;
  110. }
  111. // 下载中会隐藏更新日志,但 electron-updater 的 update-downloaded
  112. // 事件在部分平台只稳定带 version。缓存当前版本的说明,下载完成后即使 ready
  113. // 状态缺少 releaseNotes,也能把刚才隐藏的内容恢复显示。
  114. releaseNotesCacheRef.current.set(releaseNotesCacheKey, {
  115. releaseDateLabel: formattedReleaseDate,
  116. releaseNotes: localizedUpdateReleaseNotes,
  117. });
  118. if (releaseNotesCacheRef.current.size > 8) {
  119. const oldestCacheKey = releaseNotesCacheRef.current.keys().next().value;
  120. if (oldestCacheKey) {
  121. releaseNotesCacheRef.current.delete(oldestCacheKey);
  122. }
  123. }
  124. }, [formattedReleaseDate, localizedUpdateReleaseNotes, releaseNotesCacheKey]);
  125. const cachedReleaseNotes = releaseNotesCacheKey
  126. ? releaseNotesCacheRef.current.get(releaseNotesCacheKey)
  127. : undefined;
  128. const restoredUpdateReleaseNotes =
  129. localizedUpdateReleaseNotes ?? cachedReleaseNotes?.releaseNotes ?? null;
  130. const restoredReleaseDate = formattedReleaseDate ?? cachedReleaseNotes?.releaseDateLabel ?? null;
  131. const visibleUpdateReleaseNotes =
  132. dialogPhase === "downloading" ? null : restoredUpdateReleaseNotes;
  133. const handleOpenReleaseNotesExternalUrl = useCallback(
  134. (url: string) => platform.openExternal(url),
  135. [platform],
  136. );
  137. const handleDownloadUpdate = useCallback(async () => {
  138. if (updateActionInFlightRef.current) {
  139. return;
  140. }
  141. // 如果 electron-updater 命中本地已下载缓存,main 侧会直接广播
  142. // update-downloaded。renderer 不能在 IPC ACK 前后乐观切到“下载中”,否则会闪过
  143. // 一帧无意义的 0%/下载态;这里只锁按钮,真实阶段完全跟随 main 的状态广播。
  144. setUpdateActionInFlight("download");
  145. try {
  146. await platform.downloadUpdate();
  147. } catch (error) {
  148. setUpdateActionInFlight(null);
  149. throw error;
  150. }
  151. }, [platform, setUpdateActionInFlight]);
  152. const handleAutoDownloadAndInstallUpdatesChange = useCallback(
  153. async (enabled: boolean) => {
  154. setAutoDownloadAndInstallUpdates(enabled);
  155. await platform.setAutoDownloadAndInstallUpdates?.(enabled);
  156. if (enabled && updateState?.kind === "update-available") {
  157. // 功能原因:用户在“已发现更新”弹窗里勾选自动下载时,期望当前版本也进入自动流程。
  158. // 这里只触发同一个下载入口;真正是否下载、缓存命中和状态广播仍由 main 进程裁决。
  159. await handleDownloadUpdate();
  160. }
  161. },
  162. [handleDownloadUpdate, platform, updateState?.kind],
  163. );
  164. const handleCancelDownload = useCallback(async () => {
  165. if (updateActionInFlightRef.current) {
  166. return;
  167. }
  168. setUpdateActionInFlight("cancel");
  169. try {
  170. await platform.cancelUpdateDownload();
  171. } catch (error) {
  172. setUpdateActionInFlight(null);
  173. throw error;
  174. }
  175. }, [platform, setUpdateActionInFlight]);
  176. const handleSkipUpdate = useCallback(async () => {
  177. if (!skippableVersion || updateActionInFlightRef.current) {
  178. return;
  179. }
  180. setUpdateActionInFlight("skip");
  181. try {
  182. await platform.skipUpdateVersion(skippableVersion);
  183. onOpenChange(false);
  184. } catch (error) {
  185. setUpdateActionInFlight(null);
  186. throw error;
  187. }
  188. }, [onOpenChange, platform, setUpdateActionInFlight, skippableVersion]);
  189. const handleRestartUpdate = useCallback(async () => {
  190. if (updateActionInFlightRef.current) {
  191. return;
  192. }
  193. const activity = await platform.getDesktopSessionActivity?.();
  194. const runningTaskCount = activity?.runningAgentSessionCount ?? 0;
  195. if (runningTaskCount > 0) {
  196. const confirmed = await requestConfirmation({
  197. title: intl.formatMessage(
  198. { id: "updateReady.confirm.title" },
  199. {
  200. version: displayVersion ?? "",
  201. },
  202. ),
  203. description: intl.formatMessage({
  204. id: "updateReady.confirm.description",
  205. }),
  206. confirmLabel: intl.formatMessage({ id: "updateReady.confirm.ok" }),
  207. cancelLabel: intl.formatMessage({ id: "updateReady.confirm.cancel" }),
  208. });
  209. if (!confirmed) {
  210. return;
  211. }
  212. }
  213. // 重启安装之前是 fire-and-forget,renderer 发完 IPC 就关闭弹窗。
  214. // dev/mock 下 updater 若没有接管安装,用户只会看到弹窗消失,误以为按钮没有响应。
  215. setUpdateActionInFlight("restart");
  216. try {
  217. await platform.quitAndInstallUpdate();
  218. } catch (error) {
  219. setUpdateActionInFlight(null);
  220. throw error;
  221. }
  222. }, [displayVersion, intl, platform, requestConfirmation, setUpdateActionInFlight]);
  223. useEffect(() => {
  224. if (!displayVersion && updateState !== null) {
  225. onOpenChange(false);
  226. }
  227. }, [displayVersion, onOpenChange, updateState]);
  228. useEffect(() => {
  229. if (!updateActionInFlight) {
  230. return;
  231. }
  232. if (isUpdateActionCompleted(updateActionInFlight, updateState)) {
  233. setUpdateActionInFlight(null);
  234. return;
  235. }
  236. // 退出准备和 Windows 安装器交接可能超过 5 秒;旧的统一 ACK 定时器会在
  237. // 应用真正退出前恢复“重启以更新”,让用户误判失败并重复点击。restart 成功路径保持
  238. // pending 直到应用退出,只有 IPC 明确失败时才由调用处 catch 恢复按钮。
  239. if (updateActionInFlight === "restart") {
  240. if (updateState !== null && updateState.kind !== "update-downloaded") {
  241. // main 会在退出准备失败时广播 error/idle。即使 IPC reject 因窗口
  242. // 生命周期丢失,状态已经离开 ready 也必须释放按钮,不能保留上一帧永久 pending。
  243. setUpdateActionInFlight(null);
  244. }
  245. return;
  246. }
  247. // 下载/取消 IPC 在 main 进程会立即 ACK,真实状态靠后续广播收口。
  248. // 连点时需要先锁住按钮;若广播丢失或 main 侧 no-op,也要短超时释放,避免 UI 自己卡住。
  249. const timeout = globalThis.setTimeout(() => {
  250. setUpdateActionInFlight(null);
  251. }, 1500);
  252. return () => {
  253. globalThis.clearTimeout(timeout);
  254. };
  255. }, [setUpdateActionInFlight, updateActionInFlight, updateState?.kind]);
  256. if (!displayVersion) return null;
  257. const releaseDateLabel = restoredReleaseDate
  258. ? intl.formatMessage({ id: "updateDialog.releaseDate" }, { date: restoredReleaseDate })
  259. : null;
  260. return (
  261. <UpdateStatusDialog
  262. autoDownloadAndInstallUpdates={autoDownloadAndInstallUpdates}
  263. displayVersion={displayVersion}
  264. edgeToEdge={edgeToEdge}
  265. intl={intl}
  266. isUpdateActionPending={updateActionInFlight !== null}
  267. localizedUpdateReleaseNotes={visibleUpdateReleaseNotes}
  268. onAutoDownloadAndInstallUpdatesChange={handleAutoDownloadAndInstallUpdatesChange}
  269. onCancelDownload={handleCancelDownload}
  270. onDownloadUpdate={handleDownloadUpdate}
  271. onOpenChange={onOpenChange}
  272. onOpenReleaseNotesExternalUrl={handleOpenReleaseNotesExternalUrl}
  273. onRestartUpdate={handleRestartUpdate}
  274. onSkipUpdate={handleSkipUpdate}
  275. open={open}
  276. phase={dialogPhase}
  277. progressLabel={progressLabel}
  278. progressValue={progressValue}
  279. releaseDateLabel={releaseDateLabel}
  280. showOverlay={showOverlay}
  281. skippableVersion={skippableVersion}
  282. />
  283. );
  284. }