DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(desktop): add self-update and about dialog
hairyfb1d5faed367d
diff --git a/src-tauri/src/bridge/cmd.rs b/src-tauri/src/bridge/cmd.rsindex ed08df77..5ca5c11d 100644--- a/src-tauri/src/bridge/cmd.rs+++ b/src-tauri/src/bridge/cmd.rs@@ -2,6 +2,7 @@ use crate::config;use crate::service::cli;use crate::service::download::{self, Installable};use crate::service::plugin;+use crate::service::update;use crate::service::workflow;use tauri::{AppHandle, Manager};use tauri_plugin_clipboard_manager::ClipboardExt;@@ -389,3 +390,43 @@ pub async fn toggle_sidebar() -> Result<bool, String> {pub fn get_dsh_theme(app_handle: AppHandle) -> config::DshTheme {config::get_dsh_theme(&app_handle)}++/// 检查桌面端自身是否有新版本(含安装包是否已下载)+#[tauri::command]+pub async fn check_desktop_update(+ app_handle: AppHandle,+) -> Result<Option<update::DesktopUpdateInfo>, String> {+ update::check(&app_handle).await+}++/// 下载桌面端新版本安装包;已下载则直接返回。进度通过 `desktop-update-progress` 事件推送+#[tauri::command]+pub async fn download_desktop_update(+ app_handle: AppHandle,+) -> Result<update::DesktopUpdateInfo, String> {+ update::download(&app_handle).await+}++/// 打开已下载的桌面端安装包(exe/msi/dmg...,交给系统默认处理器)+#[tauri::command]+pub async fn open_desktop_installer(app_handle: AppHandle, path: String) -> Result<(), String> {+ update::open_installer(&app_handle, path).await+}++/// 关于对话框信息(版本 / 发布时间 / 版权 / 仓库)+#[tauri::command]+pub async fn get_desktop_about() -> Result<update::DesktopAboutInfo, String> {+ Ok(update::about().await)+}++/// 在系统浏览器中打开任意 http(s) 链接(更新说明 / 关于对话框仓库链接等)+#[tauri::command]+pub async fn open_external_url(app_handle: AppHandle, url: String) -> Result<(), String> {+ if !(url.starts_with("https://") || url.starts_with("http://")) {+ return Err(format!("EXTERNAL_URL_INVALID: {url}"));+ }+ app_handle+ .opener()+ .open_url(url, None::<&str>)+ .map_err(|e| e.to_string())+}diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 76278906..5b8ab7dc 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -201,6 +201,11 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::cmd::set_language,crate::bridge::cmd::toggle_sidebar,crate::bridge::cmd::get_dsh_theme,+ crate::bridge::cmd::check_desktop_update,+ crate::bridge::cmd::download_desktop_update,+ crate::bridge::cmd::open_desktop_installer,+ crate::bridge::cmd::get_desktop_about,+ crate::bridge::cmd::open_external_url,crate::desktop::notification::show_native_notification,]}diff --git a/src-tauri/src/service/mod.rs b/src-tauri/src/service/mod.rsindex bff4b931..b6499439 100644--- a/src-tauri/src/service/mod.rs+++ b/src-tauri/src/service/mod.rs@@ -2,4 +2,5 @@ pub mod cli;pub mod download;pub mod plugin;pub mod scheduler;+pub mod update;pub mod workflow;diff --git a/src-tauri/src/service/update/mod.rs b/src-tauri/src/service/update/mod.rsnew file mode 100644index 00000000..842d2d32--- /dev/null+++ b/src-tauri/src/service/update/mod.rs@@ -0,0 +1,410 @@+//! 桌面应用自更新模块。+//!+//! 与 `dsh` 内核更新(`download` 模块)不同,这里负责「DeepSeek Harness 桌面端」+//! 自身的更新:查询 GitHub Release 的最新版本、下载安装包、并交给系统打开安装器。+//!+//! 设计考量:+//! - GitHub 未认证 API 限流 60 次/小时/IP,而前端每 10 秒轮询一次「检查更新」,+//! 因此这里对最新 Release 查询结果做 5 分钟内存缓存,轮询命中缓存、不再打网络。+//! - 安装包下载到 AppData/updates 目录;已存在则视为「已下载」,不再重复拉取。+//! - 打开安装器(exe/msi/dmg 等)交给系统默认处理器(ShellExecute/LaunchServices)。++use std::path::PathBuf;+use std::sync::{Mutex, OnceLock};+use std::time::{Duration, Instant};++use futures_util::StreamExt;+use tauri::{AppHandle, Emitter, Manager};+use tauri_plugin_opener::OpenerExt;++/// 桌面端 GitHub 仓库 API 地址(未认证限流 60 次/小时/IP)+const GITHUB_API: &str = "https://api.github.com/repos/hairyf/deepseek-harness-desktop";+/// 仓库主页(关于对话框展示)+const REPO_URL: &str = "https://github.com/hairyf/deepseek-harness-desktop";+/// 版权信息(与 tauri.conf.json bundle.copyright 保持一致)+const COPYRIGHT: &str = "Copyright © 2026 Deepseek Harness Desktop contributors";+/// About 对话框的 "Powered by" 文案+const POWERED_BY: &str = "DeepSeek Harness";+/// 最新 Release 查询结果缓存时长(轮询防限流)+const CACHE_TTL: Duration = Duration::from_secs(300);+/// AppData 下安装包存放目录名+const UPDATES_DIR: &str = "updates";++/// 最新可用发布信息(仅在有更新且匹配到当前平台安装包时才有意义)+#[derive(Debug, Clone)]+struct LatestRelease {+ version: String,+ tag: String,+ published_at: String,+ url: String,+ asset_name: String,+}++/// 缓存的查询结果:published_at 无论是否有更新都会写入,+/// release 仅在「有更新且匹配到资产」时为 Some,其余为 None(同样缓存以免限流)。+struct CacheEntry {+ fetched_at: Instant,+ published_at: String,+ release: Option<LatestRelease>,+}++static CACHE: OnceLock<Mutex<Option<CacheEntry>>> = OnceLock::new();++/// 当前桌面端版本号(来自 Cargo.toml / tauri.conf.json)+fn current_version() -> String {+ env!("CARGO_PKG_VERSION").to_string()+}++/// 解析版本号为数字段序列:`v0.5.2` / `0.5.2` → [0, 5, 2]+fn parse_version(v: &str) -> Option<Vec<u64>> {+ let s = v.trim().trim_start_matches('v');+ s.split('.')+ .map(|p| p.parse().ok())+ .collect::<Option<Vec<_>>>()+}++/// 判断 `latest` 是否严格高于 `current`(逐段比较,段数多者视作更新)+fn is_newer(latest: &str, current: &str) -> bool {+ let Some(a) = parse_version(latest) else {+ return false;+ };+ let Some(b) = parse_version(current) else {+ return false;+ };+ for (x, y) in a.iter().zip(b.iter()) {+ if x != y {+ return x > y;+ }+ }+ a.len() > b.len()+}++/// 选择当前平台对应的安装包资产(名称, 下载 URL)。+///+/// 优先级由各平台偏好扩展名顺序决定:Windows 优先 msi(其次 exe/nsis),+/// macOS 选 dmg,Linux 选 AppImage(其次 deb/rpm)。+fn pick_asset(assets: &[serde_json::Value]) -> Option<(String, String)> {+ #[cfg(target_os = "windows")]+ let prefs = [".msi", ".exe"];+ #[cfg(target_os = "macos")]+ let prefs = [".dmg"];+ #[cfg(target_os = "linux")]+ let prefs = [".AppImage", ".deb", ".rpm"];++ let mut best: Option<(usize, String, String)> = None;+ for asset in assets {+ let Some(name) = asset.get("name").and_then(|v| v.as_str()) else {+ continue;+ };+ let Some(idx) = prefs.iter().position(|p| name.ends_with(p)) else {+ continue;+ };+ let Some(url) = asset.get("browser_download_url").and_then(|v| v.as_str()) else {+ continue;+ };+ let rank = prefs.len() - idx; // 越靠前优先级越高+ if best.as_ref().is_none_or(|(r, _, _)| rank > *r) {+ best = Some((rank, name.to_string(), url.to_string()));+ }+ }+ best.map(|(_, name, url)| (name, url))+}++/// 查询最新 Release(带缓存)。+///+/// 返回 `Ok(Some(LatestRelease))` 表示有更新且匹配到当前平台安装包;+/// `Ok(None)` 表示无更新(或未匹配到资产)。网络失败/限流返回 Err。+async fn fetch_latest_release() -> Result<Option<LatestRelease>, String> {+ {+ let lock = CACHE.get_or_init(|| Mutex::new(None));+ if let Ok(guard) = lock.lock() {+ if let Some(entry) = guard.as_ref() {+ if entry.fetched_at.elapsed() < CACHE_TTL {+ return Ok(entry.release.clone());+ }+ }+ }+ }++ let client = reqwest::Client::builder()+ .user_agent("deepseek-harness-desktop")+ .timeout(Duration::from_secs(5))+ .build()+ .map_err(|e| format!("UPDATE_CLIENT: {e}"))?;++ let release: serde_json::Value = client+ .get(format!("{GITHUB_API}/releases/latest"))+ .send()+ .await+ .map_err(|e| format!("UPDATE_REQ: {e}"))?+ .error_for_status()+ .map_err(|e| format!("UPDATE_REQ: {e}"))?+ .json()+ .await+ .map_err(|e| format!("UPDATE_PARSE: {e}"))?;++ let tag_name = release+ .get("tag_name")+ .and_then(|v| v.as_str())+ .unwrap_or_default()+ .to_string();+ let published_at = release+ .get("published_at")+ .and_then(|v| v.as_str())+ .unwrap_or_default()+ .to_string();+ let version = tag_name.trim_start_matches('v').to_string();++ let assets = release+ .get("assets")+ .and_then(|v| v.as_array())+ .cloned()+ .unwrap_or_default();+ let asset = pick_asset(&assets);++ // 有更新且匹配到资产才视为「可更新」+ let release = if is_newer(&version, ¤t_version()) {+ match asset {+ Some((name, url)) => Some(LatestRelease {+ version: version.clone(),+ tag: tag_name.clone(),+ published_at: published_at.clone(),+ url,+ asset_name: name,+ }),+ None => None,+ }+ } else {+ None+ };++ if let Ok(mut guard) = CACHE.get_or_init(|| Mutex::new(None)).lock() {+ *guard = Some(CacheEntry {+ fetched_at: Instant::now(),+ published_at,+ release: release.clone(),+ });+ }+ Ok(release)+}++/// 安装包存放路径(AppData/updates/<asset_name>)+fn installer_path(app_handle: &AppHandle, asset_name: &str) -> Result<PathBuf, String> {+ let dir = app_handle+ .path()+ .app_data_dir()+ .map_err(|e| format!("UPDATE_DIR: {e}"))?+ .join(UPDATES_DIR);+ std::fs::create_dir_all(&dir).map_err(|e| format!("UPDATE_DIR: {e}"))?;+ Ok(dir.join(asset_name))+}++/// 检查是否有桌面端新版本。+#[derive(Debug, Clone, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct DesktopUpdateInfo {+ pub version: String,+ pub tag: String,+ pub published_at: String,+ pub url: String,+ pub asset_name: String,+ pub path: String,+ pub downloaded: bool,+}++/// 检查是否有新版本可用(含安装包是否已下载)+pub async fn check(app_handle: &AppHandle) -> Result<Option<DesktopUpdateInfo>, String> {+ match fetch_latest_release().await? {+ None => Ok(None),+ Some(r) => {+ let path = installer_path(app_handle, &r.asset_name)?;+ let downloaded = path.exists();+ Ok(Some(DesktopUpdateInfo {+ version: r.version,+ tag: r.tag,+ published_at: r.published_at,+ url: r.url,+ asset_name: r.asset_name,+ path: path.to_string_lossy().into_owned(),+ downloaded,+ }))+ }+ }+}++/// 下载进度载荷(前端进度条展示)+#[derive(Clone, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct DesktopDownloadProgress {+ pub percentage: f64,+ pub downloaded: u64,+ pub total: u64,+}++/// 下载桌面端安装包;已下载则直接返回。+///+/// 下载期间通过 `desktop-update-progress` 事件推送进度;完成后返回+/// `DesktopUpdateInfo`(path/downloaded 已更新)。+pub async fn download(app_handle: &AppHandle) -> Result<DesktopUpdateInfo, String> {+ let release = fetch_latest_release()+ .await?+ .ok_or_else(|| "UPDATE_NONE".to_string())?;+ let path = installer_path(app_handle, &release.asset_name)?;++ if path.exists() {+ log::info!("Installer already downloaded: {}", path.display());+ return check(app_handle)+ .await?+ .ok_or_else(|| "UPDATE_NONE".to_string());+ }++ log::info!("Downloading desktop installer from {}", release.url);+ let client = reqwest::Client::builder()+ .user_agent("deepseek-harness-desktop")+ .build()+ .map_err(|e| format!("UPDATE_CLIENT: {e}"))?;++ let res = client+ .get(&release.url)+ .send()+ .await+ .map_err(|e| format!("UPDATE_DOWNLOAD: {e}"))?+ .error_for_status()+ .map_err(|e| format!("UPDATE_DOWNLOAD: {e}"))?;++ let total = res.content_length().unwrap_or(0);+ // 先写临时文件再原子改名,避免下载中断残留半成品被误判为「已下载」+ let tmp = path.with_extension("part");+ let mut file = std::fs::File::create(&tmp).map_err(|e| format!("UPDATE_FILE: {e}"))?;++ use std::io::Write;+ let mut downloaded: u64 = 0;+ let mut stream = res.bytes_stream();+ while let Some(chunk) = stream.next().await {+ let chunk = chunk.map_err(|e| format!("UPDATE_DOWNLOAD: {e}"))?;+ file.write_all(&chunk).map_err(|e| format!("UPDATE_FILE: {e}"))?;+ downloaded += chunk.len() as u64;+ let pct = if total > 0 {+ (downloaded as f64 / total as f64) * 100.0+ } else {+ 0.0+ };+ let _ = app_handle.emit(+ "desktop-update-progress",+ DesktopDownloadProgress {+ percentage: pct,+ downloaded,+ total,+ },+ );+ }+ drop(file);+ std::fs::rename(&tmp, &path).map_err(|e| format!("UPDATE_FILE: {e}"))?;++ check(app_handle)+ .await?+ .ok_or_else(|| "UPDATE_NONE".to_string())+}++/// 打开安装包:交给系统默认处理器(Windows 会触发 UAC 执行安装器)。+pub async fn open_installer(app_handle: &AppHandle, path: String) -> Result<(), String> {+ let p = std::path::Path::new(&path);+ if !p.exists() {+ return Err(format!("UPDATE_NOT_FOUND: {path}"));+ }+ log::info!("Opening desktop installer: {}", p.display());+ app_handle+ .opener()+ .open_path(path, None::<&str>)+ .map_err(|e| format!("UPDATE_OPEN: {e}"))+}++/// 关于对话框信息。+#[derive(Debug, Clone, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct DesktopAboutInfo {+ pub version: String,+ pub published_at: String,+ pub copyright: String,+ pub repo: String,+ pub powered_by: String,+}++/// 关于信息:版本来自编译常量,发布时间复用最近一次 Release 查询结果。+/// 缓存为空(如尚未触发任何轮询)时做一次尽力查询填充,失败则留空、不影响展示。+pub async fn about() -> DesktopAboutInfo {+ let cache_empty = CACHE+ .get()+ .map_or(true, |m| m.lock().map(|g| g.is_none()).unwrap_or(true));+ if cache_empty {+ let _ = fetch_latest_release().await;+ }+ let published_at = CACHE+ .get()+ .and_then(|m| m.lock().ok())+ .and_then(|g| g.as_ref().map(|e| e.published_at.clone()))+ .unwrap_or_default();+ DesktopAboutInfo {+ version: current_version(),+ published_at,+ copyright: COPYRIGHT.to_string(),+ repo: REPO_URL.to_string(),+ powered_by: POWERED_BY.to_string(),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parse_version_strips_v_prefix() {+ assert_eq!(parse_version("v0.5.2").as_deref(), Some(&[0u64, 5, 2][..]));+ assert_eq!(parse_version("0.5.2").as_deref(), Some(&[0u64, 5, 2][..]));+ assert_eq!(parse_version("0.5").as_deref(), Some(&[0u64, 5][..]));+ assert_eq!(parse_version("abc"), None);+ }++ #[test]+ fn is_newer_compares_segments() {+ assert!(is_newer("0.5.2", "0.5.1"));+ assert!(is_newer("1.0.0", "0.9.0"));+ assert!(is_newer("0.5.0", "0.5"));+ assert!(!is_newer("0.5.1", "0.5.2"));+ assert!(!is_newer("0.5.1", "0.5.1"));+ assert!(!is_newer("0.5.1", "1.0.0"));+ }++ #[test]+ fn is_newer_ignores_unparseable() {+ assert!(!is_newer("abc", "0.5.1"));+ assert!(!is_newer("0.5.1", "abc"));+ }++ #[test]+ fn pick_asset_prefers_matching_suffix() {+ let mk = |name: &str, url: &str| {+ serde_json::json!({ "name": name, "browser_download_url": url })+ };+ #[cfg(target_os = "windows")]+ {+ let assets = vec![+ mk("app-x86_64-setup.exe", "https://x/exe"),+ mk("app.msi", "https://x/msi"),+ ];+ let (name, url) = pick_asset(&assets).unwrap();+ assert_eq!(name, "app.msi");+ assert_eq!(url, "https://x/msi");+ }+ #[cfg(target_os = "macos")]+ {+ let assets = vec![mk("app.dmg", "https://x/dmg"), mk("app-x86_64.tar.gz", "https://x/tgz")];+ let (name, url) = pick_asset(&assets).unwrap();+ assert_eq!(name, "app.dmg");+ assert_eq!(url, "https://x/dmg");+ }+ let no_match: Vec<serde_json::Value> = vec![mk("README.md", "https://x/readme")];+ assert!(pick_asset(&no_match).is_none());+ assert!(pick_asset(&[]).is_none());+ }+}diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex c3bb0ab5..d1a5af62 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -27,7 +27,7 @@],"resources": ["resources/**/*"],"category": "DeveloperTool",- "copyright": "Copyright © 2026 deepseek-harness-desktop contributors",+ "copyright": "Copyright © 2026 Deepseek Harness Desktop contributors","shortDescription": "Desktop application for DeepSeek Harness","longDescription": "A native desktop application for running DeepSeek Harness (dsh) locally with one-click install and zero configuration."}diff --git a/src/app.tsx b/src/app.tsxindex 1fb4aed2..9edee009 100644--- a/src/app.tsx+++ b/src/app.tsx@@ -1,5 +1,8 @@import { useEffect } from 'react'import { useStore } from 'valtio-define'+import DesktopAboutDialog from './components/desktop-about-dialog'+import DesktopUpdateDialog from './components/desktop-update-dialog'+import DesktopUpdater from './components/desktop-updater'import DownloadToast from './components/download-toast'import HarnessUpdater from './components/harness-updater'import HarnessWebview from './components/harness-webview'@@ -24,6 +27,9 @@ export default function App() {<HarnessWebview />{status === 'ready' && <HarnessUpdater />}{status === 'ready' && <DownloadToast />}+ <DesktopUpdater />+ <DesktopUpdateDialog />+ <DesktopAboutDialog /></div>)}diff --git a/src/components/desktop-about-dialog.tsx b/src/components/desktop-about-dialog.tsxnew file mode 100644index 00000000..36d1bd4c--- /dev/null+++ b/src/components/desktop-about-dialog.tsx@@ -0,0 +1,90 @@+import { ArrowUpRightFromSquare } from '@gravity-ui/icons'+import { Button, Description, Modal, useOverlayState } from '@heroui/react'+import { invoke } from '@tauri-apps/api/core'+import { useTranslation } from 'react-i18next'+import { useStore } from 'valtio-define'+import { desktopUpdate } from '../store/modules/desktop-update'++/**+ * 「关于 Desktop」对话框:展示 Powered by、版本号、发布时间与版权信息。+ */+export default function DesktopAboutDialog() {+ const { t } = useTranslation()+ const { about, aboutDialogOpen } = useStore(desktopUpdate)++ const state = useOverlayState({+ isOpen: aboutDialogOpen,+ onOpenChange: (open) => {+ if (!open)+ desktopUpdate.closeAbout()+ },+ })++ return (+ <Modal state={state}>+ <Modal.Backdrop>+ <Modal.Container size="xs">+ <Modal.Dialog>+ <Modal.CloseTrigger />+ <Modal.Body className="space-y-3">+ <div className="flex flex-col items-center gap-2 pt-1 text-center">+ <img src="/favicon.svg" alt={t('about.title')} className="w-12 h-12 rounded-md" />++ <div className="text-base font-semibold text-ink">+ {about?.powered_by ?? 'DeepSeek Harness Desktop'}+ </div>+ <Description className="text-xs">+ {t('about.powered_by', { name: about?.powered_by ?? 'Hairy & DeepSeek' })}+ </Description>+ </div>+ <div className="space-y-1.5 border-t border-line/40 pt-3">+ <div className="flex items-center justify-between text-sm">+ <span className="text-muted">{t('ui.current_version')}</span>+ <span className="text-ink font-medium">{about?.version ?? '-'}</span>+ </div>+ <div className="flex items-center justify-between text-sm">+ <span className="text-muted">{t('about.release_date')}</span>+ <span className="text-ink">+ {about?.published_at ? formatDate(about.published_at) : '-'}+ </span>+ </div>+ <div className="flex items-center justify-between text-sm border-t border-line/40 pt-2 ">+ <span className="text-muted">{t('about.source_code')}</span>+ <Button+ variant="ghost"+ size="sm"+ className="rounded-md h-8"+ onPress={() => {+ if (about?.repo)+ void invoke('open_external_url', { url: about.repo })+ }}+ >+ {t('about.github')}+ <ArrowUpRightFromSquare />+ </Button>+ </div>+ <Description className="text-xs pt-2 flex justify-center text-center">+ {about?.copyright ?? '-'}+ </Description>+ </div>++ </Modal.Body>++ </Modal.Dialog>+ </Modal.Container>+ </Modal.Backdrop>+ </Modal>+ )+}++function formatDate(iso: string): string {+ try {+ const d = new Date(iso)+ if (Number.isNaN(d.getTime()))+ return iso+ return d.toLocaleDateString()+ }+ catch {+ return iso+ }+}diff --git a/src/components/desktop-update-dialog.tsx b/src/components/desktop-update-dialog.tsxnew file mode 100644index 00000000..3f7b2940--- /dev/null+++ b/src/components/desktop-update-dialog.tsx@@ -0,0 +1,93 @@+import { Button, Description, Modal, ProgressBar, useOverlayState } from '@heroui/react'+import { useTranslation } from 'react-i18next'+import { If } from 'react-if-lite'+import { useStore } from 'valtio-define'+import { desktopUpdate } from '../store/modules/desktop-update'++/**+ * 「检查更新」对话框:展示新版本信息 + 下载进度。+ * 已下载 → 「打开安装包」直接启动安装器;未下载 → 「立即更新」下载完成后自动打开。+ */+export default function DesktopUpdateDialog() {+ const { t } = useTranslation()+ const { updateInfo, downloading, downloadProgress, updateDialogOpen } = useStore(desktopUpdate)++ const state = useOverlayState({+ isOpen: updateDialogOpen,+ onOpenChange: (open) => {+ if (!open)+ desktopUpdate.closeUpdateDialog()+ },+ })++ return (+ <Modal state={state}>+ <Modal.Backdrop isDismissable={!downloading}>+ <Modal.Container size="sm">+ <Modal.Dialog>+ <Modal.Header>+ <Modal.Heading>{t('update.desktop_title')}</Modal.Heading>+ <Modal.CloseTrigger isDisabled={downloading} />+ </Modal.Header>+ <Modal.Body className="space-y-3">+ <If cond={updateInfo != null}>+ <div className="space-y-1.5">+ <div className="flex items-center justify-between text-sm">+ <span className="text-muted">{t('ui.current_version')}</span>+ <span className="text-ink font-medium">{updateInfo?.version}</span>+ </div>+ <div className="flex items-center justify-between text-sm">+ <span className="text-muted">{t('update.new_version_label')}</span>+ <span className="text-ink font-medium">{updateInfo?.tag}</span>+ </div>+ <If cond={updateInfo?.downloaded}>+ <Description className="text-xs">+ {t('update.desktop_downloaded')}+ </Description>+ </If>+ </div>+ </If>++ <If cond={downloading}>+ <div className="space-y-1">+ <div className="flex justify-between text-xs text-muted">+ <span>{t('update.desktop_downloading')}</span>+ <span className="shrink-0">+ {Math.round(downloadProgress)}+ %+ </span>+ </div>+ <ProgressBar value={downloadProgress} className="w-full">+ <ProgressBar.Track>+ <ProgressBar.Fill className="bg-accent" />+ </ProgressBar.Track>+ </ProgressBar>+ </div>+ </If>+ </Modal.Body>+ <Modal.Footer>+ <Button+ variant="tertiary"+ className="rounded-md"+ isDisabled={downloading}+ onPress={desktopUpdate.closeUpdateDialog}+ >+ {t('update.later')}+ </Button>+ <Button+ variant="primary"+ className="rounded-md"+ isDisabled={downloading || updateInfo == null}+ onPress={() => desktopUpdate.downloadAndOpen()}+ >+ {updateInfo?.downloaded+ ? t('update.open_installer')+ : t('update.now')}+ </Button>+ </Modal.Footer>+ </Modal.Dialog>+ </Modal.Container>+ </Modal.Backdrop>+ </Modal>+ )+}diff --git a/src/components/desktop-updater.tsx b/src/components/desktop-updater.tsxnew file mode 100644index 00000000..d1831bf1--- /dev/null+++ b/src/components/desktop-updater.tsx@@ -0,0 +1,51 @@+import { useWatch } from '@hairy/react-lib'+import { useEffect } from 'react'+import { useTranslation } from 'react-i18next'+import { useStore } from 'valtio-define'+import { toast } from '@/utils'+import { desktopUpdate } from '../store/modules/desktop-update'++/** 桌面端自更新轮询间隔:每 10 秒检查一次(Rust 侧带缓存,不重复打网络) */+const POLL_INTERVAL = 10_000++/**+ * 桌面端「发现新版本」提示:后台每 10 秒轮询,发现新版本时在右下角弹 toast。+ * 用户关闭后记住该版本,本次会话不再弹出;新版本出现仍会再次提示。+ */+export default function DesktopUpdater() {+ const { t } = useTranslation()+ const { updateInfo, dismissedTag, downloading, updateDialogOpen } = useStore(desktopUpdate)++ // 每 10 秒静默检查一次新版本+ useEffect(() => {+ void desktopUpdate.check()+ const timer = setInterval(() => {+ void desktopUpdate.check()+ }, POLL_INTERVAL)+ return () => clearInterval(timer)+ }, [])++ useWatch([updateInfo, dismissedTag, downloading, updateDialogOpen], () => {+ if (!updateInfo || downloading || updateDialogOpen)+ return+ // 用户已关闭过该版本提示 → 不再弹出+ if (updateInfo.tag === dismissedTag)+ return+ toast(t('update.available', { tag: updateInfo.tag }), {+ actionProps: {+ children: t('update.now'),+ onPress: () => {+ toast.clear()+ void desktopUpdate.downloadAndOpen()+ },+ variant: 'tertiary',+ },+ placement: 'bottom end',+ description: t('update.desktop_new'),+ variant: 'default',+ onClose: () => desktopUpdate.dismissToast(),+ })+ }, { immediate: true })++ return null+}diff --git a/src/components/navbar.tsx b/src/components/navbar.tsxindex 5800b933..a7fb7171 100644--- a/src/components/navbar.tsx+++ b/src/components/navbar.tsx@@ -6,15 +6,16 @@ import {LayoutSideContentLeft,Minus,Square,- Wrench,Xmark,} from '@gravity-ui/icons'-import { Button } from '@heroui/react'+import { Button, Description, Dropdown, Label } from '@heroui/react'import { getCurrentWindow } from '@tauri-apps/api/window'import { useTranslation } from 'react-i18next'import { If } from 'react-if-lite'+import { useStore } from 'valtio-define'import { useDshPlugins } from '../hooks/use-dsh-plugins'import { useIframeTauri } from '../hooks/use-iframe-tauri'+import { desktopUpdate } from '../store/modules/desktop-update'import { DebugSidebar } from './debug-sidebar'/**@@ -52,6 +53,7 @@ export default function Navbar({ iframeRef }: NavbarProps) {const { t } = useTranslation()const { plugins } = useDshPlugins()const { sidebarCollapsed, canGoBack, canGoForward, sendNav } = useIframeTauri(iframeRef)+ const { updateInfo } = useStore(desktopUpdate)// 仅当 dsh-tauri 插件启用(已安装)时显示左侧导航控件const tauriEnabled = plugins.some(plugin => plugin.id === TAURI_PLUGIN_ID)function handleWindowAction(action: 'minimize' | 'maximize' | 'background') {@@ -70,6 +72,13 @@ export default function Navbar({ iframeRef }: NavbarProps) {}}+ function handleHelpAction(key: string) {+ if (key === 'check-update')+ void desktopUpdate.openUpdateDialog()+ else if (key === 'about')+ void desktopUpdate.openAbout()+ }+return (<div className="relative flex h-11 w-full flex-none select-none items-center gap-0.5 border-b border-line px-1.5 bg-[#f9fafb] dark:bg-[#1b1b1c]"><If cond={iframeRef != null && tauriEnabled}>@@ -111,18 +120,54 @@ export default function Navbar({ iframeRef }: NavbarProps) {><ArrowRight /></Button>- <DebugSidebar>- <Button- className="rounded-lg size-7"- isIconOnly- size="sm"- variant="ghost"- aria-label={t('app.expand_sidebar')}- >- <Wrench />- </Button>- </DebugSidebar>+ <div className="ml-1">+ <DebugSidebar>+ <Button+ className="rounded-lg h-6 text-xs px-1.5"+ size="sm"+ variant="ghost"+ aria-label={t('app.expand_sidebar')}+ >+ {t('app.debug')}+ </Button>+ </DebugSidebar>+ <Dropdown>+ <Button+ className="rounded-lg h-6 text-xs px-1.5"+ size="sm"+ variant="ghost"+ aria-label={t('app.expand_sidebar')}+ >+ {t('app.help')}+ </Button>+ <Dropdown.Popover className="rounded-md w-5!">+ <Dropdown.Menu>+ <Dropdown.Item+ className="rounded-md"+ id="check-update"+ textValue={t('menu.check_update')}+ onAction={() => handleHelpAction('check-update')}+ >+ <span className="flex w-full items-center justify-between gap-3">+ <Label>{t('menu.check_update')}</Label>+ <If cond={updateInfo != null}>+ <Description>{t('menu.new_version')}</Description>+ </If>+ </span>+ </Dropdown.Item>+ <Dropdown.Item+ className="rounded-md"+ id="about"+ textValue={t('menu.about')}+ onAction={() => handleHelpAction('about')}+ >+ <Label>{t('menu.about')}</Label>+ </Dropdown.Item>+ </Dropdown.Menu>+ </Dropdown.Popover>+ </Dropdown>+ </div></If>{/* 拖拽区:Tauri 原生拖拽(仅此元素带 data-tauri-drag-region,按钮不受影响) */}diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex de0fbd5b..e1c93e35 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -46,6 +46,24 @@"update.available": "A new version {{tag}} is available. Update now?","update.now": "Update Now","update.later": "Later",+ "update.up_to_date": "You're up to date",+ "update.desktop_title": "New version available",+ "update.new_version_label": "New version",+ "update.desktop_downloaded": "Installer already downloaded — ready to open",+ "update.desktop_downloading": "Downloading installer",+ "update.open_installer": "Open Installer",+ "update.desktop_new": "A new version is available. Update now?",+ "update.desktop_download_failed": "Failed to download the installer",+ "update.desktop_opened": "Installer opened — follow the prompts to complete the update",+ "update.desktop_open_failed": "Failed to open the installer",+ "menu.check_update": "Check for Updates",+ "menu.new_version": "New version available",+ "menu.about": "About Desktop",+ "about.title": "About",+ "about.powered_by": "Powered by {{name}}",+ "about.release_date": "Release date",+ "about.github": "GitHub",+ "about.source_code": "Source Code","download.saved": "Session log saved","download.saved_to": "Saved to","download.failed": "Session log download failed",@@ -109,5 +127,7 @@"nav.maximize": "Maximize","nav.background": "Background","app.debug_sidebar_title": "Application Debug",- "messages.logs_copied": "Logs copied to clipboard"+ "messages.logs_copied": "Logs copied to clipboard",+ "app.debug": "Debug",+ "app.help": "Help"}diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex def2051d..aa69fdc1 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -46,6 +46,24 @@"update.available": "发现新版本 {{tag}},是否立即更新?","update.now": "立即更新","update.later": "稍后",+ "update.up_to_date": "已是最新版本",+ "update.desktop_title": "发现新版本",+ "update.new_version_label": "新版本",+ "update.desktop_downloaded": "安装包已下载,可直接打开",+ "update.desktop_downloading": "正在下载安装包",+ "update.open_installer": "打开安装包",+ "update.desktop_new": "存在新版本,立即更新?",+ "update.desktop_download_failed": "安装包下载失败",+ "update.desktop_opened": "已打开安装包,请按提示完成安装",+ "update.desktop_open_failed": "打开安装包失败",+ "menu.check_update": "检查更新",+ "menu.new_version": "存在新版本",+ "menu.about": "关于 Desktop",+ "about.title": "关于",+ "about.powered_by": "由 {{name}} 驱动",+ "about.release_date": "发布时间",+ "about.github": "GitHub",+ "about.source_code": "源代码","download.saved": "Session 日志已保存","download.saved_to": "已保存到","download.failed": "Session 日志下载失败",@@ -109,5 +127,7 @@"nav.maximize": "最大化","nav.background": "后台化","app.debug_sidebar_title": "应用调试",- "messages.logs_copied": "日志已复制到剪贴板"+ "messages.logs_copied": "日志已复制到剪贴板",+ "app.debug": "调试",+ "app.help": "帮助"}diff --git a/src/store/index.ts b/src/store/index.tsindex 89b64038..6e94eaa2 100644--- a/src/store/index.ts+++ b/src/store/index.ts@@ -1,3 +1,4 @@+import { desktopUpdate } from './modules/desktop-update'import { download } from './modules/download'import { harness } from './modules/harness'import { setting } from './modules/setting'@@ -9,8 +10,15 @@ export const store = {updater,download,setting,+ desktopUpdate,}+export { desktopUpdate } from './modules/desktop-update'+export type {+ DesktopAboutInfo,+ DesktopDownloadProgress,+ DesktopUpdateInfo,+} from './modules/desktop-update'export { download } from './modules/download'export type { DownloadFinishedPayload } from './modules/download'export { harness } from './modules/harness'diff --git a/src/store/modules/desktop-update/index.ts b/src/store/modules/desktop-update/index.tsnew file mode 100644index 00000000..7771cf93--- /dev/null+++ b/src/store/modules/desktop-update/index.ts@@ -0,0 +1,6 @@+export { desktopUpdate } from './store'+export type {+ DesktopAboutInfo,+ DesktopDownloadProgress,+ DesktopUpdateInfo,+} from './types'diff --git a/src/store/modules/desktop-update/store.ts b/src/store/modules/desktop-update/store.tsnew file mode 100644index 00000000..24d49ee1--- /dev/null+++ b/src/store/modules/desktop-update/store.ts@@ -0,0 +1,192 @@+import type {+ DesktopAboutInfo,+ DesktopDownloadProgress,+ DesktopUpdateInfo,+} from './types'+import { invoke } from '@tauri-apps/api/core'+import { listen } from '@tauri-apps/api/event'+import i18next from 'i18next'+import { defineStore } from 'valtio-define'+import { toast } from '@/utils'++const DISMISS_KEY = 'desktop-update-dismissed-tag'++/**+ * 桌面端自更新模块:检查新版本 → 弹出更新对话框 → 下载安装包 → 打开安装器。+ *+ * 与 `updater` 模块(dsh 内核更新)区分:本模块针对桌面应用自身。+ * 轮询检查每 10 秒触发一次(见 components/desktop-updater),命中 Rust 侧+ * 缓存后不重复打网络,避免 GitHub 未认证限流。+ */+function readDismissedTag(): string {+ try {+ return localStorage.getItem(DISMISS_KEY) ?? ''+ }+ catch {+ return ''+ }+}++export const desktopUpdate = defineStore({+ state: () => ({+ /** 发现的新版本信息(null 表示暂无) */+ updateInfo: null as DesktopUpdateInfo | null,+ /** 是否正在检查更新(避免并发/重复) */+ checking: false,+ /** 是否正在下载安装包 */+ downloading: false,+ /** 下载进度 0-100 */+ downloadProgress: 0,+ /** 更新对话框开关 */+ updateDialogOpen: false,+ /** 关于对话框开关 */+ aboutDialogOpen: false,+ /** 关于对话框信息 */+ about: null as DesktopAboutInfo | null,+ /** 用户已关闭提示的版本 tag(持久化,同版本不再弹 toast) */+ dismissedTag: readDismissedTag(),+ }),+ actions: {+ /**+ * 检查是否有新版本。+ * 轮询与「检查更新」共用;仅在 tag 变化时更新 updateInfo,+ * 既避免重复弹 toast,也让菜单「存在新版本」指示实时反映。+ */+ async check(): Promise<DesktopUpdateInfo | null> {+ if (this.checking)+ return this.updateInfo+ this.checking = true+ try {+ const info = await invoke<DesktopUpdateInfo | null>('check_desktop_update')+ if (info) {+ if (this.updateInfo?.tag !== info.tag)+ this.updateInfo = info+ }+ else {+ this.updateInfo = null+ }+ return info+ }+ catch (err) {+ console.warn('[DesktopUpdate] check skipped:', err)+ return this.updateInfo+ }+ finally {+ this.checking = false+ }+ },++ /** 用户关闭 toast 提示:记住该版本,本次会话不再弹出 */+ dismissToast() {+ const tag = this.updateInfo?.tag+ if (!tag)+ return+ this.dismissedTag = tag+ try {+ localStorage.setItem(DISMISS_KEY, tag)+ }+ catch {+ /* 忽略持久化失败 */+ }+ },++ /** 打开更新对话框(「检查更新」菜单):先检查,有更新才弹框,否则提示已是最新 */+ async openUpdateDialog() {+ this.updateDialogOpen = true++ if (!this.updateInfo)+ await this.check()+ if (this.updateInfo) {+ this.updateDialogOpen = true+ }+ else {+ toast(i18next.t('update.up_to_date'), { variant: 'default' })+ }+ },++ closeUpdateDialog() {+ this.updateDialogOpen = false+ },++ /** 打开关于对话框:拉取信息后展示 */+ async openAbout() {+ if (!this.about) {+ try {+ this.about = await invoke<DesktopAboutInfo>('get_desktop_about')+ }+ catch (err) {+ console.warn('[DesktopUpdate] failed to load about info:', err)+ }+ }+ this.aboutDialogOpen = true+ },++ closeAbout() {+ this.aboutDialogOpen = false+ },++ /**+ * 下载并打开安装包:已下载则直接打开;+ * 否则监听进度流式下载,完成后自动打开安装器。+ */+ async downloadAndOpen() {+ if (this.downloading)+ return+ const info = this.updateInfo+ if (!info)+ return++ // 已下载 → 直接打开安装包+ if (info.downloaded) {+ await this.openInstaller(info.path)+ return+ }++ this.downloading = true+ this.downloadProgress = 0+ try {+ const updated = await invoke<DesktopUpdateInfo>('download_desktop_update')+ this.updateInfo = updated+ if (updated.downloaded)+ await this.openInstaller(updated.path)+ }+ catch (err) {+ console.error('[DesktopUpdate] download failed:', err)+ toast(i18next.t('update.desktop_download_failed'), {+ variant: 'danger',+ placement: 'bottom end',+ })+ }+ finally {+ this.downloading = false+ this.downloadProgress = 0+ }+ },++ /** 打开安装包并收尾(关对话框 + 提示) */+ async openInstaller(path: string) {+ try {+ await invoke('open_desktop_installer', { path })+ this.closeUpdateDialog()+ toast(i18next.t('update.desktop_opened'), {+ variant: 'default',+ placement: 'bottom end',+ })+ }+ catch (err) {+ console.error('[DesktopUpdate] failed to open installer:', err)+ toast(i18next.t('update.desktop_open_failed'), {+ variant: 'danger',+ placement: 'bottom end',+ })+ }+ },+ },+})++// 模块级监听下载进度(应用生命周期内常驻)+listen<DesktopDownloadProgress>('desktop-update-progress', (e) => {+ desktopUpdate.downloadProgress = e.payload.percentage+}).catch((err) => {+ console.error('[DesktopUpdate] failed to listen desktop-update-progress:', err)+})diff --git a/src/store/modules/desktop-update/types.ts b/src/store/modules/desktop-update/types.tsnew file mode 100644index 00000000..c54ef039--- /dev/null+++ b/src/store/modules/desktop-update/types.ts@@ -0,0 +1,26 @@+/** Rust 侧 check_desktop_update 返回的桌面端新版本信息 */+export interface DesktopUpdateInfo {+ version: string+ tag: string+ published_at: string+ url: string+ asset_name: string+ path: string+ downloaded: boolean+}++/** Rust 侧 desktop-update-progress 事件载荷 */+export interface DesktopDownloadProgress {+ percentage: number+ downloaded: number+ total: number+}++/** Rust 侧 get_desktop_about 返回的关于信息 */+export interface DesktopAboutInfo {+ version: string+ published_at: string+ copyright: string+ repo: string+ powered_by: string+}