Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(updater): 修复失败重试和重复安装请求 (#980)

SkanderBot6c28f126361b
diff --git a/src/store/modules/desktop-updater/store.test.ts b/src/store/modules/desktop-updater/store.test.ts
new file mode 100644
index 00000000..e2332766
--- /dev/null
+++ b/src/store/modules/desktop-updater/store.test.ts
@@ -0,0 +1,240 @@
+import type { DesktopUpdateInfo } from './types'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ invoke: vi.fn(),
+ listen: vi.fn(),
+ toast: vi.fn(),
+}))
+
+vi.mock('@tauri-apps/api/core', () => ({ invoke: mocks.invoke }))
+vi.mock('@tauri-apps/api/event', () => ({ listen: mocks.listen }))
+vi.mock('i18next', () => ({ default: { t: (key: string) => key } }))
+vi.mock('@/utils/toast', () => ({ toast: mocks.toast }))
+
+const UPDATE: DesktopUpdateInfo = {
+ version: '0.22.4',
+ currentVersion: '0.22.3',
+ tag: 'v0.22.4',
+ published_at: '2026-10-08T00:00:00Z',
+ url: 'https://example.test/v0.22.4',
+ asset_name: 'desktop-installer.exe',
+ path: 'C:/desktop-installer.exe',
+ downloaded: true,
+}
+
+let desktopUpdater: (typeof import('./store'))['desktopUpdater']
+
+beforeEach(async () => {
+ vi.resetModules()
+ mocks.invoke.mockReset()
+ mocks.listen.mockReset().mockResolvedValue(() => {})
+ mocks.toast.mockReset()
+ ;({ desktopUpdater } = await import('./store'))
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+})
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason: unknown) => void
+ const promise = new Promise<T>((done, fail) => {
+ resolve = done
+ reject = fail
+ })
+ return { promise, resolve, reject }
+}
+
+describe('desktop updater operation coordination', () => {
+ it('shares the final update result while a check is already in flight', async () => {
+ const pending = deferred<DesktopUpdateInfo | null>()
+ const stale = { ...UPDATE, version: '0.22.2', tag: 'v0.22.2' }
+ desktopUpdater.updateInfo = stale
+ mocks.invoke.mockImplementation((command: string) => {
+ if (command === 'check_desktop_update')
+ return pending.promise
+ throw new Error(`Unexpected command: ${command}`)
+ })
+
+ const first = desktopUpdater.check()
+ const second = desktopUpdater.check()
+
+ expect(second).toBe(first)
+ expect(desktopUpdater.checking).toBe(true)
+ expect(mocks.invoke).toHaveBeenCalledExactlyOnceWith('check_desktop_update')
+ pending.resolve(UPDATE)
+ await expect(Promise.all([first, second])).resolves.toEqual([UPDATE, UPDATE])
+ expect(desktopUpdater.updateInfo).toEqual(UPDATE)
+ expect(desktopUpdater.checking).toBe(false)
+ })
+
+ it('shares a check failure with every caller and allows a later retry', async () => {
+ const pending = deferred<DesktopUpdateInfo | null>()
+ const failure = new Error('release service unavailable')
+ mocks.invoke.mockImplementationOnce(() => pending.promise).mockResolvedValueOnce(null)
+
+ const first = desktopUpdater.check()
+ const second = desktopUpdater.check()
+ const outcomes = Promise.allSettled([first, second])
+ pending.reject(failure)
+
+ await expect(outcomes).resolves.toEqual([
+ { status: 'rejected', reason: failure },
+ { status: 'rejected', reason: failure },
+ ])
+ expect(desktopUpdater.checking).toBe(false)
+ await expect(desktopUpdater.check()).resolves.toBeNull()
+ expect(mocks.invoke).toHaveBeenCalledTimes(2)
+ })
+
+ it('refreshes native installer state when the release tag is unchanged', async () => {
+ const download = deferred<DesktopUpdateInfo>()
+ const refreshed = { ...UPDATE, path: 'C:/replacement-installer.exe', downloaded: false }
+ desktopUpdater.updateInfo = { ...UPDATE, path: 'C:/removed-installer.exe' }
+ mocks.invoke.mockImplementation((command: string) => {
+ if (command === 'check_desktop_update')
+ return Promise.resolve(refreshed)
+ if (command === 'download_desktop_update')
+ return download.promise
+ throw new Error(`Unexpected command: ${command}`)
+ })
+
+ await expect(desktopUpdater.check()).resolves.toEqual(refreshed)
+ expect(desktopUpdater.updateInfo).toEqual(refreshed)
+ expect(mocks.invoke).toHaveBeenCalledWith('download_desktop_update')
+ download.resolve({ ...refreshed, downloaded: true })
+ await vi.waitFor(() => {
+ expect(desktopUpdater.updateInfo).toEqual({ ...refreshed, downloaded: true })
+ })
+ })
+
+ it('downloads and opens an installer only once for simultaneous actions', async () => {
+ const download = deferred<DesktopUpdateInfo>()
+ const open = deferred<void>()
+ desktopUpdater.updateInfo = { ...UPDATE, downloaded: false }
+ mocks.invoke.mockImplementation((command: string) => {
+ if (command === 'download_desktop_update')
+ return download.promise
+ if (command === 'open_desktop_installer')
+ return open.promise
+ throw new Error(`Unexpected command: ${command}`)
+ })
+
+ const first = desktopUpdater.downloadAndOpen()
+ const second = desktopUpdater.downloadAndOpen()
+
+ expect(second).toBe(first)
+ expect(mocks.invoke).toHaveBeenCalledExactlyOnceWith('download_desktop_update')
+ download.resolve(UPDATE)
+ await vi.waitFor(() => {
+ expect(mocks.invoke).toHaveBeenCalledWith('open_desktop_installer', { path: UPDATE.path })
+ })
+ expect(mocks.invoke.mock.calls.filter(([command]) => command === 'open_desktop_installer')).toHaveLength(1)
+ open.resolve()
+ await expect(Promise.all([first, second])).resolves.toEqual([true, true])
+ expect(mocks.toast).toHaveBeenCalledExactlyOnceWith('update.desktop_opened', {
+ variant: 'default',
+ placement: 'bottom end',
+ })
+ })
+
+ it('reuses a background download before opening the installer', async () => {
+ const download = deferred<DesktopUpdateInfo>()
+ const open = deferred<void>()
+ desktopUpdater.updateInfo = { ...UPDATE, downloaded: false }
+ mocks.invoke.mockImplementation((command: string) => {
+ if (command === 'download_desktop_update')
+ return download.promise
+ if (command === 'open_desktop_installer')
+ return open.promise
+ throw new Error(`Unexpected command: ${command}`)
+ })
+
+ const background = desktopUpdater.download()
+ const first = desktopUpdater.downloadAndOpen()
+ const second = desktopUpdater.downloadAndOpen()
+
+ expect(second).toBe(first)
+ expect(mocks.invoke).toHaveBeenCalledExactlyOnceWith('download_desktop_update')
+ download.resolve(UPDATE)
+ await vi.waitFor(() => {
+ expect(mocks.invoke).toHaveBeenCalledWith('open_desktop_installer', { path: UPDATE.path })
+ })
+ open.resolve()
+ await expect(Promise.all([background, first, second])).resolves.toEqual([undefined, true, true])
+ expect(mocks.invoke.mock.calls.filter(([command]) => command === 'download_desktop_update')).toHaveLength(1)
+ expect(mocks.invoke.mock.calls.filter(([command]) => command === 'open_desktop_installer')).toHaveLength(1)
+ })
+
+ it('opens an existing installer only once for simultaneous actions', async () => {
+ const open = deferred<void>()
+ desktopUpdater.updateInfo = UPDATE
+ mocks.invoke.mockImplementation((command: string) => {
+ if (command === 'open_desktop_installer')
+ return open.promise
+ throw new Error(`Unexpected command: ${command}`)
+ })
+
+ const first = desktopUpdater.downloadAndOpen()
+ const second = desktopUpdater.downloadAndOpen()
+
+ expect(second).toBe(first)
+ expect(mocks.invoke).toHaveBeenCalledExactlyOnceWith('open_desktop_installer', { path: UPDATE.path })
+ open.resolve()
+ await expect(Promise.all([first, second])).resolves.toEqual([true, true])
+ })
+
+ it('reports an installer launch failure and permits a retry', async () => {
+ const failure = new Error('shell rejected installer')
+ desktopUpdater.updateInfo = UPDATE
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ mocks.invoke.mockRejectedValueOnce(failure).mockResolvedValueOnce(undefined)
+
+ await expect(desktopUpdater.downloadAndOpen()).resolves.toBe(false)
+ expect(mocks.toast).toHaveBeenCalledWith('update.desktop_open_failed', {
+ variant: 'danger',
+ placement: 'bottom end',
+ })
+ await expect(desktopUpdater.downloadAndOpen()).resolves.toBe(true)
+ expect(mocks.invoke).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not invoke native update actions when no update is available', async () => {
+ desktopUpdater.updateInfo = null
+
+ await expect(desktopUpdater.downloadAndOpen()).resolves.toBe(false)
+ expect(mocks.invoke).not.toHaveBeenCalled()
+ expect(mocks.toast).not.toHaveBeenCalled()
+ })
+
+ it('does not open an installer after a failed download', async () => {
+ desktopUpdater.updateInfo = { ...UPDATE, downloaded: false }
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ mocks.invoke.mockRejectedValueOnce(new Error('download interrupted'))
+
+ await expect(desktopUpdater.downloadAndOpen()).resolves.toBe(false)
+ expect(mocks.invoke).toHaveBeenCalledExactlyOnceWith('download_desktop_update')
+ expect(mocks.toast).toHaveBeenCalledExactlyOnceWith('update.desktop_download_failed', {
+ variant: 'danger',
+ placement: 'bottom end',
+ })
+ })
+
+ it('retries a failed download before opening the installer', async () => {
+ desktopUpdater.updateInfo = { ...UPDATE, downloaded: false }
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ mocks.invoke
+ .mockRejectedValueOnce(new Error('download interrupted'))
+ .mockResolvedValueOnce(UPDATE)
+ .mockResolvedValueOnce(undefined)
+
+ await expect(desktopUpdater.downloadAndOpen()).resolves.toBe(false)
+ await expect(desktopUpdater.downloadAndOpen()).resolves.toBe(true)
+ expect(mocks.invoke.mock.calls.filter(([command]) => command === 'download_desktop_update')).toHaveLength(2)
+ expect(mocks.invoke.mock.calls.filter(([command]) => command === 'open_desktop_installer')).toEqual([
+ ['open_desktop_installer', { path: UPDATE.path }],
+ ])
+ })
+})
diff --git a/src/store/modules/desktop-updater/store.ts b/src/store/modules/desktop-updater/store.ts
index d7f23894..998aab5b 100644
--- a/src/store/modules/desktop-updater/store.ts
+++ b/src/store/modules/desktop-updater/store.ts
@@ -9,11 +9,9 @@ import i18next from 'i18next'
import { defineStore } from 'valtio-define'
import { toast } from '@/utils/toast'
-/**
- * 在途的静默下载任务:同一时刻只允许一个下载,用户点击「立即更新」时复用它
- * 而不是重复发起(后端 `download` 幂等,但重复的进度事件会让进度条来回跳)。
- */
+let checkTask: Promise<DesktopUpdateInfo | null> | null = null
let downloadTask: Promise<void> | null = null
+let downloadAndOpenTask: Promise<boolean> | null = null
/**
* 桌面端自更新模块:检查新版本 → 静默下载安装包 → 打开安装器完成升级。
@@ -44,32 +42,36 @@ export const desktopUpdater = defineStore({
actions: {
/**
* 检查是否有新版本;发现更新时顺带发起静默下载。
- * 轮询与「检查更新」共用;仅在 tag 变化时更新 updateInfo,
- * 让菜单/chip 的新版本指示实时反映。
+ * 轮询与「检查更新」共用;每次用原生结果同步完整 updateInfo,
+ * 让安装包被移动/删除后的 downloaded/path 状态也能实时反映。
* 网络失败/限流时抛出错误(不吞掉),由调用方决定如何提示——
* 绝不能把「检查失败」误报成「已是最新」。
*/
- async check(): Promise<DesktopUpdateInfo | null> {
- if (this.checking)
- return this.updateInfo
+ check(): Promise<DesktopUpdateInfo | null> {
+ if (checkTask)
+ return checkTask
this.checking = true
- try {
- const info = await invoke<DesktopUpdateInfo | null>('check_desktop_update')
- if (info) {
- if (this.updateInfo?.tag !== info.tag)
+ const task = (async () => {
+ try {
+ const info = await invoke<DesktopUpdateInfo | null>('check_desktop_update')
+ if (info) {
this.updateInfo = info
- // 检测到更新即静默下载(不弹 toast、不打开安装器);失败静默,
- // 用户点击「立即更新」时会重试并给出可见的错误提示
- void this.download()
+ // 检测到更新即静默下载(不弹 toast、不打开安装器);失败静默,
+ // 用户点击「立即更新」时会重试并给出可见的错误提示
+ void this.download()
+ }
+ else {
+ this.updateInfo = null
+ }
+ return info
}
- else {
- this.updateInfo = null
+ finally {
+ checkTask = null
+ this.checking = false
}
- return info
- }
- finally {
- this.checking = false
- }
+ })()
+ checkTask = task
+ return task
},
/**
@@ -119,47 +121,49 @@ export const desktopUpdater = defineStore({
* 「立即更新」:等待在途的静默下载(没有则发起),完成后打开安装器。
* 已下载则直接打开;下载失败时给出可见提示(对话框保持打开)。
*/
- async downloadAndOpen() {
- const info = this.updateInfo
- if (!info)
- return
+ downloadAndOpen(): Promise<boolean> {
+ if (downloadAndOpenTask)
+ return downloadAndOpenTask
+ const task = (async () => {
+ const info = this.updateInfo
+ if (!info)
+ return false
- // 已下载 → 直接打开安装包
- if (info.downloaded) {
- await this.openInstaller(info.path)
- return
- }
-
- await this.download()
- const updated = this.updateInfo
- if (updated?.downloaded) {
- await this.openInstaller(updated.path)
- }
- else if (!this.downloading) {
- // 下载确实失败(download 内部已 console 记录)→ 给出可见提示
- toast(i18next.t('update.desktop_download_failed'), {
- variant: 'danger',
- placement: 'bottom end',
- })
- }
- },
+ let path = info.path
+ if (!info.downloaded) {
+ await this.download()
+ const updated = this.updateInfo
+ if (!updated?.downloaded) {
+ toast(i18next.t('update.desktop_download_failed'), {
+ variant: 'danger',
+ placement: 'bottom end',
+ })
+ return false
+ }
+ path = updated.path
+ }
- /** 打开安装包并提示(对话框由调用方 / overlastic 自行关闭) */
- async openInstaller(path: string) {
- try {
- await invoke('open_desktop_installer', { path })
- toast(i18next.t('update.desktop_opened'), {
- variant: 'default',
- placement: 'bottom end',
- })
- }
- catch (err) {
- console.error('[DesktopUpdater] failed to open installer:', err)
- toast(i18next.t('update.desktop_open_failed'), {
- variant: 'danger',
- placement: 'bottom end',
- })
- }
+ try {
+ await invoke('open_desktop_installer', { path })
+ toast(i18next.t('update.desktop_opened'), {
+ variant: 'default',
+ placement: 'bottom end',
+ })
+ return true
+ }
+ catch (err) {
+ console.error('[DesktopUpdater] failed to open installer:', err)
+ toast(i18next.t('update.desktop_open_failed'), {
+ variant: 'danger',
+ placement: 'bottom end',
+ })
+ return false
+ }
+ })().finally(() => {
+ downloadAndOpenTask = null
+ })
+ downloadAndOpenTask = task
+ return task
},
},
})
diff --git a/src/ui/dialog/update.test.tsx b/src/ui/dialog/update.test.tsx
index 6078ea73..0e29d7fb 100644
--- a/src/ui/dialog/update.test.tsx
+++ b/src/ui/dialog/update.test.tsx
@@ -1,5 +1,6 @@
// @vitest-environment jsdom
import { OverlaysProvider, useOverlay } from '@overlastic/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { StrictMode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -11,7 +12,6 @@ const { desktopUpdater } = vi.hoisted(() => ({
downloading: false,
downloadProgress: 0,
downloadAndOpen: vi.fn(),
- openInstaller: vi.fn(),
},
}))
@@ -27,12 +27,21 @@ function Launcher() {
return <button onClick={handleOpen}>Open update</button>
}
+let client: QueryClient
+
function openDialog() {
- render(<StrictMode><OverlaysProvider><Launcher /></OverlaysProvider></StrictMode>)
+ render(
+ <StrictMode>
+ <QueryClientProvider client={client}>
+ <OverlaysProvider><Launcher /></OverlaysProvider>
+ </QueryClientProvider>
+ </StrictMode>,
+ )
fireEvent.click(screen.getByText('Open update'))
}
beforeEach(() => {
+ client = new QueryClient({ defaultOptions: { mutations: { retry: false } } })
desktopUpdater.updateInfo = {
currentVersion: '0.21.1',
version: '0.21.2',
@@ -43,7 +52,6 @@ beforeEach(() => {
desktopUpdater.downloading = false
desktopUpdater.downloadProgress = 0
desktopUpdater.downloadAndOpen.mockReset()
- desktopUpdater.openInstaller.mockReset()
})
afterEach(() => {
@@ -74,11 +82,44 @@ describe('desktop update dialog', () => {
expect((await screen.findByRole('button', { name: 'update.open_installer' })).textContent).toBe('update.open_installer')
})
- it('opens the installer instead of downloading when the package already exists', async () => {
+ it('closes after an existing installer is opened successfully', async () => {
+ desktopUpdater.updateInfo!.downloaded = true
+ desktopUpdater.downloadAndOpen.mockResolvedValue(true)
+ openDialog()
+ fireEvent.click(await screen.findByRole('button', { name: 'update.open_installer' }))
+ await vi.waitFor(() => {
+ expect(screen.queryByRole('button', { name: 'update.open_installer' })).toBeNull()
+ })
+ expect(desktopUpdater.downloadAndOpen).toHaveBeenCalledOnce()
+ })
+
+ it('keeps the dialog open when the installer cannot be opened', async () => {
desktopUpdater.updateInfo!.downloaded = true
+ desktopUpdater.downloadAndOpen.mockResolvedValue(false)
openDialog()
fireEvent.click(await screen.findByRole('button', { name: 'update.open_installer' }))
- expect(desktopUpdater.openInstaller).toHaveBeenCalledExactlyOnceWith('C:/installer.exe')
- expect(desktopUpdater.downloadAndOpen).not.toHaveBeenCalled()
+ await vi.waitFor(() => {
+ expect(desktopUpdater.downloadAndOpen).toHaveBeenCalledOnce()
+ })
+ expect(screen.queryByRole('button', { name: 'update.open_installer' })).not.toBeNull()
+ })
+
+ it('disables the primary action while installer handoff is pending', async () => {
+ let finish!: (opened: boolean) => void
+ const pending = new Promise<boolean>((resolve) => {
+ finish = resolve
+ })
+ desktopUpdater.updateInfo!.downloaded = true
+ desktopUpdater.downloadAndOpen.mockReturnValue(pending)
+ openDialog()
+ const primary = await screen.findByRole<HTMLButtonElement>('button', { name: 'update.open_installer' })
+ fireEvent.click(primary)
+ await vi.waitFor(() => {
+ expect(primary.disabled).toBe(true)
+ })
+ finish(false)
+ await vi.waitFor(() => {
+ expect(primary.disabled).toBe(false)
+ })
})
})
diff --git a/src/ui/dialog/update.tsx b/src/ui/dialog/update.tsx
index c0d7cac3..ef7ce97b 100644
--- a/src/ui/dialog/update.tsx
+++ b/src/ui/dialog/update.tsx
@@ -1,6 +1,7 @@
import type { PropsWithOverlays } from '@overlastic/react'
import { AlertDialog, Button, Description, ProgressBar } from '@heroui/react'
import { useDisclosure } from '@overlastic/react'
+import { useMutation } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { If } from 'react-if-lite'
import { useStore } from 'valtio-define'
@@ -9,44 +10,21 @@ import { store } from '@/store'
export interface DesktopUpdateDialogProps extends PropsWithOverlays {}
-/**
- * 「检查更新」对话框:展示新版本信息 + 下载进度。
- *
- * 两个入口共用(顶部「更新可用」chip / 帮助菜单「检查更新」):
- * - 检测到更新后 store 已在静默下载 → 打开即展示进度条;此时点「立即更新」会
- * 等待这次下载结束,完成后再打开安装包(不会重复下载);
- * - 已下载 → 「打开安装包」直接交给系统安装器;
- * - 未下载(上次下载失败等)→ 「立即更新」重新下载,完成后自动打开安装包。
- *
- * 注意:后台静默下载完成时**不**自动关闭/打开——只有用户点了主按钮才交给安装器,
- * 否则用户刚打开的对话框会在下载完成时莫名消失。
- *
- * 对话框在下载中同样可关闭:下载由 store 驱动、与对话框生命周期无关,锁住弹窗
- * 只会让「打开看进度」的用户无法退出(更新入口 chip 常驻,随时能再打开)。
- *
- * 下载中隐藏底部按钮(「稍后」/「立即更新」):此阶段主按钮只会阻塞等待同一次下载,
- * 点击无意义;关闭仍可用右上角 X。
- */
+/** 「检查更新」对话框:展示新版本信息、下载进度并交给系统安装器。 */
export function DesktopUpdateDialog(props: DesktopUpdateDialogProps) {
+ // 1. 数据查询 (Queries)
const disclosure = useDisclosure({ props })
const { t } = useTranslation()
const { updateInfo, downloading, downloadProgress } = useStore(store.desktopUpdater)
- /** 主按钮:已下载直接打开;未下载则等待/发起下载,完成后打开安装器 */
- async function handlePrimary() {
- const info = store.desktopUpdater.updateInfo
- if (!info)
- return
- if (info.downloaded) {
- await store.desktopUpdater.openInstaller(info.path)
- disclosure.cancel()
- return
- }
- await store.desktopUpdater.downloadAndOpen()
- // 下载成功(安装包已交给系统)→ 收起对话框;失败保持打开,用户可重试
- if (store.desktopUpdater.updateInfo?.downloaded)
- disclosure.cancel()
- }
+ // 5. 使用 useMutation 封装安装流程 (Mutations)
+ const { mutate: handlePrimary, isPending: openingInstaller } = useMutation({
+ mutationFn: () => store.desktopUpdater.downloadAndOpen(),
+ onSuccess: (opened) => {
+ if (opened)
+ disclosure.cancel()
+ },
+ })
return (
<AlertDialog onOpenChange={disclosure.cancel} isOpen={disclosure.visible}>
@@ -98,8 +76,8 @@ export function DesktopUpdateDialog(props: DesktopUpdateDialogProps) {
</Button>
<Button
variant="primary"
- isDisabled={updateInfo == null}
- onPress={handlePrimary}
+ isDisabled={updateInfo == null || openingInstaller}
+ onPress={() => handlePrimary()}
>
{updateInfo?.downloaded
? t('update.open_installer')