🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(desktop): unified update channel switching with S3 distribution (#12644)
Innei9cb0560ebf3c
diff --git a/.github/workflows/pr-build-desktop.yml b/.github/workflows/pr-build-desktop.ymlindex 7067620a4c3..8e58fdc9197 100644--- a/.github/workflows/pr-build-desktop.yml+++ b/.github/workflows/pr-build-desktop.yml@@ -129,6 +129,7 @@ jobs:env:# 设置更新通道,PR构建为nightly,否则为stableUPDATE_CHANNEL: 'nightly'+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}APP_URL: http://localhost:3015DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'# 默认添加一个加密 SECRET@@ -153,6 +154,7 @@ jobs:env:# 设置更新通道,PR构建为nightly,否则为stableUPDATE_CHANNEL: 'nightly'+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}APP_URL: http://localhost:3015DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='@@ -169,6 +171,7 @@ jobs:env:# 设置更新通道,PR构建为nightly,否则为stableUPDATE_CHANNEL: 'nightly'+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}APP_URL: http://localhost:3015DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='diff --git a/.github/workflows/release-desktop-canary.yml b/.github/workflows/release-desktop-canary.ymlindex 44ea457d29b..761654c223e 100644--- a/.github/workflows/release-desktop-canary.yml+++ b/.github/workflows/release-desktop-canary.yml@@ -187,6 +187,7 @@ jobs:run: npm run desktop:package:appenv:UPDATE_CHANNEL: canary+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}APP_URL: http://localhost:3015DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='@@ -205,6 +206,7 @@ jobs:run: npm run desktop:package:appenv:UPDATE_CHANNEL: canary+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}APP_URL: http://localhost:3015DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='@@ -219,6 +221,7 @@ jobs:run: npm run desktop:package:appenv:UPDATE_CHANNEL: canary+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}APP_URL: http://localhost:3015DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='diff --git a/.github/workflows/release-desktop-nightly.yml b/.github/workflows/release-desktop-nightly.ymlindex 0508c824b00..aa6da70cf3b 100644--- a/.github/workflows/release-desktop-nightly.yml+++ b/.github/workflows/release-desktop-nightly.yml@@ -182,6 +182,7 @@ jobs:run: npm run desktop:package:appenv:UPDATE_CHANNEL: nightly+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}APP_URL: http://localhost:3015DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='@@ -200,6 +201,7 @@ jobs:run: npm run desktop:package:appenv:UPDATE_CHANNEL: nightly+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}APP_URL: http://localhost:3015DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='@@ -214,6 +216,7 @@ jobs:run: npm run desktop:package:appenv:UPDATE_CHANNEL: nightly+ UPDATE_SERVER_URL: ${{ secrets.UPDATE_SERVER_URL }}APP_URL: http://localhost:3015DATABASE_URL: 'postgresql://postgres@localhost:5432/postgres'KEY_VAULTS_SECRET: 'oLXWIiR/AKF+rWaqy9lHkrYgzpATbW3CtJp3UfkVgpE='diff --git a/.github/workflows/release-desktop-stable.yml b/.github/workflows/release-desktop-stable.ymlindex 2daafaa18b3..f584ba19c26 100644--- a/.github/workflows/release-desktop-stable.yml+++ b/.github/workflows/release-desktop-stable.yml@@ -294,7 +294,7 @@ jobs:fibun add --no-save [email protected]- - name: Merge latest-mac.yml files+ - name: Merge mac YAML filesrun: bun run scripts/electronWorkflow/mergeMacReleaseFiles.js- name: Upload artifacts with merged macOS filesdiff --git a/apps/desktop/dev-app-update.yml b/apps/desktop/dev-app-update.ymlindex 0d3c70a026e..dc2048fe3a2 100644--- a/apps/desktop/dev-app-update.yml+++ b/apps/desktop/dev-app-update.yml@@ -1,16 +1,15 @@-# 开发环境更新配置-# 可选择 GitHub 或 Generic provider 进行测试+# 本地更新测试配置+# 将此文件复制到 apps/desktop/dev-app-update.yml 以使用本地服务器测试+#+# 注意: 此配置仅用于应用初始启动时的 provider 配置。+# Channel 切换功能通过 UPDATE_SERVER_URL 环境变量 + setFeedURL() 实现,+# 不依赖此文件。+#+# 使用方法:+# cp scripts/update-test/dev-app-update.local.yml dev-app-update.yml+# UPDATE_SERVER_URL=http://localhost:8787 bun run dev-# 方式1: GitHub Provider (默认)-provider: github-owner: lobehub-repo: lobe-chat-updaterCacheDirName: electron-app-updater-allowPrerelease: true-channel: nightly--# 方式2: Generic Provider (测试自定义服务器)-# 取消下面的注释,注释掉上面的 GitHub 配置-# provider: generic-# url: http://localhost:8080-# updaterCacheDirName: electron-app-updater+provider: generic+url: http://localhost:8787/stable+updaterCacheDirName: lobehub-desktop-local-test+channel: stablediff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjsindex 9e63a1b25bd..a13e80e7400 100644--- a/apps/desktop/electron-builder.mjs+++ b/apps/desktop/electron-builder.mjs@@ -25,39 +25,46 @@ const hasAppleCertificate = Boolean(process.env.CSC_LINK);// 自定义更新服务器 URL (用于 stable 频道)const updateServerUrl = process.env.UPDATE_SERVER_URL;-console.log(`🚄 Build Version ${packageJSON.version}, Channel: ${channel}`);-console.log(`🏗️ Building for architecture: ${arch}`);+console.info(`🚄 Build Version ${packageJSON.version}, Channel: ${channel}`);+console.info(`🏗️ Building for architecture: ${arch}`);// Channel identity derived solely from UPDATE_CHANNEL env var.-// Adding a new channel won't break stable detection.+// Supported channels: stable, nightly, canaryconst isStable = !channel || channel === 'stable';const isNightly = channel === 'nightly';-const isBeta = channel === 'beta';+const isCanary = channel === 'canary';-// 根据 channel 配置不同的 publish provider-// - Stable + UPDATE_SERVER_URL: 使用 generic (自定义 HTTP 服务器)-// - Beta/Nightly: 仅使用 GitHub+// Strip trailing channel path from URL for re-appending the correct channel+// Handles both base URL (https://cdn.example.com) and legacy URL with channel (https://cdn.example.com/stable)+const stripChannelSuffix = (url) => url.replace(/\/(stable|nightly|canary|beta)\/?$/, '');++// 根据 channel 配置 publish provider+// - 所有渠道 + UPDATE_SERVER_URL: 使用 generic (S3)+// - 无 UPDATE_SERVER_URL: 回退到 GitHub (本地开发)const getPublishConfig = () => {- const githubProvider = {- owner: 'lobehub',- provider: 'github',- repo: 'lobe-chat',- };-- // Stable channel: 使用自定义服务器 (generic provider)- if (isStable && updateServerUrl) {- console.log(`📦 Stable channel: Using generic provider (${updateServerUrl})`);- const genericProvider = {- provider: 'generic',- url: updateServerUrl,- };- // 同时发布到自定义服务器和 GitHub (GitHub 作为备用/镜像)- return [genericProvider, githubProvider];+ const channelPath = isStable ? 'stable' : isNightly ? 'nightly' : channel || 'stable';++ if (updateServerUrl) {+ const baseUrl = stripChannelSuffix(updateServerUrl);+ const fullUrl = `${baseUrl}/${channelPath}`;+ console.info(`📦 ${channelPath} channel: Using generic provider (${fullUrl})`);+ return [+ {+ provider: 'generic',+ url: fullUrl,+ },+ ];}- // Beta/Nightly channel: 仅使用 GitHub- console.log(`📦 ${channel || 'default'} channel: Using GitHub provider`);- return [githubProvider];+ // 本地开发无 S3 时回退到 GitHub+ console.info(`📦 ${channelPath} channel: No UPDATE_SERVER_URL, falling back to GitHub provider`);+ return [+ {+ owner: 'lobehub',+ provider: 'github',+ repo: 'lobehub',+ },+ ];};// Keep only these Electron Framework localization folders (*.lproj)@@ -68,14 +75,13 @@ const keepLanguages = new Set(['en', 'en_GB', 'en-US', 'en_US']);if (!hasAppleCertificate) {// Disable auto discovery to keep electron-builder from searching unavailable signing identitiesprocess.env.CSC_IDENTITY_AUTO_DISCOVERY = 'false';- console.log('⚠️ Apple certificate link not found, macOS artifacts will be unsigned.');+ console.info('⚠️ Apple certificate link not found, macOS artifacts will be unsigned.');}// 根据版本类型确定协议 schemeconst getProtocolScheme = () => {+ if (isCanary) return 'lobehub-canary';if (isNightly) return 'lobehub-nightly';- if (isBeta) return 'lobehub-beta';-return 'lobehub';};@@ -84,8 +90,7 @@ const protocolScheme = getProtocolScheme();// Determine icon file based on version typeconst getIconFileName = () => {if (isStable) return 'Icon';- if (isBeta) return 'Icon-beta';- // nightly, canary, and any future pre-release channels share nightly icon+ // nightly, canary share pre-release iconreturn 'Icon-nightly';};@@ -172,18 +177,14 @@ const config = {try {await fs.access(assetsCarSource);await fs.copyFile(assetsCarSource, assetsCarDest);- console.log(`✅ Copied Liquid Glass icon: ${iconFileName}.Assets.car`);+ console.info(`✅ Copied Liquid Glass icon: ${iconFileName}.Assets.car`);} catch {// Non-critical: Assets.car not found or copy failed// App will use fallback .icns icon on all macOS versions- console.log(`⏭️ Skipping Assets.car (not found or copy failed)`);+ console.info(`⏭️ Skipping Assets.car (not found or copy failed)`);}},- appId: isNightly- ? 'com.lobehub.lobehub-desktop-nightly'- : isBeta- ? 'com.lobehub.lobehub-desktop-beta'- : 'com.lobehub.lobehub-desktop',+ appId: 'com.lobehub.lobehub-desktop',appImage: {artifactName: '${productName}-${version}.${ext}',},diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 08b0fbbe983..8fb79b7e6ef 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -30,7 +30,7 @@"package:local": "npm run build:main && electron-builder --dir --config electron-builder.mjs --c.mac.notarize=false -c.mac.identity=null --c.asar=false","package:local:reuse": "electron-builder --dir --config electron-builder.mjs --c.mac.notarize=false -c.mac.identity=null --c.asar=false","package:mac": "npm run build:main && electron-builder --mac --config electron-builder.mjs --publish never",- "package:mac:local": "npm run build:main && cross-env UPDATE_CHANNEL=nightly electron-builder --mac --config electron-builder.mjs --publish never",+ "package:mac:local": "npm run build:main && cross-env UPDATE_CHANNEL=nightly electron-builder --mac --config electron-builder.mjs --publish never --c.mac.notarize=false -c.mac.identity=null","package:win": "npm run build:main && electron-builder --win --config electron-builder.mjs --publish never","start": "electron-vite preview","stylelint": "stylelint \"src/**/*.{js,jsx,ts,tsx}\" --fix",diff --git a/apps/desktop/scripts/update-test/.gitignore b/apps/desktop/scripts/update-test/.gitignorenew file mode 100644index 00000000000..13cd1fa7f12--- /dev/null+++ b/apps/desktop/scripts/update-test/.gitignore@@ -0,0 +1 @@+server\ No newline at end of filediff --git a/apps/desktop/scripts/update-test/README.md b/apps/desktop/scripts/update-test/README.mdindex 44ad87f26ad..89181f67d4f 100644--- a/apps/desktop/scripts/update-test/README.md+++ b/apps/desktop/scripts/update-test/README.md@@ -1,6 +1,6 @@# 本地更新测试指南-本目录包含用于在本地测试 Desktop 应用更新功能的工具和脚本。+本目录包含用于在本地测试 Desktop 应用更新功能的工具和脚本,支持 stable/nightly/canary 三渠道切换测试。## 目录结构@@ -8,98 +8,95 @@scripts/update-test/├── README.md # 本文档├── setup.sh # 一键设置脚本+├── run-test.sh # 一键启动测试(推荐)├── start-server.sh # 启动本地更新服务器├── stop-server.sh # 停止本地更新服务器├── generate-manifest.sh # 生成 manifest 和目录结构├── dev-app-update.local.yml # 本地测试用的更新配置模板└── server/ # 本地服务器文件目录 (自动生成)├── stable/ # stable 渠道- │ ├── latest-mac.yml+ │ ├── stable-mac.yml│ └── {version}/│ ├── xxx.dmg│ └── xxx.zip- ├── beta/ # beta 渠道- │ └── ...- └── nightly/ # nightly 渠道- └── ...+ ├── nightly/ # nightly 渠道+ │ ├── nightly-mac.yml+ │ └── {version}/+ │ └── ...+ └── canary/ # canary 渠道+ ├── canary-mac.yml+ └── {version}/+ └── ...```## 快速开始-### 1. 首次设置+### 一键测试(推荐)```bashcd apps/desktop/scripts/update-testchmod +x *.sh-./setup.sh+./run-test.sh```-### 2. 构建测试包--```bash-# 回到 desktop 目录-cd ../..+此脚本会自动:为三个渠道生成不同版本号的 manifest → 启动本地服务器 → 配置应用 → 启动应用。-# 构建未签名的本地测试包-bun run build:main-bun run package:local-```+### 手动步骤-如果需要模拟 CI 的渠道构建(Nightly / Beta / Stable),可以使用根目录脚本:+#### 1. 首次设置```bash-# 回到仓库根目录-cd ../../..+cd apps/desktop/scripts/update-test+chmod +x *.sh+./setup.sh+```-# 指定渠道与版本号-npm run desktop:build-channel -- nightly 2.1.0-nightly.1-npm run desktop:build-channel -- beta 2.1.0-beta.1-npm run desktop:build-channel -- stable 2.1.0+#### 2. 构建测试包-# 保留 package.json 与 icon 变更-npm run desktop:build-channel -- stable 2.1.0 --keep-changes+```bash+cd ../..+# 构建 DMG + ZIP (macOS 自动更新需要 ZIP)+bun run package:mac:local```-### 3. 生成更新文件+> **注意**: 不要使用 `package:local`,它只输出目录结构不产出 DMG/ZIP 安装包。++#### 3. 生成更新文件```bashcd scripts/update-test-# 从 release 目录自动检测并生成 (默认 stable 渠道)-./generate-manifest.sh --from-release--# 指定版本号 (用于模拟更新)-./generate-manifest.sh --from-release -v 0.0.1+# 为所有渠道生成(推荐,会自动分配不同版本号)+./generate-manifest.sh --from-release --all-channels-# 指定渠道-./generate-manifest.sh --from-release -c beta -v 2.1.0-beta.1+# 或指定单个渠道+./generate-manifest.sh --from-release -c nightly -v 2.1.0-nightly.1```-### 4. 启动本地服务器+#### 4. 启动本地服务器```bash./start-server.sh# 服务器默认在 http://localhost:8787 启动```-### 5. 配置应用使用本地服务器+#### 5. 启动应用```bash-# 复制本地测试配置到 desktop 根目录-cp dev-app-update.local.yml ../../dev-app-update.yml--# 或者直接编辑 dev-app-update.yml,确保 URL 指向正确的渠道:-# url: http://localhost:8787/stable+cd ../..+UPDATE_SERVER_URL=http://localhost:8787 bun run dev```-### 6. 运行应用测试+**重要**: 必须设置 `UPDATE_SERVER_URL` 环境变量,否则 channel 切换时 `configureUpdateProvider()` 会回退到 GitHub。-```bash-cd ../..-bun run dev-```+#### 6. 测试 Channel 切换-### 7. 测试完成后+1. 进入 **设置 > Beta**+2. 在 **Update Channel** 下拉框中选择不同渠道+3. 切换后应用会自动检查对应渠道的更新+4. 查看日志确认 feed URL 切换正确:`tail -f ~/Library/Logs/lobehub-desktop-dev/main.log`++#### 7. 测试完成后```bashcd scripts/update-test@@ -119,7 +116,8 @@ git checkout dev-app-update.yml选项:-v, --version VERSION 指定版本号 (例如: 2.0.1)- -c, --channel CHANNEL 指定渠道 (stable|beta|nightly, 默认: stable)+ -c, --channel CHANNEL 指定渠道 (stable|nightly|canary, 默认: stable)+ -a, --all-channels 为所有渠道生成 manifest (stable/nightly/canary)-d, --dmg FILE 指定 DMG 文件名-z, --zip FILE 指定 ZIP 文件名-n, --notes TEXT 指定 release notes@@ -127,80 +125,79 @@ git checkout dev-app-update.yml-h, --help 显示帮助信息示例:- ./generate-manifest.sh --from-release+ ./generate-manifest.sh --from-release --all-channels./generate-manifest.sh -v 2.0.1 -c stable --from-release- ./generate-manifest.sh -v 2.1.0-beta.1 -c beta --from-release+ ./generate-manifest.sh -v 2.1.0-nightly.1 -c nightly --from-release```----## 详细说明+## 测试场景-### 关于 macOS 签名验证+| 场景 | 操作 |+| -------------------- | ------------------------------------------------------- |+| 有新版本可用 | manifest 中 `version` 大于当前应用版本 |+| 无新版本 | `version` 小于或等于当前版本 |+| Channel 切换(升级) | 从 Stable 切到 Nightly/Canary,应检测到更高版本 |+| Channel 切换(降级) | 从 Canary 切到 Stable,`allowDowngrade` 应自动设为 true |+| 下载失败 | 删除 server/{channel}/{version}/ 中的 DMG 文件 |+| 网络错误 | 停止本地服务器 |+| Manifest 不存在 | 删除对应的 {channel}-mac.yml |-本地测试的包未经签名和公证,macOS 会阻止运行。解决方法:+---++## 关于 macOS 签名验证++### Gatekeeper-#### 方法 1:临时禁用 Gatekeeper(推荐)+本地测试的包未经签名和公证,macOS 会阻止运行。解决方法:```bash-# 禁用+# 临时禁用 Gatekeeper(推荐,测试完成后务必重新启用)sudo spctl --master-disable-# 测试完成后务必重新启用!+# 测试完成后sudo spctl --master-enable```-#### 方法 2:手动移除隔离属性+或手动移除隔离属性:```bash-# 对下载的 DMG 或解压后的 .app 执行xattr -cr /path/to/YourApp.app```-#### 方法 3:系统偏好设置--1. 打开「系统偏好设置」→「安全性与隐私」→「通用」-2. 点击「仍要打开」允许未签名的应用--### 自定义 Release Notes+### Squirrel.Mac 更新安装限制-编辑 `server/{channel}/latest-mac.yml` 中的 `releaseNotes` 字段:+**本地未签名构建无法完成更新的安装步骤。** Squirrel.Mac 要求更新包的签名与当前运行 app 的 designated requirement 匹配。ad-hoc 签名的 DR 包含 `cdhash`(二进制哈希),不同构建的哈希必定不同,因此校验必然失败。-```yaml-releaseNotes: |- ## 🎉 v2.0.1 测试版本+这意味着本地测试能验证到 **下载完成** 为止,但无法安装。CI 中有真实 Apple Developer 证书,不存在此问题。- ### ✨ 新功能- - 功能 A- - 功能 B+**可验证的部分(通过日志):**- ### 🐛 修复- - 修复问题 X+```bash+tail -f ~/Library/Logs/lobehub-desktop-dev/main.log | grep -E 'Switching|Configuring|channel|checking'```-### 测试不同场景+- Channel 切换: `Switching update channel: stable -> canary`+- Feed URL 切换: `Configuring generic provider for canary channel`+- Manifest 匹配: `Channel set to: canary (will look for canary-mac.yml)`+- 更新检测: `Update available: x.y.z` 或 `Update not available`-| 场景 | 操作 |-| ------------ | ----------------------------------------------------- |-| 有新版本可用 | 设置 manifest 中的 `version` 大于当前应用版本 (0.0.0) |-| 无新版本 | 设置 `version` 小于或等于当前版本 |-| 下载失败 | 删除 server/{channel}/{version}/ 中的 DMG 文件 |-| 网络错误 | 停止本地服务器 |-| 测试不同渠道 | 修改 dev-app-update.yml 中的 URL 指向不同渠道 |+----### 环境变量+## 故障排除-也可以通过环境变量指定更新服务器:+### 1. Channel 切换后仍请求旧渠道-```bash-UPDATE_SERVER_URL=http://localhost:8787/stable bun run dev-```+- 确认启动应用时设置了 `UPDATE_SERVER_URL=http://localhost:8787`+- 查看日志确认 `configureUpdateProvider` 被调用:`grep 'Configuring generic' ~/Library/Logs/lobehub-desktop-dev/main.log`----+### 2. 更新检测不到-## 故障排除+- 确认对应渠道的 manifest 存在:`curl http://localhost:8787/stable/stable-mac.yml`+- 确认 manifest 中的版本号大于当前版本-### 1. 服务器启动失败+### 3. 服务器启动失败```bash# 检查端口是否被占用@@ -210,22 +207,6 @@ lsof -i :8787PORT=9000 ./start-server.sh```-### 2. 更新检测不到--- 确认 `dev-app-update.yml` 中的 URL 包含渠道路径 (如 `/stable`)-- 确认 manifest 中的版本号大于当前版本 (0.0.0)-- 查看日志:`tail -f ~/Library/Logs/lobehub-desktop-dev/main.log`--### 3. 请求了错误的 yml 文件--- 如果请求的是 `stable-mac.yml` 而不是 `latest-mac.yml`,说明代码中设置了 channel-- 确保在 dev 模式下运行,代码不会设置 `autoUpdater.channel`--### 4. 下载后无法安装--- 确认已禁用 Gatekeeper 或移除隔离属性-- 确认 DMG 文件完整----## 注意事项diff --git a/apps/desktop/scripts/update-test/dev-app-update.local.yml b/apps/desktop/scripts/update-test/dev-app-update.local.ymlindex e01f6645d75..dc2048fe3a2 100644--- a/apps/desktop/scripts/update-test/dev-app-update.local.yml+++ b/apps/desktop/scripts/update-test/dev-app-update.local.yml@@ -1,18 +1,15 @@# 本地更新测试配置# 将此文件复制到 apps/desktop/dev-app-update.yml 以使用本地服务器测试#+# 注意: 此配置仅用于应用初始启动时的 provider 配置。+# Channel 切换功能通过 UPDATE_SERVER_URL 环境变量 + setFeedURL() 实现,+# 不依赖此文件。+## 使用方法:# cp scripts/update-test/dev-app-update.local.yml dev-app-update.yml-#-# 恢复默认配置:-# git checkout dev-app-update.yml+# UPDATE_SERVER_URL=http://localhost:8787 bun run devprovider: generic-# URL 格式: http://localhost:8787/{channel}-# 可选渠道: stable, beta, nightlyurl: http://localhost:8787/stableupdaterCacheDirName: lobehub-desktop-local-test--# 设置 channel 为 stable 以匹配生产环境行为-# stable channel 会找 stable-mac.ymlchannel: stablediff --git a/apps/desktop/scripts/update-test/generate-manifest.sh b/apps/desktop/scripts/update-test/generate-manifest.shindex 53a8919177d..62a1d00e63f 100755--- a/apps/desktop/scripts/update-test/generate-manifest.sh+++ b/apps/desktop/scripts/update-test/generate-manifest.sh@@ -26,6 +26,7 @@ DMG_FILE=""ZIP_FILE=""RELEASE_NOTES=""FROM_RELEASE=false+ALL_CHANNELS=false# 帮助信息show_help() {@@ -33,7 +34,8 @@ show_help() {echo ""echo "选项:"echo " -v, --version VERSION 指定版本号 (例如: 2.0.1)"- echo " -c, --channel CHANNEL 指定渠道 (stable|beta|nightly, 默认: stable)"+ echo " -c, --channel CHANNEL 指定渠道 (stable|nightly|canary, 默认: stable)"+ echo " -a, --all-channels 为所有渠道生成 manifest (stable/nightly/canary)"echo " -d, --dmg FILE 指定 DMG 文件名"echo " -z, --zip FILE 指定 ZIP 文件名"echo " -n, --notes TEXT 指定 release notes"@@ -43,7 +45,8 @@ show_help() {echo "示例:"echo " $0 --from-release"echo " $0 -v 2.0.1 -c stable -d LobeHub-2.0.1-arm64.dmg"- echo " $0 -v 2.1.0-beta.1 -c beta --from-release"+ echo " $0 --from-release --all-channels"+ echo " $0 -v 2.1.0-nightly.1 -c nightly --from-release"echo ""echo "生成的目录结构:"echo " server/"@@ -75,8 +78,86 @@ get_file_size() {fi}+# 为单个渠道生成 manifest+generate_for_channel() {+ local ch="$1"+ local ver="$2"+ local dmg="$3"+ local zip="$4"+ local notes="$5"+ local dmg_path="$6"+ local zip_path="$7"++ local ch_dir="$SERVER_DIR/$ch"+ local ver_dir="$ch_dir/$ver"++ echo ""+ echo "📦 渠道: $ch 版本: $ver"++ mkdir -p "$ver_dir"++ # 复制文件到版本目录+ if [ -n "$dmg_path" ] && [ -f "$dmg_path" ]; then+ echo " 复制 $dmg -> $ch/$ver/"+ cp -f "$dmg_path" "$ver_dir/"+ fi++ if [ -n "$zip_path" ] && [ -f "$zip_path" ]; then+ echo " 复制 $zip -> $ch/$ver/"+ cp -f "$zip_path" "$ver_dir/"+ fi++ # 计算哈希+ local dmg_sha512="" dmg_size="0" zip_sha512="" zip_size="0"++ if [ -n "$dmg" ] && [ -f "$ver_dir/$dmg" ]; then+ echo " 计算 DMG SHA512..."+ dmg_sha512=$(calc_sha512 "$ver_dir/$dmg")+ dmg_size=$(get_file_size "$ver_dir/$dmg")+ fi++ if [ -n "$zip" ] && [ -f "$ver_dir/$zip" ]; then+ echo " 计算 ZIP SHA512..."+ zip_sha512=$(calc_sha512 "$ver_dir/$zip")+ zip_size=$(get_file_size "$ver_dir/$zip")+ fi++ # 生成 {channel}-mac.yml+ local manifest="$ch-mac.yml"++ cat > "$ch_dir/$manifest" << EOF+version: $ver+files:+EOF++ if [ -n "$dmg" ]; then+ cat >> "$ch_dir/$manifest" << EOF+ - url: $ver/$dmg+ sha512: ${dmg_sha512:-placeholder}+ size: $dmg_size+EOF+ fi++ if [ -n "$zip" ]; then+ cat >> "$ch_dir/$manifest" << EOF+ - url: $ver/$zip+ sha512: ${zip_sha512:-placeholder}+ size: $zip_size+EOF+ fi++ cat >> "$ch_dir/$manifest" << EOF+path: $ver/${dmg:-LobeHub-$ver-arm64.dmg}+sha512: ${dmg_sha512:-placeholder}+releaseDate: '$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")'+releaseNotes: |+$(echo "$notes" | sed 's/^/ /')+EOF++ echo " ✅ 生成 $ch/$manifest"+}+# 解析参数-FROM_RELEASE=falsewhile [[ $# -gt 0 ]]; docase $1 in-v | --version)@@ -87,6 +168,10 @@ while [[ $# -gt 0 ]]; doCHANNEL="$2"shift 2;;+ -a | --all-channels)+ ALL_CHANNELS=true+ shift+ ;;-d | --dmg)DMG_FILE="$2"shift 2@@ -116,11 +201,9 @@ while [[ $# -gt 0 ]]; dodoneecho "🔧 生成更新 manifest 文件..."-echo " 渠道: $CHANNEL"-echo ""-# 渠道目录-CHANNEL_DIR="$SERVER_DIR/$CHANNEL"+DMG_PATH=""+ZIP_PATH=""# 自动从 release 目录检测和复制if [ "$FROM_RELEASE" = true ]; then@@ -139,20 +222,23 @@ if [ "$FROM_RELEASE" = true ]; thenecho " 找到 DMG: $DMG_FILE"fi- # 查找 ZIP 文件+ # 查找 ZIP 文件 (尝试多种命名模式)ZIP_PATH=$(find "$RELEASE_DIR" -maxdepth 1 -name "*-mac.zip" -type f | head -1)+ if [ -z "$ZIP_PATH" ]; then+ ZIP_PATH=$(find "$RELEASE_DIR" -maxdepth 1 -name "*.zip" -type f | head -1)+ fiif [ -n "$ZIP_PATH" ]; thenZIP_FILE=$(basename "$ZIP_PATH")echo " 找到 ZIP: $ZIP_FILE"+ else+ echo " ⚠️ 未找到 ZIP 文件"+ echo " macOS 自动更新需要 ZIP 文件。请使用以下命令构建:"+ echo " cd $(dirname "$SCRIPT_DIR") && electron-builder --config electron-builder.mjs --mac dmg zip --c.mac.notarize=false -c.mac.identity=null"fi# 从文件名提取版本号- # 文件名格式: lobehub-desktop-dev-0.0.0-arm64.dmg- # 版本号格式: x.y.z 或 x.y.z-beta.1 等if [ -z "$VERSION" ] && [ -n "$DMG_FILE" ]; then- # 先尝试匹配带预发布标签的版本 (如 2.0.0-beta.1)- VERSION=$(echo "$DMG_FILE" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+-(alpha|beta|rc|nightly)\.[0-9]+' | head -1)- # 如果没有预发布标签,只匹配基本版本号 (如 2.0.0)+ VERSION=$(echo "$DMG_FILE" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+-(alpha|beta|rc|nightly|canary)\.[0-9]+' | head -1)if [ -z "$VERSION" ]; thenVERSION=$(echo "$DMG_FILE" | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)fi@@ -165,113 +251,76 @@ if [ -z "$VERSION" ]; thenecho "⚠️ 未指定版本号,使用默认值: $VERSION"fi-# 版本目录-VERSION_DIR="$CHANNEL_DIR/$VERSION"--# 创建目录结构-echo ""-echo "📁 创建目录结构..."-mkdir -p "$VERSION_DIR"-echo " $CHANNEL_DIR/"-echo " $VERSION/"+if [ "$ALL_CHANNELS" = true ]; then+ echo ""+ echo "📡 为所有渠道生成 manifest..."-# 复制文件到版本目录-if [ "$FROM_RELEASE" = true ]; then- if [ -n "$DMG_PATH" ] && [ -f "$DMG_PATH" ]; then- echo " 复制 $DMG_FILE -> $VERSION/"- cp "$DMG_PATH" "$VERSION_DIR/"- fi+ # stable: 使用基础版本号+ STABLE_VER="$VERSION"+ # nightly: 版本号 +1 patch,加 nightly 后缀+ MAJOR=$(echo "$VERSION" | cut -d. -f1)+ MINOR=$(echo "$VERSION" | cut -d. -f2)+ PATCH=$(echo "$VERSION" | cut -d. -f3 | cut -d- -f1)+ NIGHTLY_VER="$MAJOR.$MINOR.$((PATCH + 1))-nightly.$(date +%Y%m%d)"+ # canary: 版本号 +1 patch,加 canary 后缀+ CANARY_VER="$MAJOR.$MINOR.$((PATCH + 1))-canary.1"- if [ -n "$ZIP_PATH" ] && [ -f "$ZIP_PATH" ]; then- echo " 复制 $ZIP_FILE -> $VERSION/"- cp "$ZIP_PATH" "$VERSION_DIR/"- fi-fi+ STABLE_NOTES="## v$STABLE_VER (Stable)-# 设置默认 release notes-if [ -z "$RELEASE_NOTES" ]; then- RELEASE_NOTES="## 🎉 v$VERSION 本地测试版本+稳定版本,适合日常使用。-这是一个用于本地测试更新功能的模拟版本。+### 测试要点+- 从 Nightly/Canary 切换到 Stable 应触发降级更新+- allowDowngrade 应自动设为 true"-### ✨ 新功能-- 测试自动更新功能-- 验证更新流程+ NIGHTLY_NOTES="## v$NIGHTLY_VER (Nightly)-### 🐛 修复-- 本地测试环境配置"-fi+每日构建版本,包含最新功能。-# 生成 {channel}-mac.yml (e.g., stable-mac.yml)-MANIFEST_FILE="$CHANNEL-mac.yml"-echo ""-echo "📝 生成 $CHANNEL/$MANIFEST_FILE..."+### 测试要点+- 从 Stable 切换到 Nightly 应检测到此版本+- allowPrerelease 应自动设为 true"-DMG_SHA512=""-DMG_SIZE="0"-ZIP_SHA512=""-ZIP_SIZE="0"+ CANARY_NOTES="## v$CANARY_VER (Canary)-if [ -n "$DMG_FILE" ] && [ -f "$VERSION_DIR/$DMG_FILE" ]; then- echo " 计算 DMG SHA512..."- DMG_SHA512=$(calc_sha512 "$VERSION_DIR/$DMG_FILE")- DMG_SIZE=$(get_file_size "$VERSION_DIR/$DMG_FILE")-fi+最前沿版本,每次 PR 合并后构建。-if [ -n "$ZIP_FILE" ] && [ -f "$VERSION_DIR/$ZIP_FILE" ]; then- echo " 计算 ZIP SHA512..."- ZIP_SHA512=$(calc_sha512 "$VERSION_DIR/$ZIP_FILE")- ZIP_SIZE=$(get_file_size "$VERSION_DIR/$ZIP_FILE")-fi+### 测试要点+- 从 Stable/Nightly 切换到 Canary 应检测到此版本+- 从 Canary 切换回其他渠道应触发降级"-# 写入 manifest 文件 (放在渠道目录下)-cat > "$CHANNEL_DIR/$MANIFEST_FILE" << EOF-version: $VERSION-files:-EOF+ generate_for_channel "stable" "$STABLE_VER" "$DMG_FILE" "$ZIP_FILE" "$STABLE_NOTES" "$DMG_PATH" "$ZIP_PATH"+ generate_for_channel "nightly" "$NIGHTLY_VER" "$DMG_FILE" "$ZIP_FILE" "$NIGHTLY_NOTES" "$DMG_PATH" "$ZIP_PATH"+ generate_for_channel "canary" "$CANARY_VER" "$DMG_FILE" "$ZIP_FILE" "$CANARY_NOTES" "$DMG_PATH" "$ZIP_PATH"+else+ if [ -z "$RELEASE_NOTES" ]; then+ RELEASE_NOTES="## 🎉 v$VERSION 本地测试版本-if [ -n "$DMG_FILE" ]; then- cat >> "$CHANNEL_DIR/$MANIFEST_FILE" << EOF- - url: $VERSION/$DMG_FILE- sha512: ${DMG_SHA512:-placeholder}- size: $DMG_SIZE-EOF-fi--if [ -n "$ZIP_FILE" ]; then- cat >> "$CHANNEL_DIR/$MANIFEST_FILE" << EOF- - url: $VERSION/$ZIP_FILE- sha512: ${ZIP_SHA512:-placeholder}- size: $ZIP_SIZE-EOF-fi+这是一个用于本地测试更新功能的模拟版本。-cat >> "$CHANNEL_DIR/$MANIFEST_FILE" << EOF-path: $VERSION/${DMG_FILE:-LobeHub-$VERSION-arm64.dmg}-sha512: ${DMG_SHA512:-placeholder}-releaseDate: '$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")'-releaseNotes: |-$(echo "$RELEASE_NOTES" | sed 's/^/ /')-EOF+### ✨ 新功能+- 测试自动更新功能+- 验证更新流程-echo "✅ 已生成 $CHANNEL_DIR/$MANIFEST_FILE"+### 🐛 修复+- 本地测试环境配置"+ fi-# 显示生成的文件内容-echo ""-echo "📋 文件内容:"-echo "----------------------------------------"-cat "$CHANNEL_DIR/$MANIFEST_FILE"-echo "----------------------------------------"+ echo " 渠道: $CHANNEL"+ generate_for_channel "$CHANNEL" "$VERSION" "$DMG_FILE" "$ZIP_FILE" "$RELEASE_NOTES" "$DMG_PATH" "$ZIP_PATH"+fi# 显示目录结构echo ""-echo "📁 目录结构:"-find "$CHANNEL_DIR" -type f | sed "s|$SERVER_DIR/||" | sort-+echo "📁 服务器目录结构:"+find "$SERVER_DIR" -type f -name "*.yml" | sed "s|$SERVER_DIR/||" | sortecho ""+echo "✅ 完成!"echo ""echo "下一步:"echo " 1. 启动服务器: ./start-server.sh"-echo " 2. 确认 dev-app-update.yml 的 URL 为: http://localhost:8787/$CHANNEL"-echo " 3. 运行应用: cd ../.. && bun run dev"+echo " 2. 运行测试: ./run-test.sh"+echo " 或手动:"+echo " 3. 设置环境变量: UPDATE_SERVER_URL=http://localhost:8787"+echo " 4. 运行应用: cd ../.. && bun run dev"diff --git a/apps/desktop/scripts/update-test/run-test.sh b/apps/desktop/scripts/update-test/run-test.shindex 6fc218a7365..93b3c640d1f 100755--- a/apps/desktop/scripts/update-test/run-test.sh+++ b/apps/desktop/scripts/update-test/run-test.sh@@ -1,25 +1,42 @@#!/bin/bash# ============================================-# 一键启动本地更新测试+# 一键启动本地更新测试 (含 Channel 切换)# ============================================#-# 此脚本会:-# 1. 设置测试环境-# 2. 从 release 目录复制文件-# 3. 生成 manifest-# 4. 启动本地服务器-# 5. 配置应用使用本地服务器-# 6. 启动应用+# 两种测试模式:+# 1. 打包模式 (默认): 构建打包后的应用,可完整测试更新流程+# 2. 开发模式 (--dev): 使用 bun run dev,仅测试 UI 和 IPC,+# updater 不会初始化 (isDev=true 时 enableAppUpdate=false)#set -eSCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"DESKTOP_DIR="$(dirname "$(dirname "$SCRIPT_DIR")")"+PORT="${PORT:-8787}"+DEV_MODE=false++# 解析参数+while [[ $# -gt 0 ]]; do+ case $1 in+ --dev)+ DEV_MODE=true+ shift+ ;;+ *)+ shift+ ;;+ esac+doneecho "============================================"-echo "🧪 本地更新测试 - 一键启动"+echo "🧪 本地更新测试 - Channel 切换"+if [ "$DEV_MODE" = true ]; then+ echo " 模式: 开发模式 (仅 UI/IPC 测试)"+else+ echo " 模式: 打包模式 (完整更新流程)"+fiecho "============================================"echo ""@@ -46,60 +63,144 @@ check_gatekeeper() {}# 步骤 1: 设置-echo "📦 步骤 1/5: 设置测试环境..."+echo "📦 步骤 1: 设置测试环境..."cd "$SCRIPT_DIR"chmod +x *.sh-mkdir -p server+mkdir -p server/stable server/nightly server/canary-# 步骤 2: 检查 release 目录-echo ""-echo "📂 步骤 2/5: 检查构建产物..."-if [ ! -d "$DESKTOP_DIR/release" ] || [ -z "$(ls -A "$DESKTOP_DIR/release"/*.dmg 2> /dev/null)" ]; then- echo "❌ 未找到构建产物"+if [ "$DEV_MODE" = true ]; then+ # ============================================+ # 开发模式: 只启动服务器 + dev+ # ============================================++ # 生成 mock manifest (不需要真实构建产物)+ echo ""+ echo "📝 步骤 2: 生成 mock manifest..."+ for ch in stable nightly canary; do+ cat > "server/$ch/$ch-mac.yml" << EOF+version: 99.0.0-$ch.1+files:+ - url: mock.dmg+ sha512: placeholder+ size: 100000000+path: mock.dmg+sha512: placeholder+releaseDate: '$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")'+releaseNotes: |+ ## v99.0.0-$ch.1 本地测试 ($ch 渠道)+ Mock manifest for UI testing.+EOF+ echo " ✅ $ch/$ch-mac.yml (v99.0.0-$ch.1)"+ done++ # 启动服务器echo ""- echo "请先构建应用:"+ echo "🚀 步骤 3: 启动本地服务器..."+ ./start-server.sh++ echo ""+ echo "============================================"+ echo "✅ 准备完成!(开发模式)"+ echo "============================================"+ echo ""+ echo "⚠️ 注意: 开发模式下 updater 不会初始化"+ echo " 仅可测试: Settings > Beta 页面 UI、IPC 通信"+ echo " 不可测试: 实际更新检查、下载、安装"+ echo ""+ echo "启动应用:"echo " cd $DESKTOP_DIR"- echo " npm run build-local"+ echo " UPDATE_SERVER_URL=http://localhost:$PORT bun run dev"echo ""- exit 1-fi+ read -p "是否现在启动应用?[Y/n] " -n 1 -r+ echo ""+ if [[ ! $REPLY =~ ^[Nn]$ ]]; then+ echo "🚀 启动应用..."+ cd "$DESKTOP_DIR"+ UPDATE_SERVER_URL="http://localhost:$PORT" bun run dev+ fi-# 步骤 3: 生成 manifest-echo ""-echo "📝 步骤 3/5: 生成 manifest 文件..."-./generate-manifest.sh --from-release+else+ # ============================================+ # 打包模式: 完整更新流程测试+ # ============================================-# 步骤 4: 启动服务器-echo ""-echo "🚀 步骤 4/5: 启动本地服务器..."-./start-server.sh+ # 步骤 2: 检查构建产物+ echo ""+ echo "📂 步骤 2: 检查构建产物..."+ if [ ! -d "$DESKTOP_DIR/release" ] || [ -z "$(ls -A "$DESKTOP_DIR/release"/*.dmg 2> /dev/null)" ]; then+ echo "❌ 未找到构建产物"+ echo ""+ echo "请先构建应用 (需产出 DMG + ZIP):"+ echo " cd $DESKTOP_DIR"+ echo " bun run package:mac:local"+ echo ""+ exit 1+ fi-# 步骤 5: 配置并启动应用-echo ""-echo "⚙️ 步骤 5/5: 配置应用..."-cp "$SCRIPT_DIR/dev-app-update.local.yml" "$DESKTOP_DIR/dev-app-update.yml"-echo "✅ 已更新 dev-app-update.yml"+ # 检查 ZIP 文件+ if [ -z "$(ls -A "$DESKTOP_DIR/release"/*.zip 2> /dev/null)" ]; then+ echo "⚠️ 未找到 ZIP 文件,macOS 自动更新需要 ZIP"+ echo " 请使用 bun run package:mac:local 构建"+ echo ""+ read -p "是否仍然继续 (仅生成 DMG manifest)?[y/N] " -n 1 -r+ echo ""+ if [[ ! $REPLY =~ ^[Yy]$ ]]; then+ exit 1+ fi+ fi-# 检查 Gatekeeper-echo ""-check_gatekeeper+ # 步骤 3: 为所有渠道生成 manifest+ echo ""+ echo "📝 步骤 3: 为 stable/nightly/canary 生成 manifest..."+ ./generate-manifest.sh --from-release --all-channels-echo ""-echo "============================================"-echo "✅ 准备完成!"-echo "============================================"-echo ""-echo "现在可以运行应用进行测试:"-echo ""-echo " cd $DESKTOP_DIR"-echo " npm run dev"-echo ""-echo "或者直接运行:"-read -p "是否现在启动应用?[Y/n] " -n 1 -r-echo ""-if [[ ! $REPLY =~ ^[Nn]$ ]]; then+ # 步骤 4: 启动服务器echo ""- echo "🚀 启动应用..."- cd "$DESKTOP_DIR"- npm run dev+ echo "🚀 步骤 4: 启动本地服务器..."+ ./start-server.sh++ # 步骤 5: 配置应用+ echo ""+ echo "⚙️ 步骤 5: 配置应用..."+ cp "$SCRIPT_DIR/dev-app-update.local.yml" "$DESKTOP_DIR/dev-app-update.yml"+ echo "✅ 已更新 dev-app-update.yml"++ # 检查 Gatekeeper+ echo ""+ check_gatekeeper++ echo ""+ echo "============================================"+ echo "✅ 准备完成!(打包模式)"+ echo "============================================"+ echo ""+ echo "📡 服务器渠道:"+ echo " stable -> http://localhost:$PORT/stable/stable-mac.yml"+ echo " nightly -> http://localhost:$PORT/nightly/nightly-mac.yml"+ echo " canary -> http://localhost:$PORT/canary/canary-mac.yml"+ echo ""+ echo "🔄 测试 Channel 切换:"+ echo " 1. 启动打包后的应用"+ echo " 2. 进入 设置 > Beta"+ echo " 3. 在 Update Channel 下拉框中切换渠道"+ echo " 4. 查看日志: tail -f ~/Library/Logs/lobehub-desktop/main.log"+ echo ""+ echo "运行打包后的应用:"+ echo " 需设置环境变量: FORCE_DEV_UPDATE_CONFIG=true UPDATE_SERVER_URL=http://localhost:$PORT"+ echo ""++ # 查找并提供启动打包应用的命令+ APP_PATH=$(find "$DESKTOP_DIR/release" -maxdepth 2 -name "*.app" -type d | head -1)+ if [ -n "$APP_PATH" ]; then+ echo "检测到打包应用: $APP_PATH"+ echo ""+ read -p "是否现在启动?[Y/n] " -n 1 -r+ echo ""+ if [[ ! $REPLY =~ ^[Nn]$ ]]; then+ echo "🚀 启动应用..."+ FORCE_DEV_UPDATE_CONFIG=true UPDATE_SERVER_URL="http://localhost:$PORT" open "$APP_PATH"+ fi+ else+ echo "未找到 .app,请手动启动打包后的应用"+ fifidiff --git a/apps/desktop/scripts/update-test/setup.sh b/apps/desktop/scripts/update-test/setup.shindex 1cfe207aee8..fc663f06410 100755--- a/apps/desktop/scripts/update-test/setup.sh+++ b/apps/desktop/scripts/update-test/setup.sh@@ -11,9 +11,11 @@ SERVER_DIR="$SCRIPT_DIR/server"echo "🚀 设置本地更新测试环境..."-# 创建服务器目录-mkdir -p "$SERVER_DIR"-echo "✅ 创建服务器目录: $SERVER_DIR"+# 创建服务器目录(含三个渠道子目录)+mkdir -p "$SERVER_DIR/stable"+mkdir -p "$SERVER_DIR/nightly"+mkdir -p "$SERVER_DIR/canary"+echo "✅ 创建服务器目录: $SERVER_DIR/{stable,nightly,canary}"# 设置脚本执行权限chmod +x "$SCRIPT_DIR"/*.sh@@ -25,8 +27,9 @@ if ! command -v npx &> /dev/null; thenexit 1fi-# 创建示例 latest-mac.yml-cat > "$SERVER_DIR/latest-mac.yml" << 'EOF'+# 为三个渠道创建示例 manifest+for ch in stable nightly canary; do+ cat > "$SERVER_DIR/$ch/$ch-mac.yml" << EOFversion: 99.0.0files:- url: LobeHub-99.0.0-arm64.dmg@@ -39,44 +42,30 @@ path: LobeHub-99.0.0-arm64.dmgsha512: placeholder-sha512-will-be-replacedreleaseDate: '2026-01-15T10:00:00.000Z'releaseNotes: |- ## 🎉 v99.0.0 本地测试版本+ ## v99.0.0 本地测试版本 ($ch)- 这是一个用于本地测试更新功能的模拟版本。-- ### ✨ 新功能- - 测试功能 A- - 测试功能 B-- ### 🐛 修复- - 修复测试问题 X+ 这是 $ch 渠道的模拟版本。EOF-echo "✅ 创建示例 latest-mac.yml"--# 创建 Windows 版本的 manifest (可选)-cat > "$SERVER_DIR/latest.yml" << 'EOF'-version: 99.0.0-files:- - url: LobeHub-99.0.0-setup.exe- sha512: placeholder-sha512-will-be-replaced- size: 100000000-path: LobeHub-99.0.0-setup.exe-sha512: placeholder-sha512-will-be-replaced-releaseDate: '2026-01-15T10:00:00.000Z'-releaseNotes: |- ## 🎉 v99.0.0 本地测试版本-- 这是一个用于本地测试更新功能的模拟版本。-EOF-echo "✅ 创建示例 latest.yml (Windows)"+ echo "✅ 创建示例 $ch/$ch-mac.yml"+done# 创建本地测试用的 dev-app-update.ymlcat > "$SCRIPT_DIR/dev-app-update.local.yml" << 'EOF'# 本地更新测试配置# 将此文件复制到 apps/desktop/dev-app-update.yml 以使用本地服务器测试+#+# 注意: 此配置仅用于应用初始启动时的 provider 配置。+# Channel 切换功能通过 UPDATE_SERVER_URL 环境变量 + setFeedURL() 实现,+# 不依赖此文件。+#+# 使用方法:+# cp scripts/update-test/dev-app-update.local.yml dev-app-update.yml+# UPDATE_SERVER_URL=http://localhost:8787 bun run devprovider: generic-url: http://localhost:8787+url: http://localhost:8787/stableupdaterCacheDirName: lobehub-desktop-local-test+channel: stableEOFecho "✅ 创建本地测试配置文件"@@ -87,25 +76,14 @@ echo "============================================"echo ""echo "下一步操作:"echo ""-echo "1. 构建测试包:"+echo "1. 构建测试包 (需产出 DMG + ZIP):"echo " cd $(dirname "$SCRIPT_DIR")"-echo " npm run build-local"+echo " bun run package:mac:local"echo ""-echo "2. 复制构建产物到服务器目录:"-echo " cp release/*.dmg scripts/update-test/server/"-echo " cp release/*.zip scripts/update-test/server/"-echo ""-echo "3. 更新 manifest 文件(可选):"+echo "2. 生成真实的 manifest (从构建产物):"echo " cd scripts/update-test"-echo " ./generate-manifest.sh"-echo ""-echo "4. 启动本地服务器:"-echo " ./start-server.sh"-echo ""-echo "5. 配置应用使用本地服务器:"-echo " cp dev-app-update.local.yml ../../dev-app-update.yml"+echo " ./generate-manifest.sh --from-release --all-channels"echo ""-echo "6. 运行应用:"-echo " cd ../.."-echo " npm run dev"+echo "3. 或者直接一键测试:"+echo " ./run-test.sh"echo ""diff --git a/apps/desktop/scripts/update-test/start-server.sh b/apps/desktop/scripts/update-test/start-server.shindex aec62472bc2..e4e8b4b175f 100755--- a/apps/desktop/scripts/update-test/start-server.sh+++ b/apps/desktop/scripts/update-test/start-server.sh@@ -35,9 +35,20 @@ echo " 目录: $SERVER_DIR"echo " 端口: $PORT"echo ""-# 列出服务器目录中的文件-echo "📦 可用文件:"-ls -la "$SERVER_DIR" | grep -v "^d" | grep -v "^total" | awk '{print " " $NF}'+# 列出可用渠道+echo "📦 可用渠道:"+for ch_dir in "$SERVER_DIR"/*/; do+ if [ -d "$ch_dir" ]; then+ ch=$(basename "$ch_dir")+ manifest="$ch_dir/$ch-mac.yml"+ if [ -f "$manifest" ]; then+ ver=$(grep '^version:' "$manifest" | awk '{print $2}')+ echo " $ch -> v$ver (http://localhost:$PORT/$ch/$ch-mac.yml)"+ else+ echo " $ch -> (no manifest)"+ fi+ fi+doneecho ""# 启动服务器 (后台运行)@@ -57,10 +68,6 @@ if ps -p "$SERVER_PID" > /dev/null 2>&1; thenecho " PID: $SERVER_PID"echo " 日志: $LOG_FILE"echo ""- echo "📋 测试 URL:"- echo " latest-mac.yml: http://localhost:$PORT/latest-mac.yml"- echo " latest.yml: http://localhost:$PORT/latest.yml"- echo ""echo "🛑 停止服务器: ./stop-server.sh"elseecho "❌ 服务器启动失败"diff --git a/apps/desktop/src/main/const/store.ts b/apps/desktop/src/main/const/store.tsindex 3564056d225..aea6150c9c7 100644--- a/apps/desktop/src/main/const/store.ts+++ b/apps/desktop/src/main/const/store.ts@@ -1,11 +1,12 @@/*** Application settings storage related constants*/-import { NetworkProxySettings } from '@lobechat/electron-client-ipc';+import type { NetworkProxySettings } from '@lobechat/electron-client-ipc';import { appStorageDir } from '@/const/dir';+import { UPDATE_CHANNEL } from '@/modules/updater/configs';import { DEFAULT_SHORTCUTS_CONFIG } from '@/shortcuts';-import { ElectronMainStore } from '@/types/store';+import type { ElectronMainStore } from '@/types/store';/*** Storage name@@ -32,4 +33,5 @@ export const STORE_DEFAULTS: ElectronMainStore = {shortcuts: DEFAULT_SHORTCUTS_CONFIG,storagePath: appStorageDir,themeMode: 'system',+ updateChannel: UPDATE_CHANNEL,};diff --git a/apps/desktop/src/main/controllers/UpdaterCtr.ts b/apps/desktop/src/main/controllers/UpdaterCtr.tsindex 8129a9c16ad..466404d03e4 100644--- a/apps/desktop/src/main/controllers/UpdaterCtr.ts+++ b/apps/desktop/src/main/controllers/UpdaterCtr.ts@@ -1,3 +1,5 @@+import type { UpdateChannel, UpdaterState } from '@lobechat/electron-client-ipc';+import { createLogger } from '@/utils/logger';import { ControllerModule, IpcMethod } from './index';@@ -41,4 +43,26 @@ export default class UpdaterCtr extends ControllerModule {logger.info('Install later requested');this.app.updaterManager.installLater();}++ @IpcMethod()+ async getUpdateChannel(): Promise<UpdateChannel> {+ return this.app.storeManager.get('updateChannel') ?? 'stable';+ }++ @IpcMethod()+ async setUpdateChannel(channel: UpdateChannel): Promise<void> {+ const validChannels = new Set(['stable', 'nightly', 'canary']);+ if (!validChannels.has(channel)) {+ logger.warn(`Invalid update channel: ${channel}, ignoring`);+ return;+ }+ logger.info(`Set update channel requested: ${channel}`);+ this.app.storeManager.set('updateChannel', channel);+ this.app.updaterManager.switchChannel(channel);+ }++ @IpcMethod()+ async getUpdaterState(): Promise<UpdaterState> {+ return this.app.updaterManager.getUpdaterState();+ }}diff --git a/apps/desktop/src/main/core/infrastructure/UpdaterManager.ts b/apps/desktop/src/main/core/infrastructure/UpdaterManager.tsindex 47e420ceb8f..a5a1b5eb39d 100644--- a/apps/desktop/src/main/core/infrastructure/UpdaterManager.ts+++ b/apps/desktop/src/main/core/infrastructure/UpdaterManager.ts@@ -1,17 +1,17 @@-import type { UpdateInfo } from '@lobechat/electron-client-ipc';+import type {+ ProgressInfo,+ UpdateChannel,+ UpdateInfo,+ UpdaterStage,+ UpdaterState,+} from '@lobechat/electron-client-ipc';import { app as electronApp } from 'electron';import log from 'electron-log';import { autoUpdater } from 'electron-updater';import { isDev, isWindows } from '@/const/env';import { getDesktopEnv } from '@/env';-import {- UPDATE_SERVER_URL,- UPDATE_CHANNEL as channel,- githubConfig,- isStableChannel,- updaterConfig,-} from '@/modules/updater/configs';+import { UPDATE_CHANNEL, UPDATE_SERVER_URL, updaterConfig } from '@/modules/updater/configs';import { createLogger } from '@/utils/logger';import type { App as AppCore } from '../App';@@ -25,8 +25,18 @@ export class UpdaterManager {private checking: boolean = false;private downloading: boolean = false;private updateAvailable: boolean = false;- private isManualCheck: boolean = false;- private usingFallbackProvider: boolean = false;+ private currentChannel: UpdateChannel = UPDATE_CHANNEL;+ /** Incremented on each channel switch to invalidate in-flight checks */+ private checkGeneration: number = 0;+ /** Generation at the start of the current active check */+ private activeGeneration: number = 0;+ /** Whether a recheck is needed after the current check completes */+ private pendingRecheck: boolean = false;++ private stage: UpdaterStage = 'idle';+ private latestUpdateInfo: UpdateInfo | null = null;+ private latestProgress: ProgressInfo | null = null;+ private latestError: string | null = null;constructor(app: AppCore) {this.app = app;@@ -41,6 +51,44 @@ export class UpdaterManager {return this.app.browserManager.getMainWindow();}+ public getUpdaterState(): UpdaterState {+ const state: UpdaterState = { stage: this.stage };+ if (this.latestProgress) state.progress = this.latestProgress;+ if (this.latestUpdateInfo) state.updateInfo = this.latestUpdateInfo;+ if (this.latestError) state.errorMessage = this.latestError;+ return state;+ }++ private setStage(+ stage: UpdaterStage,+ opts?: {+ error?: string;+ progress?: ProgressInfo;+ rebuildMenu?: boolean;+ updateInfo?: UpdateInfo;+ },+ ) {+ this.stage = stage;+ if (opts?.updateInfo !== undefined) this.latestUpdateInfo = opts.updateInfo;+ if (opts?.progress !== undefined) this.latestProgress = opts.progress;+ if (opts?.error !== undefined) this.latestError = opts.error;++ // Clear irrelevant fields on stage transitions+ if (stage === 'idle' || stage === 'checking') {+ this.latestProgress = null;+ this.latestError = null;+ }+ if (stage !== 'error') {+ this.latestError = null;+ }++ this.mainWindow.broadcast('updaterStateChanged', this.getUpdaterState());++ if (opts?.rebuildMenu !== false) {+ this.app.menuManager.rebuildAppMenu();+ }+ }+public initialize = async () => {logger.debug('Initializing UpdaterManager');@@ -49,6 +97,9 @@ export class UpdaterManager {return;}+ // Read persisted channel from store (defaults to build-time UPDATE_CHANNEL)+ this.currentChannel = this.app.storeManager.get('updateChannel') ?? UPDATE_CHANNEL;+autoUpdater.autoDownload = false;autoUpdater.autoInstallOnAppQuit = false;autoUpdater.allowDowngrade = false;@@ -61,8 +112,10 @@ export class UpdaterManager {);logger.info('Dev mode: Using dev-app-update.yml for update configuration');} else {- autoUpdater.allowPrerelease = channel !== 'stable';- logger.info(`Production mode: channel=${channel}, allowPrerelease=${channel !== 'stable'}`);+ autoUpdater.allowPrerelease = this.currentChannel !== 'stable';+ logger.info(+ `Production mode: channel=${this.currentChannel}, allowPrerelease=${this.currentChannel !== 'stable'}`,+ );this.configureUpdateProvider();}@@ -80,93 +133,111 @@ export class UpdaterManager {logger.info('UpdaterManager initialization completed');};+ /**+ * Switch to a different update channel at runtime+ */+ public switchChannel = (channel: UpdateChannel) => {+ logger.info(`Switching update channel: ${this.currentChannel} -> ${channel}`);++ const isDowngrade =+ (this.currentChannel === 'canary' && channel !== 'canary') ||+ (this.currentChannel === 'nightly' && channel === 'stable');++ this.currentChannel = channel;+ autoUpdater.allowDowngrade = isDowngrade;+ logger.info(`allowDowngrade=${isDowngrade}`);++ autoUpdater.allowPrerelease = channel !== 'stable';+ this.configureUpdateProvider();++ this.mainWindow.broadcast('updateChannelChanged', channel);++ // Invalidate any in-flight check and schedule a recheck+ this.checkGeneration++;+ if (this.checking) {+ this.pendingRecheck = true;+ } else {+ this.checkForUpdates();+ }+ };+/*** Check for updates- * @param manual whether this is a manual check for updates*/public checkForUpdates = async ({ manual = false }: { manual?: boolean } = {}) => {if (this.checking || this.downloading) return;this.checking = true;- this.isManualCheck = manual;-- if (!isStableChannel) {- autoUpdater.allowPrerelease = true;- }+ this.activeGeneration = this.checkGeneration;- logger.info(`${manual ? 'Manually checking' : 'Auto checking'} for updates...`);+ autoUpdater.allowPrerelease = this.currentChannel !== 'stable';- const inferredChannel =- autoUpdater.channel ||- (autoUpdater.currentVersion?.prerelease?.[0]- ? String(autoUpdater.currentVersion.prerelease[0])- : null);+ logger.info(+ `${manual ? 'Manually checking' : 'Auto checking'} for updates... (gen=${this.activeGeneration})`,+ );logger.info('[Updater Config] Channel:', autoUpdater.channel);- logger.info('[Updater Config] inferredChannel:', inferredChannel);+ logger.info('[Updater Config] currentChannel:', this.currentChannel);logger.info('[Updater Config] allowPrerelease:', autoUpdater.allowPrerelease);logger.info('[Updater Config] currentVersion:', autoUpdater.currentVersion?.version);logger.info('[Updater Config] allowDowngrade:', autoUpdater.allowDowngrade);logger.info('[Updater Config] autoDownload:', autoUpdater.autoDownload);logger.info('[Updater Config] forceDevUpdateConfig:', autoUpdater.forceDevUpdateConfig);- logger.info('[Updater Config] Build channel from config:', channel);- logger.info('[Updater Config] isStableChannel:', isStableChannel);+ logger.info('[Updater Config] Build channel from config:', UPDATE_CHANNEL);logger.info('[Updater Config] UPDATE_SERVER_URL:', UPDATE_SERVER_URL || '(not set)');- logger.info('[Updater Config] usingFallbackProvider:', this.usingFallbackProvider);- logger.info('[Updater Config] GitHub config:', JSON.stringify(githubConfig));- if (manual) {- this.mainWindow.broadcast('manualUpdateCheckStart');- }+ this.setStage('checking');try {await autoUpdater.checkForUpdates();} catch (error) {+ if (this.isStaleCheck()) return;+const message = error instanceof Error ? error.message : String(error);- // Edge case: Release tag exists but update manifest assets (latest/stable-*.yml) aren't uploaded yet.- // Treat this gap period as "no updates available" instead of a user-facing error.if (this.isMissingUpdateManifestError(error)) {logger.warn('[Updater] Update manifest not ready yet, treating as no update:', message);- if (manual) {- this.mainWindow.broadcast('manualUpdateNotAvailable', this.getCurrentUpdateInfo());- }+ this.setStage('latest');+ setTimeout(() => {+ if (this.stage === 'latest') this.setStage('idle');+ }, 5000);return;}logger.error('Error checking for updates:', message);-- if (manual) {- this.mainWindow.broadcast('updateError', message);- }+ this.setStage('error', { error: message });+ setTimeout(() => {+ if (this.stage === 'error') this.setStage('idle');+ }, 3000);} finally {this.checking = false;+ if (this.pendingRecheck) {+ this.pendingRecheck = false;+ this.checkForUpdates();+ }}};/*** Download update- * @param manual whether this is a manual download*/- public downloadUpdate = async (manual: boolean = false) => {+ public downloadUpdate = async () => {if (this.downloading || !this.updateAvailable) return;this.downloading = true;- logger.info(`${manual ? 'Manually downloading' : 'Auto downloading'} update...`);+ logger.info('Downloading update...');- if (manual || this.isManualCheck) {- this.mainWindow.broadcast('updateDownloadStart');- }+ this.setStage('downloading');try {await autoUpdater.downloadUpdate();} catch (error) {this.downloading = false;logger.error('Error downloading update:', error);-- if (manual || this.isManualCheck) {- this.mainWindow.broadcast('updateError', (error as Error).message);- }+ this.setStage('error', { error: (error as Error).message });+ setTimeout(() => {+ if (this.stage === 'error') this.setStage('idle');+ }, 3000);}};@@ -182,7 +253,7 @@ export class UpdaterManager {const { BrowserWindow, app } = require('electron');if (!isWindows) {const allWindows = BrowserWindow.getAllWindows();- allWindows.forEach((window) => {+ allWindows.forEach((window: any) => {if (!window.isDestroyed()) {window.close();}@@ -210,15 +281,13 @@ export class UpdaterManager {/*** Test mode: Simulate update available- * Only for use in development environment*/public simulateUpdateAvailable = () => {if (!isDev) return;logger.info('Simulating update available...');- const mainWindow = this.mainWindow;- const mockUpdateInfo = {+ const mockUpdateInfo: UpdateInfo = {releaseDate: new Date().toISOString(),releaseNotes: ` #### Version 1.0.0 Release Notes- Added some great new features@@ -230,69 +299,62 @@ export class UpdaterManager {};this.updateAvailable = true;+ this.setStage('checking');- if (this.isManualCheck) {- mainWindow.broadcast('manualUpdateAvailable', mockUpdateInfo);- } else {+ setTimeout(() => {+ this.setStage('downloading', { updateInfo: mockUpdateInfo });this.simulateDownloadProgress();- }+ }, 1000);};/*** Test mode: Simulate update downloaded- * Only for use in development environment*/public simulateUpdateDownloaded = () => {if (!isDev) return;logger.info('Simulating update downloaded...');- const mainWindow = this.app.browserManager.getMainWindow();- if (mainWindow) {- const mockUpdateInfo = {- releaseDate: new Date().toISOString(),- releaseNotes: ` #### Version 1.0.0 Release Notes+ const mockUpdateInfo: UpdateInfo = {+ releaseDate: new Date().toISOString(),+ releaseNotes: ` #### Version 1.0.0 Release Notes- Added some great new features- Fixed bugs affecting usability- Optimized overall application performance- Updated dependency libraries`,- version: '1.0.0',- };+ version: '1.0.0',+ };- this.downloading = false;- mainWindow.broadcast('updateDownloaded', mockUpdateInfo);- }+ this.downloading = false;+ this.setStage('downloaded', { updateInfo: mockUpdateInfo });+ this.mainWindow.broadcast('updateDownloaded', mockUpdateInfo);};/*** Test mode: Simulate update download progress- * Only for use in development environment*/public simulateDownloadProgress = () => {if (!isDev) return;logger.info('Simulating download progress...');- const mainWindow = this.app.browserManager.getMainWindow();-this.downloading = true;- if (this.isManualCheck) {- mainWindow.broadcast('updateDownloadStart');- }-let progress = 0;const interval = setInterval(() => {progress += 10;- if (progress <= 100 && this.isManualCheck) {- mainWindow.broadcast('updateDownloadProgress', {+ if (progress <= 100) {+ const progressInfo: ProgressInfo = {bytesPerSecond: 1024 * 1024,percent: progress,total: 1024 * 1024 * 100,transferred: 1024 * 1024 * progress,- });+ };+ this.latestProgress = progressInfo;+ this.mainWindow.broadcast('updaterStateChanged', this.getUpdaterState());+ this.mainWindow.broadcast('updateDownloadProgress', progressInfo);}if (progress >= 100) {@@ -303,80 +365,51 @@ export class UpdaterManager {};/**- * Configure update provider based on channel- * - Stable channel + UPDATE_SERVER_URL: Use generic HTTP provider (S3) as primary, channel=stable- * - Other channels (beta/nightly) or no S3: Use GitHub provider, channel unset (defaults to latest)- *- * Important: S3 has stable-mac.yml, GitHub has latest-mac.yml+ * Strip trailing channel path from URL so we can re-append the correct channel.+ * Handles both base URL (https://cdn.example.com) and legacy URL with channel (https://cdn.example.com/stable)+ */+ private getBaseUpdateUrl(): string | undefined {+ if (!UPDATE_SERVER_URL) return undefined;+ return UPDATE_SERVER_URL.replace(/\/(stable|nightly|canary|beta)\/?$/, '');+ }++ /**+ * Configure update provider — all channels use generic HTTP provider (S3)+ * URL format: {base}/{channel}/+ * electron-updater looks for {channel}-mac.yml*/private configureUpdateProvider() {- if (isStableChannel && UPDATE_SERVER_URL && !this.usingFallbackProvider) {- autoUpdater.channel = 'stable';- logger.info(`Configuring generic provider for stable channel (primary)`);- logger.info(`Update server URL: ${UPDATE_SERVER_URL}`);- logger.info(`Channel set to: stable (will look for stable-mac.yml)`);+ const baseUrl = this.getBaseUpdateUrl();+ if (baseUrl) {+ const feedUrl = `${baseUrl}/${this.currentChannel}`;+ autoUpdater.channel = this.currentChannel;++ logger.info(`Configuring generic provider for ${this.currentChannel} channel`);+ logger.info(`Update server URL: ${feedUrl}`);+ logger.info(+ `Channel set to: ${this.currentChannel} (will look for ${this.currentChannel}-mac.yml)`,+ );autoUpdater.setFeedURL({provider: 'generic',- url: UPDATE_SERVER_URL,+ url: feedUrl,});} else {- const reason = this.usingFallbackProvider ? '(fallback from S3)' : '';- logger.info(`Configuring GitHub provider for ${channel} channel ${reason}`);- if (autoUpdater.channel !== null) {- autoUpdater.channel = null;- }- logger.info('Channel left unset (defaults to latest-mac.yml for GitHub)');-- const needPrerelease = channel !== 'stable';+ // Fallback to GitHub when no S3 URL configured (local dev)+ logger.info(+ `No UPDATE_SERVER_URL configured, falling back to GitHub provider for ${this.currentChannel} channel`,+ );autoUpdater.setFeedURL({- owner: githubConfig.owner,+ owner: 'lobehub',provider: 'github',- repo: githubConfig.repo,+ repo: 'lobehub',});- autoUpdater.allowPrerelease = needPrerelease;-- logger.info(- `GitHub update URL configured: ${githubConfig.owner}/${githubConfig.repo}, allowPrerelease=${needPrerelease}`,- );+ autoUpdater.allowPrerelease = this.currentChannel !== 'stable';}}- /**- * Switch to fallback provider (GitHub) and retry update check- * Called when primary provider (S3) fails- */- private switchToFallbackAndRetry = async () => {- if (!isStableChannel || !UPDATE_SERVER_URL || this.usingFallbackProvider) {- return false;- }-- logger.info('Primary update server (S3) failed, switching to GitHub fallback...');- this.usingFallbackProvider = true;- this.configureUpdateProvider();-- try {- await autoUpdater.checkForUpdates();- return true;- } catch (error) {- logger.error('Fallback provider (GitHub) also failed:', error);- return false;- }- };-- /**- * Reset to primary provider for next update check- */- private resetToPrimaryProvider = () => {- if (this.usingFallbackProvider) {- logger.info('Resetting to primary update provider (S3)');- this.usingFallbackProvider = false;- this.configureUpdateProvider();- }- };-private registerEvents() {logger.debug('Registering updater events');@@ -387,95 +420,93 @@ export class UpdaterManager {});autoUpdater.on('update-available', (info) => {- logger.info(`Update available: ${info.version}`);- this.updateAvailable = true;+ logger.info(+ `Update available: ${info.version} (activeGen=${this.activeGeneration}, currentGen=${this.checkGeneration})`,+ );- this.resetToPrimaryProvider();+ if (this.isStaleCheck()) return;- if (this.isManualCheck) {- this.mainWindow.broadcast('manualUpdateAvailable', info);- } else {- logger.info('Auto check found update, starting download automatically...');- this.downloadUpdate();- }+ this.updateAvailable = true;++ // Always auto-download+ logger.info('Update found, starting download automatically...');+ this.setStage('downloading', { updateInfo: info });+ this.downloadUpdate();});autoUpdater.on('update-not-available', (info) => {logger.info(`Update not available. Current: ${info.version}`);- this.resetToPrimaryProvider();-- if (this.isManualCheck) {- this.mainWindow.broadcast('manualUpdateNotAvailable', info);- }+ this.setStage('latest');+ setTimeout(() => {+ if (this.stage === 'latest') this.setStage('idle');+ }, 5000);});autoUpdater.on('error', async (err) => {const message = err instanceof Error ? err.message : String(err);- // Edge case: Release tag exists but update manifest assets aren't uploaded yet.- // Skip fallback switching and avoid user-facing errors.if (this.isMissingUpdateManifestError(err)) {logger.warn('[Updater] Update manifest not ready yet, skipping error handling:', message);- if (this.isManualCheck) {- this.mainWindow.broadcast('manualUpdateNotAvailable', this.getCurrentUpdateInfo());- }+ this.setStage('latest');+ setTimeout(() => {+ if (this.stage === 'latest') this.setStage('idle');+ }, 5000);return;}logger.error('Error in auto-updater:', err);logger.error('[Updater Error Context] Channel:', autoUpdater.channel);+ logger.error('[Updater Error Context] currentChannel:', this.currentChannel);logger.error('[Updater Error Context] allowPrerelease:', autoUpdater.allowPrerelease);- logger.error('[Updater Error Context] Build channel from config:', channel);- logger.error('[Updater Error Context] isStableChannel:', isStableChannel);logger.error('[Updater Error Context] UPDATE_SERVER_URL:', UPDATE_SERVER_URL || '(not set)');- logger.error('[Updater Error Context] usingFallbackProvider:', this.usingFallbackProvider);- logger.error('[Updater Error Context] GitHub config:', JSON.stringify(githubConfig));-- if (!this.usingFallbackProvider && isStableChannel && UPDATE_SERVER_URL) {- logger.info('Attempting fallback to GitHub provider...');- const fallbackSucceeded = await this.switchToFallbackAndRetry();- if (fallbackSucceeded) {- return;- }- }- if (this.isManualCheck) {- this.mainWindow.broadcast('updateError', err.message);- }+ this.mainWindow.broadcast('updateError', err.message);+ this.setStage('error', { error: message });+ setTimeout(() => {+ if (this.stage === 'error') this.setStage('idle');+ }, 3000);});autoUpdater.on('download-progress', (progressObj) => {logger.debug(`Download speed: ${progressObj.bytesPerSecond} - Downloaded ${progressObj.percent}% (${progressObj.transferred}/${progressObj.total})`,);- if (this.isManualCheck) {- this.mainWindow.broadcast('updateDownloadProgress', progressObj);- }+ this.latestProgress = progressObj;+ // Broadcast state without menu rebuild (too frequent)+ this.mainWindow.broadcast('updaterStateChanged', this.getUpdaterState());+ this.mainWindow.broadcast('updateDownloadProgress', progressObj);});autoUpdater.on('update-downloaded', (info) => {logger.info(`Update downloaded: ${info.version}`);this.downloading = false;+ this.setStage('downloaded', { updateInfo: info });this.mainWindow.broadcast('updateDownloaded', info);});logger.debug('Updater events registered');}+ /** Check if the current active check has been superseded by a channel switch */+ private isStaleCheck(): boolean {+ if (this.activeGeneration !== this.checkGeneration) {+ logger.info(+ `Discarding stale check result (activeGen=${this.activeGeneration}, currentGen=${this.checkGeneration})`,+ );+ return true;+ }+ return false;+ }+private isMissingUpdateManifestError(error: unknown): boolean {const message = error instanceof Error ? error.message : String(error ?? '');if (!message) return false;- // Expect patterns like:- // - "Cannot find latest-mac.yml ... HttpError: 404 ..."- // - "Cannot find stable.yml ... 404 ..."if (!/cannot find/i.test(message)) return false;if (!/\b404\b/.test(message)) return false;- // Match channel manifest filenames across platforms/architectures:- // latest.yml, latest-mac.yml, latest-linux.yml, stable.yml, stable-mac.yml, etc.- const manifestMatch = message.match(/\b(?:latest|stable)(?:-[\da-z]+)?\.yml\b/i);+ const manifestMatch = message.match(/\b(?:latest|stable|nightly|canary)(?:-[\da-z]+)?\.yml\b/i);return Boolean(manifestMatch);}diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/UpdaterManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/UpdaterManager.test.tsindex 5416b81a404..59d7cd91ef4 100644--- a/apps/desktop/src/main/core/infrastructure/__tests__/UpdaterManager.test.ts+++ b/apps/desktop/src/main/core/infrastructure/__tests__/UpdaterManager.test.ts@@ -66,11 +66,6 @@ vi.mock('@/utils/logger', () => ({vi.mock('@/modules/updater/configs', () => ({UPDATE_CHANNEL: 'stable',UPDATE_SERVER_URL: 'https://mock.update.server',- githubConfig: {- owner: 'lobehub',- repo: 'lobe-chat',- },- isStableChannel: true,updaterConfig: {app: {autoCheckUpdate: false,@@ -130,6 +125,13 @@ describe('UpdaterManager', () => {}),},isQuiting: false,+ menuManager: {+ rebuildAppMenu: vi.fn(),+ },+ storeManager: {+ get: vi.fn().mockReturnValue('stable'),+ set: vi.fn(),+ },} as unknown as AppCore;updaterManager = new UpdaterManager(mockApp);@@ -180,16 +182,22 @@ describe('UpdaterManager', () => {expect(autoUpdater.checkForUpdates).toHaveBeenCalled();});- it('should broadcast manualUpdateCheckStart when manual check', async () => {+ it('should broadcast updaterStateChanged with checking stage when checking', async () => {await updaterManager.checkForUpdates({ manual: true });- expect(mockBroadcast).toHaveBeenCalledWith('manualUpdateCheckStart');+ expect(mockBroadcast).toHaveBeenCalledWith(+ 'updaterStateChanged',+ expect.objectContaining({ stage: 'checking' }),+ );});- it('should not broadcast when auto check', async () => {+ it('should broadcast updaterStateChanged for auto check', async () => {await updaterManager.checkForUpdates({ manual: false });- expect(mockBroadcast).not.toHaveBeenCalledWith('manualUpdateCheckStart');+ expect(mockBroadcast).toHaveBeenCalledWith(+ 'updaterStateChanged',+ expect.objectContaining({ stage: 'checking' }),+ );});it('should ignore duplicate check requests while checking', async () => {@@ -207,16 +215,19 @@ describe('UpdaterManager', () => {expect(autoUpdater.checkForUpdates).toHaveBeenCalledTimes(1);});- it('should broadcast updateError when check fails during manual check', async () => {+ it('should broadcast updaterStateChanged with error stage when check fails', async () => {const error = new Error('Network error');vi.mocked(autoUpdater.checkForUpdates).mockRejectedValue(error);await updaterManager.checkForUpdates({ manual: true });- expect(mockBroadcast).toHaveBeenCalledWith('updateError', 'Network error');+ expect(mockBroadcast).toHaveBeenCalledWith(+ 'updaterStateChanged',+ expect.objectContaining({ stage: 'error', errorMessage: 'Network error' }),+ );});- it('should treat missing latest/stable yml 404 as not-available during manual check', async () => {+ it('should set stage to latest when missing manifest 404 (gap period)', async () => {const error = new Error('Cannot find latest-mac.yml in the latest release artifacts (https://github.com/lobehub/lobe-chat/releases/download/v2.0.0-next.311/latest-mac.yml): HttpError: 404',);@@ -225,11 +236,8 @@ describe('UpdaterManager', () => {await updaterManager.checkForUpdates({ manual: true });expect(mockBroadcast).toHaveBeenCalledWith(- 'manualUpdateNotAvailable',- expect.objectContaining({- releaseDate: expect.any(String),- version: expect.any(String),- }),+ 'updaterStateChanged',+ expect.objectContaining({ stage: 'latest' }),);expect(mockBroadcast).not.toHaveBeenCalledWith('updateError', expect.anything());});@@ -280,65 +288,37 @@ describe('UpdaterManager', () => {expect(autoUpdater.downloadUpdate).toHaveBeenCalledTimes(1);});- it('should broadcast updateDownloadStart when isManualCheck is true', async () => {- // Create a fresh manager to avoid state pollution from beforeEach+ it('should broadcast updaterStateChanged with downloading stage when download starts', async () => {const freshManager = new UpdaterManager(mockApp);-- // Setup fresh event capture- const freshEvents = new Map<string, (...args: any[]) => void>();- vi.mocked(autoUpdater.on).mockImplementation((event: string, handler: any) => {- freshEvents.set(event, handler);- return autoUpdater;- });await freshManager.initialize();- // Trigger a manual check to set isManualCheck = true- vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);- await freshManager.checkForUpdates({ manual: true });-- // Manually set updateAvailable without triggering auto-download- // Access private property to set state(freshManager as any).updateAvailable = true;-- // Clear previous broadcast callsmockBroadcast.mockClear();- // Now download should broadcast updateDownloadStart because isManualCheck is truevi.mocked(autoUpdater.downloadUpdate).mockResolvedValue([] as any);await freshManager.downloadUpdate();- expect(mockBroadcast).toHaveBeenCalledWith('updateDownloadStart');+ expect(mockBroadcast).toHaveBeenCalledWith(+ 'updaterStateChanged',+ expect.objectContaining({ stage: 'downloading' }),+ );});- it('should broadcast updateError when download fails with isManualCheck true', async () => {- // Create a fresh manager to avoid state pollution from beforeEach+ it('should broadcast updaterStateChanged with error stage when download fails', async () => {const freshManager = new UpdaterManager(mockApp);-- // Setup fresh event capture- const freshEvents = new Map<string, (...args: any[]) => void>();- vi.mocked(autoUpdater.on).mockImplementation((event: string, handler: any) => {- freshEvents.set(event, handler);- return autoUpdater;- });await freshManager.initialize();- // Trigger a manual check to set isManualCheck = true- vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);- await freshManager.checkForUpdates({ manual: true });-- // Manually set updateAvailable without triggering auto-download(freshManager as any).updateAvailable = true;-- // Clear previous broadcast callsmockBroadcast.mockClear();- // Setup error- const error = new Error('Download failed');- vi.mocked(autoUpdater.downloadUpdate).mockRejectedValue(error);+ vi.mocked(autoUpdater.downloadUpdate).mockRejectedValue(new Error('Download failed'));await freshManager.downloadUpdate();- expect(mockBroadcast).toHaveBeenCalledWith('updateError', 'Download failed');+ expect(mockBroadcast).toHaveBeenCalledWith(+ 'updaterStateChanged',+ expect.objectContaining({ stage: 'error', errorMessage: 'Download failed' }),+ );});});@@ -401,16 +381,24 @@ describe('UpdaterManager', () => {});describe('update-available', () => {- it('should broadcast manualUpdateAvailable when manual check', async () => {- // Trigger manual check first+ it('should broadcast updaterStateChanged and auto download when update available', async () => {vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);await updaterManager.checkForUpdates({ manual: true });+ vi.mocked(autoUpdater.downloadUpdate).mockResolvedValue([] as any);+const updateInfo = { version: '2.0.0' };const handler = registeredEvents.get('update-available');handler?.(updateInfo);- expect(mockBroadcast).toHaveBeenCalledWith('manualUpdateAvailable', updateInfo);+ expect(mockBroadcast).toHaveBeenCalledWith(+ 'updaterStateChanged',+ expect.objectContaining({+ stage: 'downloading',+ updateInfo: expect.objectContaining({ version: '2.0.0' }),+ }),+ );+ expect(autoUpdater.downloadUpdate).toHaveBeenCalled();});it('should auto download when auto check finds update', async () => {@@ -428,7 +416,7 @@ describe('UpdaterManager', () => {});describe('update-not-available', () => {- it('should broadcast manualUpdateNotAvailable when manual check', async () => {+ it('should broadcast updaterStateChanged with latest stage when manual check', async () => {vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);await updaterManager.checkForUpdates({ manual: true });@@ -436,19 +424,22 @@ describe('UpdaterManager', () => {const handler = registeredEvents.get('update-not-available');handler?.(info);- expect(mockBroadcast).toHaveBeenCalledWith('manualUpdateNotAvailable', info);+ expect(mockBroadcast).toHaveBeenCalledWith(+ 'updaterStateChanged',+ expect.objectContaining({ stage: 'latest' }),+ );});- it('should not broadcast when auto check', async () => {+ it('should broadcast updaterStateChanged when auto check finds no update', async () => {vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);await updaterManager.checkForUpdates({ manual: false });const handler = registeredEvents.get('update-not-available');handler?.({ version: '1.0.0' });- expect(mockBroadcast).not.toHaveBeenCalledWith(- 'manualUpdateNotAvailable',- expect.anything(),+ expect(mockBroadcast).toHaveBeenCalledWith(+ 'updaterStateChanged',+ expect.objectContaining({ stage: 'latest' }),);});});@@ -497,7 +488,7 @@ describe('UpdaterManager', () => {expect(mockBroadcast).toHaveBeenCalledWith('updateError', 'Update error');});- it('should not broadcast when auto check', async () => {+ it('should broadcast updateError when auto check has non-manifest error', async () => {vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);await updaterManager.checkForUpdates({ manual: false });@@ -505,10 +496,10 @@ describe('UpdaterManager', () => {const handler = registeredEvents.get('error');handler?.(error);- expect(mockBroadcast).not.toHaveBeenCalledWith('updateError', expect.anything());+ expect(mockBroadcast).toHaveBeenCalledWith('updateError', 'Update error');});- it('should not broadcast updateError for missing manifest 404 (gap period)', async () => {+ it('should set stage to latest (not error) for missing manifest 404 (gap period)', async () => {vi.mocked(autoUpdater.checkForUpdates).mockResolvedValue({} as any);await updaterManager.checkForUpdates({ manual: true });@@ -519,11 +510,8 @@ describe('UpdaterManager', () => {await handler?.(error);expect(mockBroadcast).toHaveBeenCalledWith(- 'manualUpdateNotAvailable',- expect.objectContaining({- releaseDate: expect.any(String),- version: expect.any(String),- }),+ 'updaterStateChanged',+ expect.objectContaining({ stage: 'latest' }),);expect(mockBroadcast).not.toHaveBeenCalledWith('updateError', expect.anything());});diff --git a/apps/desktop/src/main/locales/default/menu.ts b/apps/desktop/src/main/locales/default/menu.tsindex fe2e4e944e9..2b6382100cf 100644--- a/apps/desktop/src/main/locales/default/menu.ts+++ b/apps/desktop/src/main/locales/default/menu.ts@@ -1,5 +1,9 @@const menu = {'common.checkUpdates': 'Check for updates...',+ 'common.checkingUpdates': 'Checking for updates...',+ 'common.downloadingUpdate': 'Downloading update...',+ 'common.isLatestVersion': 'Already up to date',+ 'common.restartToUpdate': 'Restart to update','context.copyImage': 'Copy Image','context.copyImageAddress': 'Copy Image Address','context.copyLink': 'Copy Link',diff --git a/apps/desktop/src/main/menus/impls/macOS.test.ts b/apps/desktop/src/main/menus/impls/macOS.test.tsindex 44460b090d3..1264e275423 100644--- a/apps/desktop/src/main/menus/impls/macOS.test.ts+++ b/apps/desktop/src/main/menus/impls/macOS.test.ts@@ -1,4 +1,4 @@-import { Menu, app, shell } from 'electron';+import { app, Menu, shell } from 'electron';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';@@ -39,7 +39,7 @@ const createMockApp = () => {let translation = menuTranslations[key as keyof typeof menuTranslations] || key;if (params && typeof translation === 'string') {Object.keys(params).forEach((paramKey) => {- translation = translation.replace(+ translation = translation.replaceAll(new RegExp(`{{${paramKey}}}`, 'g'),params[paramKey] as string,);@@ -65,6 +65,8 @@ const createMockApp = () => {},updaterManager: {checkForUpdates: vi.fn(),+ getUpdaterState: vi.fn(() => ({ stage: 'idle' })),+ installNow: vi.fn(),simulateUpdateAvailable: vi.fn(),simulateDownloadProgress: vi.fn(),simulateUpdateDownloaded: vi.fn(),diff --git a/apps/desktop/src/main/menus/impls/macOS.ts b/apps/desktop/src/main/menus/impls/macOS.tsindex c9a1adce77c..3d7e8bfc0f5 100644--- a/apps/desktop/src/main/menus/impls/macOS.ts+++ b/apps/desktop/src/main/menus/impls/macOS.ts@@ -1,7 +1,8 @@-/* eslint-disable unicorn/no-array-push-push */-import { Menu, MenuItemConstructorOptions, app, clipboard, shell } from 'electron';import * as path from 'node:path';+import type { MenuItemConstructorOptions } from 'electron';+import { app, clipboard, Menu, shell } from 'electron';+import { isDev } from '@/const/env';import NotificationCtr from '@/controllers/NotificationCtr';import SystemController from '@/controllers/SystemCtr';@@ -78,12 +79,7 @@ export class MacOSMenu extends BaseMenuPlatform implements IMenuPlatform {},label: t('macOS.about', { appName }),},- {- click: () => {- this.app.updaterManager.checkForUpdates({ manual: true });- },- label: t('common.checkUpdates'),- },+ this.getUpdateMenuItem(t),{ type: 'separator' },{accelerator: 'Command+,',@@ -250,7 +246,7 @@ export class MacOSMenu extends BaseMenuPlatform implements IMenuPlatform {{click: () => {const logsPath = app.getPath('logs');- console.log(`[Menu] Opening logs directory: ${logsPath}`);+ console.info(`[Menu] Opening logs directory: ${logsPath}`);shell.openPath(logsPath).catch((err) => {console.error(`[Menu] Error opening path ${logsPath}:`, err);// Optionally show an error dialog to the user@@ -261,7 +257,7 @@ export class MacOSMenu extends BaseMenuPlatform implements IMenuPlatform {{click: () => {const userDataPath = app.getPath('userData');- console.log(`[Menu] Opening user data directory: ${userDataPath}`);+ console.info(`[Menu] Opening user data directory: ${userDataPath}`);shell.openPath(userDataPath).catch((err) => {console.error(`[Menu] Error opening path ${userDataPath}:`, err);// Optionally show an error dialog to the user@@ -390,6 +386,34 @@ export class MacOSMenu extends BaseMenuPlatform implements IMenuPlatform {return template;}+ private getUpdateMenuItem(t: (key: string, opts?: any) => string): MenuItemConstructorOptions {+ const { stage } = this.app.updaterManager.getUpdaterState();++ switch (stage) {+ case 'checking': {+ return { enabled: false, label: t('common.checkingUpdates') };+ }+ case 'downloading': {+ return { enabled: false, label: t('common.downloadingUpdate') };+ }+ case 'downloaded': {+ return {+ click: () => this.app.updaterManager.installNow(),+ label: t('common.restartToUpdate'),+ };+ }+ case 'latest': {+ return { enabled: false, label: t('common.isLatestVersion') };+ }+ default: {+ return {+ click: () => this.app.updaterManager.checkForUpdates({ manual: true }),+ label: t('common.checkUpdates'),+ };+ }+ }+ }+private getDefaultContextMenuTemplate(data?: ContextMenuData): MenuItemConstructorOptions[] {const t = this.app.i18n.ns('menu');const hasText = Boolean(data?.selectionText?.trim());diff --git a/apps/desktop/src/main/menus/impls/windows.test.ts b/apps/desktop/src/main/menus/impls/windows.test.tsindex ebfd36af73f..d097887a752 100644--- a/apps/desktop/src/main/menus/impls/windows.test.ts+++ b/apps/desktop/src/main/menus/impls/windows.test.ts@@ -1,4 +1,4 @@-import { Menu, app, shell } from 'electron';+import { app, Menu, shell } from 'electron';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';@@ -67,6 +67,11 @@ const createMockApp = () => {ns: vi.fn(() => mockT),},browserManager: {+ getMainWindow: vi.fn(() => ({+ broadcast: vi.fn(),+ loadUrl: vi.fn(),+ show: vi.fn(),+ })),showMainWindow: vi.fn(),retrieveByIdentifier: vi.fn(() => ({show: vi.fn(),@@ -74,6 +79,8 @@ const createMockApp = () => {},updaterManager: {checkForUpdates: vi.fn(),+ getUpdaterState: vi.fn(() => ({ stage: 'idle' })),+ installNow: vi.fn(),},} as unknown as App;};diff --git a/apps/desktop/src/main/menus/impls/windows.ts b/apps/desktop/src/main/menus/impls/windows.tsindex 2ade772978c..d54e5ec30b1 100644--- a/apps/desktop/src/main/menus/impls/windows.ts+++ b/apps/desktop/src/main/menus/impls/windows.ts@@ -1,5 +1,5 @@-/* eslint-disable unicorn/no-array-push-push */-import { Menu, MenuItemConstructorOptions, app, clipboard, shell } from 'electron';+import type { MenuItemConstructorOptions } from 'electron';+import { app, clipboard, Menu, shell } from 'electron';import { isDev } from '@/const/env';@@ -96,12 +96,7 @@ export class WindowsMenu extends BaseMenuPlatform implements IMenuPlatform {click: () => this.app.browserManager.retrieveByIdentifier('settings').show(),label: t('file.preferences'),},- {- click: () => {- this.app.updaterManager.checkForUpdates({ manual: true });- },- label: t('common.checkUpdates'),- },+ this.getUpdateMenuItem(t),{ type: 'separator' },{accelerator: 'Alt+F4',@@ -213,6 +208,34 @@ export class WindowsMenu extends BaseMenuPlatform implements IMenuPlatform {return template;}+ private getUpdateMenuItem(t: (key: string, opts?: any) => string): MenuItemConstructorOptions {+ const { stage } = this.app.updaterManager.getUpdaterState();++ switch (stage) {+ case 'checking': {+ return { enabled: false, label: t('common.checkingUpdates') };+ }+ case 'downloading': {+ return { enabled: false, label: t('common.downloadingUpdate') };+ }+ case 'downloaded': {+ return {+ click: () => this.app.updaterManager.installNow(),+ label: t('common.restartToUpdate'),+ };+ }+ case 'latest': {+ return { enabled: false, label: t('common.isLatestVersion') };+ }+ default: {+ return {+ click: () => this.app.updaterManager.checkForUpdates({ manual: true }),+ label: t('common.checkUpdates'),+ };+ }+ }+ }+private getDefaultContextMenuTemplate(data?: ContextMenuData): MenuItemConstructorOptions[] {const t = this.app.i18n.ns('menu');const hasText = Boolean(data?.selectionText?.trim());diff --git a/apps/desktop/src/main/modules/updater/configs.ts b/apps/desktop/src/main/modules/updater/configs.tsindex 8e67751759e..4d1ad38e9bb 100644--- a/apps/desktop/src/main/modules/updater/configs.ts+++ b/apps/desktop/src/main/modules/updater/configs.ts@@ -1,32 +1,27 @@+import type { UpdateChannel } from '@lobechat/electron-client-ipc';+import { isDev } from '@/const/env';import { getDesktopEnv } from '@/env';-// Update channel (stable, beta, alpha, etc.)-export const UPDATE_CHANNEL = getDesktopEnv().UPDATE_CHANNEL || 'stable';--// Determine if stable channel-export const isStableChannel = UPDATE_CHANNEL === 'stable' || !UPDATE_CHANNEL;+// Build-time default channel, can be overridden at runtime via store+const rawChannel = getDesktopEnv().UPDATE_CHANNEL || 'stable';+const VALID_CHANNELS = new Set<UpdateChannel>(['stable', 'nightly', 'canary']);+export const UPDATE_CHANNEL: UpdateChannel = VALID_CHANNELS.has(rawChannel as UpdateChannel)+ ? (rawChannel as UpdateChannel)+ : rawChannel === 'beta'+ ? 'nightly'+ : 'stable';-// Custom update server URL (for stable channel)-// e.g., https://releases.lobehub.com/stable+// S3 base URL for all channels+// e.g., https://releases.lobehub.com+// Each channel resolves to {base}/{channel}/export const UPDATE_SERVER_URL = getDesktopEnv().UPDATE_SERVER_URL;-// GitHub configuration (for beta/nightly channels, or as fallback)-export const githubConfig = {- owner: 'lobehub',- repo: 'lobe-chat',-};-export const updaterConfig = {- // Application update configurationapp: {- // Whether to auto-check for updatesautoCheckUpdate: true,- // Whether to auto-download updatesautoDownloadUpdate: true,- // Update check interval (milliseconds)checkUpdateInterval: 60 * 60 * 1000, // 1 hour},- // Whether to enable application updatesenableAppUpdate: !isDev,};diff --git a/apps/desktop/src/main/types/store.ts b/apps/desktop/src/main/types/store.tsindex 71a23b41661..6d65a2bd7ef 100644--- a/apps/desktop/src/main/types/store.ts+++ b/apps/desktop/src/main/types/store.ts@@ -1,4 +1,8 @@-import { DataSyncConfig, NetworkProxySettings } from '@lobechat/electron-client-ipc';+import type {+ DataSyncConfig,+ NetworkProxySettings,+ UpdateChannel,+} from '@lobechat/electron-client-ipc';export interface ElectronMainStore {dataSyncConfig: DataSyncConfig;@@ -13,6 +17,7 @@ export interface ElectronMainStore {shortcuts: Record<string, string>;storagePath: string;themeMode: 'dark' | 'light' | 'system';+ updateChannel: UpdateChannel;}export type StoreKey = keyof ElectronMainStore;diff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex 679ad317bef..b8c0d42c6d0 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -5,6 +5,7 @@"alert.cloud.desc": "All registered users get {{credit}} free computing credits per month—no setup needed. Includes global cloud sync and advanced web search.","alert.cloud.descOnMobile": "All registered users get {{credit}} free computing credits per month—no setup needed.","alert.cloud.title": "{{name}} beta is live",+ "alreadyUpToDate": "Already Up to Date","appLoading.appIdle": "Ready to start","appLoading.appInitializing": "Application is starting...","appLoading.failed": "Something went wrong during startup. View details to troubleshoot, or try again later.",@@ -211,6 +212,7 @@"delete": "Delete","document": "User Manual","download": "Download",+ "downloadingUpdate": "Downloading {{percent}}%","duplicate": "Duplicate","edit": "Edit","errors.invalidFileFormat": "Invalid file format",@@ -360,6 +362,7 @@"releaseNotes": "Version Details","rename": "Rename","reset": "Reset",+ "restartToUpdate": "Restart to Update","retry": "Retry","run": "Run","save": "Save",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 3813b728b4f..c10f228bfec 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -694,6 +694,15 @@"tab.agent": "Agent Service","tab.all": "All","tab.apikey": "API Key Management",+ "tab.beta": "Beta",+ "tab.beta.updateChannel.canary": "Canary",+ "tab.beta.updateChannel.canaryDesc": "Triggered on every PR merge, multiple builds per day. Most unstable.",+ "tab.beta.updateChannel.desc": "By default, get notifications for stable updates. Nightly and Canary channels receive pre-release builds that may be unstable for production work.",+ "tab.beta.updateChannel.nightly": "Nightly",+ "tab.beta.updateChannel.nightlyDesc": "Automated daily builds with the latest changes.",+ "tab.beta.updateChannel.stable": "Stable",+ "tab.beta.updateChannel.stableDesc": "Production-ready releases.",+ "tab.beta.updateChannel.title": "Update Channel","tab.chatAppearance": "Chat Appearance","tab.common": "Appearance","tab.experiment": "Experiment",diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex 3367fe0a7e2..9f3dd62f672 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -5,6 +5,7 @@"alert.cloud.desc": "所有注册用户每月可获得 {{credit}} 免费计算额度—无需设置。包括全球云同步和高级网页搜索功能。","alert.cloud.descOnMobile": "所有注册用户每月可获得 {{credit}} 免费计算额度—无需设置。","alert.cloud.title": "{{name}} 开始公测",+ "alreadyUpToDate": "已是最新版本","appLoading.appIdle": "准备启动","appLoading.appInitializing": "应用启动中…","appLoading.failed": "启动时遇到一点问题。你可以查看详情继续排查,或稍后再试一次",@@ -211,6 +212,7 @@"delete": "删除","document": "使用文档","download": "下载",+ "downloadingUpdate": "正在下载 {{percent}}%","duplicate": "创建副本","edit": "编辑","errors.invalidFileFormat": "文件格式错误",@@ -360,6 +362,7 @@"releaseNotes": "版本详情","rename": "重命名","reset": "重置",+ "restartToUpdate": "重启以更新","retry": "重试","run": "运行","save": "保存",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 29b1f05d44a..a31952f5ea9 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -694,6 +694,15 @@"tab.agent": "助理服务","tab.all": "全部","tab.apikey": "API Key 管理",+ "tab.beta": "Beta",+ "tab.beta.updateChannel.canary": "Canary",+ "tab.beta.updateChannel.canaryDesc": "每次 PR 合并触发构建,一天可能多次。最不稳定。",+ "tab.beta.updateChannel.desc": "默认接收稳定版更新通知。Nightly 和 Canary 通道将接收预发布版本,可能不适合生产使用。",+ "tab.beta.updateChannel.nightly": "Nightly",+ "tab.beta.updateChannel.nightlyDesc": "每日自动构建,包含最新更改。",+ "tab.beta.updateChannel.stable": "稳定版",+ "tab.beta.updateChannel.stableDesc": "正式发布版本。",+ "tab.beta.updateChannel.title": "更新通道","tab.chatAppearance": "聊天外观","tab.common": "外观","tab.experiment": "实验",diff --git a/packages/electron-client-ipc/src/events/update.ts b/packages/electron-client-ipc/src/events/update.tsindex 6c68822b077..e7166710c10 100644--- a/packages/electron-client-ipc/src/events/update.ts+++ b/packages/electron-client-ipc/src/events/update.ts@@ -1,12 +1,10 @@-import type { ProgressInfo, UpdateInfo } from '../types';+import type { ProgressInfo, UpdateChannel, UpdateInfo, UpdaterState } from '../types';export interface AutoUpdateBroadcastEvents {- manualUpdateAvailable: (info: UpdateInfo) => void;- manualUpdateCheckStart: () => void;- manualUpdateNotAvailable: (info: UpdateInfo) => void;+ updateChannelChanged: (channel: UpdateChannel) => void;updateDownloaded: (info: UpdateInfo) => void;updateDownloadProgress: (progress: ProgressInfo) => void;- updateDownloadStart: () => void;updateError: (message: string) => void;+ updaterStateChanged: (state: UpdaterState) => void;updateWillInstallLater: () => void;}diff --git a/packages/electron-client-ipc/src/types/update.ts b/packages/electron-client-ipc/src/types/update.tsindex dbb02673ebc..74fb83e1d9a 100644--- a/packages/electron-client-ipc/src/types/update.ts+++ b/packages/electron-client-ipc/src/types/update.ts@@ -1,3 +1,5 @@+export type UpdateChannel = 'stable' | 'nightly' | 'canary';+export interface ReleaseNoteInfo {/*** The note.@@ -21,3 +23,12 @@ export interface UpdateInfo {releaseNotes?: string | ReleaseNoteInfo[];version: string;}++export type UpdaterStage = 'idle' | 'checking' | 'downloading' | 'downloaded' | 'latest' | 'error';++export interface UpdaterState {+ errorMessage?: string;+ progress?: ProgressInfo;+ stage: UpdaterStage;+ updateInfo?: UpdateInfo;+}diff --git a/scripts/electronWorkflow/mergeMacReleaseFiles.js b/scripts/electronWorkflow/mergeMacReleaseFiles.jsindex caa2881b41e..b86393feebe 100644--- a/scripts/electronWorkflow/mergeMacReleaseFiles.js+++ b/scripts/electronWorkflow/mergeMacReleaseFiles.js@@ -3,15 +3,14 @@ import path from 'node:path';import YAML from 'yaml';-// 配置-// Support both stable-mac.yml (stable channel) and latest-mac.yml (fallback)-const STABLE_outputFileName = 'stable-mac.yml';-const LATEST_outputFileName = 'latest-mac.yml';const RELEASE_DIR = path.resolve('release');+// All channel manifest prefixes to process+const CHANNEL_PREFIXES = ['stable', 'nightly', 'canary', 'latest'];+/**- * 检测 latest-mac.yml 文件的平台类型- * @param {Object} yamlContent - YAML 文件内容+ * Detect platform type from YAML content+ * @param {Object} yamlContent* @returns {'x64' | 'arm64' | 'both' | 'none'}*/function detectPlatform(yamlContent) {@@ -25,13 +24,12 @@ function detectPlatform(yamlContent) {}/**- * 合并两个 latest-mac.yml 文件- * @param {Object} x64Content - x64 平台的 YAML 内容- * @param {Object} arm64Content - ARM64 平台的 YAML 内容- * @returns {string} 合并后的 YAML 字符串+ * Merge x64 and ARM64 YAML files+ * @param {Object} x64Content+ * @param {Object} arm64Content+ * @returns {string}*/function mergeYamlFiles(x64Content, arm64Content) {- // 以 ARM64 为基础(Apple Silicon 优先)const merged = {...arm64Content,files: [...arm64Content.files, ...x64Content.files],@@ -40,11 +38,6 @@ function mergeYamlFiles(x64Content, arm64Content) {return YAML.stringify(merged);}-/**- * 读取本地文件- * @param {string} filePath - 文件路径- * @returns {string | null} 文件内容或 null- */function readLocalFile(filePath) {try {if (fs.existsSync(filePath)) {@@ -60,11 +53,6 @@ function readLocalFile(filePath) {}}-/**- * 写入本地文件- * @param {string} filePath - 文件路径- * @param {string} content - 文件内容- */function writeLocalFile(filePath, content) {try {fs.writeFileSync(filePath, content, 'utf8');@@ -76,118 +64,107 @@ function writeLocalFile(filePath, content) {}/**- * 主函数+ * Merge mac YAML files for a given channel prefix+ * @param {string} prefix - e.g. 'stable', 'nightly', 'canary', 'latest'+ * @param {string[]} releaseFiles - files in release directory*/-async function main() {- try {- console.log('🚀 Starting macOS Release file merge');- console.log(`📁 Working directory: ${RELEASE_DIR}`);+function mergeForPrefix(prefix, releaseFiles) {+ const outputFileName = `${prefix}-mac.yml`;+ const macYmlFiles = releaseFiles.filter(+ (f) => f.startsWith(`${prefix}-mac`) && f.endsWith('.yml'),+ );++ if (macYmlFiles.length === 0) {+ console.log(`⚠️ No ${prefix}-mac*.yml files found, skipping`);+ return;+ }- // 1. 检查 release 目录下的所有文件- const releaseFiles = fs.readdirSync(RELEASE_DIR);- console.log(`📂 Files in release directory: ${releaseFiles.join(', ')}`);+ console.log(`\n🔍 Processing ${prefix} channel: ${macYmlFiles.join(', ')} -> ${outputFileName}`);- // 2. 查找所有 stable-mac*.yml 和 latest-mac*.yml 文件- // Prioritize stable-mac*.yml, fallback to latest-mac*.yml- const stableMacYmlFiles = releaseFiles.filter(- (f) => f.startsWith('stable-mac') && f.endsWith('.yml'),- );- const latestMacYmlFiles = releaseFiles.filter(- (f) => f.startsWith('latest-mac') && f.endsWith('.yml'),- );-- // Use stable files if available, otherwise use latest- const macYmlFiles = stableMacYmlFiles.length > 0 ? stableMacYmlFiles : latestMacYmlFiles;- const outputFileName =- stableMacYmlFiles.length > 0 ? STABLE_outputFileName : LATEST_outputFileName;-- console.log(`🔍 Found stable macOS YAML files: ${stableMacYmlFiles.join(', ') || 'none'}`);- console.log(`🔍 Found latest macOS YAML files: ${latestMacYmlFiles.join(', ') || 'none'}`);- console.log(`🔍 Using files: ${macYmlFiles.join(', ')} -> ${outputFileName}`);-- if (macYmlFiles.length === 0) {- console.log('⚠️ No macOS YAML files found, skipping merge');- return;- }+ const macFiles = [];- // 3. 处理找到的文件,识别平台- const macFiles = [];-- for (const fileName of macYmlFiles) {- const filePath = path.join(RELEASE_DIR, fileName);- const content = readLocalFile(filePath);-- if (!content) continue;-- try {- const yamlContent = YAML.parse(content);- const platform = detectPlatform(yamlContent);-- if (platform === 'x64' || platform === 'arm64') {- macFiles.push({ content, filename: fileName, platform, yaml: yamlContent });- console.log(`🔍 Detected ${platform} platform in ${fileName}`);- } else if (platform === 'both') {- console.log(`✅ Found already merged file: ${fileName}`);- // 如果已经是合并后的文件,直接复制为最终文件- writeLocalFile(path.join(RELEASE_DIR, outputFileName), content);- return;- } else {- console.log(`⚠️ Unknown platform type: ${platform} in ${fileName}`);- }- } catch (error) {- console.warn(`⚠️ Failed to parse ${fileName}:`, error);+ for (const fileName of macYmlFiles) {+ const filePath = path.join(RELEASE_DIR, fileName);+ const content = readLocalFile(filePath);++ if (!content) continue;++ try {+ const yamlContent = YAML.parse(content);+ const platform = detectPlatform(yamlContent);++ if (platform === 'x64' || platform === 'arm64') {+ macFiles.push({ content, filename: fileName, platform, yaml: yamlContent });+ console.log(`🔍 Detected ${platform} platform in ${fileName}`);+ } else if (platform === 'both') {+ console.log(`✅ Found already merged file: ${fileName}`);+ writeLocalFile(path.join(RELEASE_DIR, outputFileName), content);+ return;+ } else {+ console.log(`⚠️ Unknown platform type: ${platform} in ${fileName}`);}+ } catch (error) {+ console.warn(`⚠️ Failed to parse ${fileName}:`, error);}+ }- // 4. 检查是否有两个不同平台的文件- const x64Files = macFiles.filter((f) => f.platform === 'x64');- const arm64Files = macFiles.filter((f) => f.platform === 'arm64');+ const x64Files = macFiles.filter((f) => f.platform === 'x64');+ const arm64Files = macFiles.filter((f) => f.platform === 'arm64');- if (x64Files.length === 0 && arm64Files.length === 0) {- console.log('⚠️ No valid platform files found');- return;- }+ if (x64Files.length === 0 && arm64Files.length === 0) {+ console.log(`⚠️ No valid platform files found for ${prefix}`);+ return;+ }- if (x64Files.length === 0) {- console.log('⚠️ No x64 files found, using ARM64 only');- writeLocalFile(path.join(RELEASE_DIR, outputFileName), arm64Files[0].content);- return;- }+ if (x64Files.length === 0) {+ console.log(`⚠️ No x64 files found for ${prefix}, using ARM64 only`);+ writeLocalFile(path.join(RELEASE_DIR, outputFileName), arm64Files[0].content);+ return;+ }- if (arm64Files.length === 0) {- console.log('⚠️ No ARM64 files found, using x64 only');- writeLocalFile(path.join(RELEASE_DIR, outputFileName), x64Files[0].content);- return;- }+ if (arm64Files.length === 0) {+ console.log(`⚠️ No ARM64 files found for ${prefix}, using x64 only`);+ writeLocalFile(path.join(RELEASE_DIR, outputFileName), x64Files[0].content);+ return;+ }++ const x64File = x64Files[0];+ const arm64File = arm64Files[0];- // 5. 合并 x64 和 ARM64 文件- const x64File = x64Files[0];- const arm64File = arm64Files[0];+ console.log(`🔄 Merging ${x64File.filename} (x64) and ${arm64File.filename} (ARM64)...`);+ const mergedContent = mergeYamlFiles(x64File.yaml, arm64File.yaml);- console.log(`🔄 Merging ${x64File.filename} (x64) and ${arm64File.filename} (ARM64)...`);- const mergedContent = mergeYamlFiles(x64File.yaml, arm64File.yaml);+ const mergedFilePath = path.join(RELEASE_DIR, outputFileName);+ writeLocalFile(mergedFilePath, mergedContent);- // 6. 保存合并后的文件- const mergedFilePath = path.join(RELEASE_DIR, outputFileName);- writeLocalFile(mergedFilePath, mergedContent);+ const mergedYaml = YAML.parse(mergedContent);+ const finalPlatform = detectPlatform(mergedYaml);- // 7. 验证合并结果- const mergedYaml = YAML.parse(mergedContent);- const finalPlatform = detectPlatform(mergedYaml);+ if (finalPlatform === 'both') {+ console.log(`✅ Successfully merged both x64 and ARM64 platforms for ${prefix}`);+ console.log(`📊 Final file contains ${mergedYaml.files.length} files`);+ } else {+ console.warn(`⚠️ Merge result unexpected: ${finalPlatform}`);+ }+}++async function main() {+ try {+ console.log('🚀 Starting macOS Release file merge');+ console.log(`📁 Working directory: ${RELEASE_DIR}`);++ const releaseFiles = fs.readdirSync(RELEASE_DIR);+ console.log(`📂 Files in release directory: ${releaseFiles.join(', ')}`);- if (finalPlatform === 'both') {- console.log('✅ Successfully merged both x64 and ARM64 platforms');- console.log(`📊 Final file contains ${mergedYaml.files.length} files`);- } else {- console.warn(`⚠️ Merge result unexpected: ${finalPlatform}`);+ for (const prefix of CHANNEL_PREFIXES) {+ mergeForPrefix(prefix, releaseFiles);}- console.log('🎉 Merge complete!');+ console.log('\n🎉 Merge complete!');} catch (error) {console.error('❌ Error during merge:', error);process.exit(1);}}-// 运行主函数await main();diff --git a/src/app/spa/[variants]/[[...path]]/route.ts b/src/app/spa/[variants]/[[...path]]/route.tsindex 883befa0a95..0e8aba197d9 100644--- a/src/app/spa/[variants]/[[...path]]/route.ts+++ b/src/app/spa/[variants]/[[...path]]/route.ts@@ -19,8 +19,6 @@ import {} from '@/types/spaServerConfig';import { RouteVariants } from '@/utils/server/routeVariants';-export const dynamic = 'force-static';-export function generateStaticParams() {const mobileOptions = isDesktop ? [false] : [true, false];const staticLocales: Locales[] = ['en-US', 'zh-CN'];diff --git a/src/features/Electron/titlebar/TitleBar.tsx b/src/features/Electron/titlebar/TitleBar.tsxindex 3150123da61..d5807473451 100644--- a/src/features/Electron/titlebar/TitleBar.tsx+++ b/src/features/Electron/titlebar/TitleBar.tsx@@ -1,8 +1,7 @@import { TITLE_BAR_HEIGHT } from '@lobechat/desktop-bridge';-import { useWatchBroadcast } from '@lobechat/electron-client-ipc';import { Flexbox } from '@lobehub/ui';import { Divider } from 'antd';-import { memo, useMemo, useRef } from 'react';+import { memo, useMemo } from 'react';import { useElectronStore } from '@/store/electron';import { electronStylish } from '@/styles/electron';@@ -10,7 +9,6 @@ import { isMacOS } from '@/utils/platform';import Connection from '../connection/Connection';import { useWatchThemeUpdate } from '../system/useWatchThemeUpdate';-import { useUpdateModal } from '../updater/UpdateModal';import { UpdateNotification } from '../updater/UpdateNotification';import NavigationBar from './NavigationBar';import WinControl from './WinControl';@@ -26,19 +24,6 @@ const TitleBar = memo(() => {initElectronAppState();useWatchThemeUpdate();- const { open: openUpdateModal } = useUpdateModal();- const updateModalOpenRef = useRef(false);-- useWatchBroadcast('manualUpdateCheckStart', () => {- if (updateModalOpenRef.current) return;- updateModalOpenRef.current = true;- openUpdateModal({- onAfterClose: () => {- updateModalOpenRef.current = false;- },- });- });-const showWinControl = isAppStateInit && !isMac;const padding = useMemo(() => {diff --git a/src/features/Electron/updater/UpdateModal.tsx b/src/features/Electron/updater/UpdateModal.tsxdeleted file mode 100644index ee3fd444907..00000000000--- a/src/features/Electron/updater/UpdateModal.tsx+++ /dev/null@@ -1,297 +0,0 @@-import { type ProgressInfo, type UpdateInfo } from '@lobechat/electron-client-ipc';-import { useWatchBroadcast } from '@lobechat/electron-client-ipc';-import { type ModalInstance } from '@lobehub/ui';-import { Button, createModal, Flexbox } from '@lobehub/ui';-import { App, Progress, Spin } from 'antd';-import React, { memo, useCallback, useEffect, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { autoUpdateService } from '@/services/electron/autoUpdate';-import { formatSpeed } from '@/utils/format';--type UpdateStage = 'checking' | 'available' | 'latest' | 'downloading' | 'downloaded';--interface ModalUpdateOptions {- closable?: boolean;- keyboard?: boolean;- maskClosable?: boolean;- title?: React.ReactNode;-}--interface UpdateModalContentProps {- onClose: () => void;- setModalProps: (props: ModalUpdateOptions) => void;-}--const UpdateModalContent = memo<UpdateModalContentProps>(({ onClose, setModalProps }) => {- const { t } = useTranslation(['electron', 'common']);- const { modal } = App.useApp();- const errorHandledRef = useRef(false);- const isClosingRef = useRef(false);-- const [stage, setStage] = useState<UpdateStage>('checking');- const [updateAvailableInfo, setUpdateAvailableInfo] = useState<UpdateInfo | null>(null);- const [downloadedInfo, setDownloadedInfo] = useState<UpdateInfo | null>(null);- const [progress, setProgress] = useState<ProgressInfo | null>(null);- const [latestVersionInfo, setLatestVersionInfo] = useState<UpdateInfo | null>(null);-- useEffect(() => {- const isDownloading = stage === 'downloading';- const modalTitle = (() => {- switch (stage) {- case 'checking': {- return t('updater.checkingUpdate');- }- case 'available': {- return t('updater.newVersionAvailable');- }- case 'downloading': {- return t('updater.downloadingUpdate');- }- case 'downloaded': {- return t('updater.updateReady');- }- case 'latest': {- return t('updater.isLatestVersion');- }- default: {- return '';- }- }- })();-- setModalProps({- closable: !isDownloading,- keyboard: !isDownloading,- maskClosable: !isDownloading,- title: modalTitle,- });- }, [setModalProps, stage, t]);-- useWatchBroadcast('manualUpdateAvailable', (info: UpdateInfo) => {- if (isClosingRef.current) return;- setStage('available');- setUpdateAvailableInfo(info);- setDownloadedInfo(null);- setLatestVersionInfo(null);- });-- useWatchBroadcast('manualUpdateNotAvailable', (info: UpdateInfo) => {- if (isClosingRef.current) return;- setStage('latest');- setLatestVersionInfo(info);- setUpdateAvailableInfo(null);- setDownloadedInfo(null);- setProgress(null);- });-- useWatchBroadcast('updateDownloadStart', () => {- if (isClosingRef.current) return;- setStage('downloading');- setProgress({ bytesPerSecond: 0, percent: 0, total: 0, transferred: 0 });- setUpdateAvailableInfo(null);- setLatestVersionInfo(null);- });-- useWatchBroadcast('updateDownloadProgress', (progressInfo: ProgressInfo) => {- if (isClosingRef.current) return;- setProgress(progressInfo);- });-- useWatchBroadcast('updateDownloaded', (info: UpdateInfo) => {- if (isClosingRef.current) return;- setStage('downloaded');- setDownloadedInfo(info);- setProgress(null);- setUpdateAvailableInfo(null);- setLatestVersionInfo(null);- });-- useWatchBroadcast('updateError', (message: string) => {- if (isClosingRef.current || errorHandledRef.current) return;- errorHandledRef.current = true;- isClosingRef.current = true;- onClose();- modal.error({ content: message, title: t('updater.updateError') });- });-- const closeModal = () => {- if (isClosingRef.current) return;- errorHandledRef.current = true;- isClosingRef.current = true;- onClose();- };-- const handleDownload = () => {- if (!updateAvailableInfo) return;- autoUpdateService.downloadUpdate();- };-- const handleInstallNow = () => {- autoUpdateService.installNow();- closeModal();- };-- const handleInstallLater = () => {- autoUpdateService.installLater();- closeModal();- };-- const renderReleaseNotes = (notes?: UpdateInfo['releaseNotes']) => {- if (!notes) return null;- return (- <div- dangerouslySetInnerHTML={{ __html: notes as string }}- style={{- borderRadius: 4,- marginTop: 8,- maxHeight: 300,- overflow: 'auto',- padding: '8px 12px',- }}- />- );- };-- const renderBody = () => {- switch (stage) {- case 'checking': {- return (- <Spin spinning>- <div style={{ padding: '20px', textAlign: 'center' }}>- {t('updater.checkingUpdateDesc')}- </div>- </Spin>- );- }- case 'available': {- return (- <>- <h4>- {t('updater.newVersionAvailableDesc', { version: updateAvailableInfo?.version })}- </h4>- {renderReleaseNotes(updateAvailableInfo?.releaseNotes)}- </>- );- }- case 'downloading': {- const percent = progress ? Math.round(progress.percent) : 0;- return (- <div style={{ padding: '20px 0' }}>- <Progress percent={percent} status="active" />- <div style={{ fontSize: 12, marginTop: 8, textAlign: 'center' }}>- {t('updater.downloadingUpdateDesc', { percent })}- {progress && progress.bytesPerSecond > 0 && (- <span>{formatSpeed(progress.bytesPerSecond)}</span>- )}- </div>- </div>- );- }- case 'downloaded': {- return (- <>- <h4>{t('updater.updateReadyDesc', { version: downloadedInfo?.version })}</h4>- {renderReleaseNotes(downloadedInfo?.releaseNotes)}- </>- );- }- case 'latest': {- return <p>{t('updater.isLatestVersionDesc', { version: latestVersionInfo?.version })}</p>;- }- default: {- return null;- }- }- };-- const renderActions = () => {- if (stage === 'downloading') return null;-- let actions: React.ReactNode[] = [];-- if (stage === 'checking') {- actions = [- <Button key="cancel" onClick={closeModal}>- {t('cancel', { ns: 'common' })}- </Button>,- ];- }-- if (stage === 'available') {- actions = [- <Button key="cancel" onClick={closeModal}>- {t('cancel', { ns: 'common' })}- </Button>,- <Button key="download" type="primary" onClick={handleDownload}>- {t('updater.downloadNewVersion')}- </Button>,- ];- }-- if (stage === 'downloaded') {- actions = [- <Button key="later" onClick={handleInstallLater}>- {t('updater.installLater')}- </Button>,- <Button key="now" type="primary" onClick={handleInstallNow}>- {t('updater.restartAndInstall')}- </Button>,- ];- }-- if (stage === 'latest') {- actions = [- <Button key="ok" type="primary" onClick={closeModal}>- {t('ok', { ns: 'common' })}- </Button>,- ];- }-- if (actions.length === 0) return null;-- return (- <Flexbox horizontal gap={8} justify="end">- {actions}- </Flexbox>- );- };-- return (- <Flexbox gap={16} style={{ padding: 16 }}>- <div>{renderBody()}</div>- {renderActions()}- </Flexbox>- );-});--UpdateModalContent.displayName = 'UpdateModalContent';--interface UpdateModalOpenProps {- onAfterClose?: () => void;-}--export const useUpdateModal = () => {- const instanceRef = useRef<ModalInstance | null>(null);-- const open = useCallback((props?: UpdateModalOpenProps) => {- const setModalProps = (nextProps: ModalUpdateOptions) => {- instanceRef.current?.update?.(nextProps);- };-- const handleClose = () => {- instanceRef.current?.close();- };-- instanceRef.current = createModal({- afterClose: props?.onAfterClose,- children: <UpdateModalContent setModalProps={setModalProps} onClose={handleClose} />,- footer: null,- keyboard: true,- maskClosable: true,- title: '',- });- }, []);-- return { open };-};diff --git a/src/locales/default/common.ts b/src/locales/default/common.tsindex 19cc9688b12..cd0fdb99e49 100644--- a/src/locales/default/common.ts+++ b/src/locales/default/common.ts@@ -34,7 +34,10 @@ export default {'Current topic is not saved, please save it first to use subtopic feature','cancel': 'Cancel','changelog': 'Changelog',+ 'alreadyUpToDate': 'Already Up to Date','checkForUpdates': 'Check for Updates',+ 'downloadingUpdate': 'Downloading {{percent}}%',+ 'restartToUpdate': 'Restart to Update','clientDB.autoInit.title': 'Initializing PGlite Database','clientDB.error.desc':'PGlite failed to initialize. Retry first. If it helps, open Self-serve fixes and follow the steps. Still stuck after a few tries? Use Report issue to send us the error details.',diff --git a/src/locales/default/setting.ts b/src/locales/default/setting.tsindex e4a7454932d..9a49437ef1f 100644--- a/src/locales/default/setting.ts+++ b/src/locales/default/setting.ts@@ -794,6 +794,17 @@ When I am ___, I need ___'systemAgent.translation.title': 'Message Translation Agent','tab.about': 'About','tab.addAgentSkill': 'Add Agent Skill',+ 'tab.beta': 'Beta',+ 'tab.beta.updateChannel.canary': 'Canary',+ 'tab.beta.updateChannel.canaryDesc':+ 'Triggered on every PR merge, multiple builds per day. Most unstable.',+ 'tab.beta.updateChannel.desc':+ 'By default, get notifications for stable updates. Nightly and Canary channels receive pre-release builds that may be unstable for production work.',+ 'tab.beta.updateChannel.nightly': 'Nightly',+ 'tab.beta.updateChannel.nightlyDesc': 'Automated daily builds with the latest changes.',+ 'tab.beta.updateChannel.stable': 'Stable',+ 'tab.beta.updateChannel.stableDesc': 'Production-ready releases.',+ 'tab.beta.updateChannel.title': 'Update Channel','tab.addCustomMcp': 'Add Custom MCP Skill','tab.addCustomMcp.desc': 'Manually configure a custom MCP server','tab.addCustomSkill': 'Add',diff --git a/src/routes/(main)/settings/about/features/Version.tsx b/src/routes/(main)/settings/about/features/Version.tsxindex eaa1a48a4ed..c8461aa303f 100644--- a/src/routes/(main)/settings/about/features/Version.tsx+++ b/src/routes/(main)/settings/about/features/Version.tsx@@ -1,8 +1,12 @@import { BRANDING_NAME } from '@lobechat/business-const';-import { getElectronIpc } from '@lobechat/electron-client-ipc';+import {+ getElectronIpc,+ type UpdaterState,+ useWatchBroadcast,+} from '@lobechat/electron-client-ipc';import { Block, Button, Flexbox, Tag } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';-import { memo, useMemo } from 'react';+import { memo, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { ProductLogo } from '@/components/Branding';@@ -32,6 +36,73 @@ const Version = memo<{ mobile?: boolean }>(({ mobile }) => {const showServerVersion = serverVersion && serverVersion !== CURRENT_VERSION;const isDesktop = useMemo(() => !!getElectronIpc(), []);+ const [updaterState, setUpdaterState] = useState<UpdaterState>({ stage: 'idle' });++ useEffect(() => {+ if (!isDesktop) return;+ autoUpdateService.getUpdaterState().then(setUpdaterState);+ }, [isDesktop]);++ useWatchBroadcast('updaterStateChanged', (state: UpdaterState) => {+ setUpdaterState(state);+ });++ const renderUpdateButton = () => {+ if (!isDesktop) {+ if (hasNewVersion) {+ return (+ <a href={MANUAL_UPGRADE_URL} rel="noreferrer" style={{ flex: 1 }} target="_blank">+ <Button block={mobile} type={'primary'}>+ {t('upgradeVersion.action')}+ </Button>+ </a>+ );+ }+ return null;+ }++ const { stage, progress } = updaterState;++ switch (stage) {+ case 'checking': {+ return (+ <Button loading block={mobile}>+ {t('checkForUpdates')}+ </Button>+ );+ }+ case 'downloading': {+ const percent = progress ? Math.round(progress.percent) : 0;+ return (+ <Button loading block={mobile}>+ {t('downloadingUpdate', { percent })}+ </Button>+ );+ }+ case 'downloaded': {+ return (+ <Button block={mobile} type="primary" onClick={() => void autoUpdateService.installNow()}>+ {t('restartToUpdate')}+ </Button>+ );+ }+ case 'latest': {+ return (+ <Button disabled block={mobile}>+ {t('alreadyUpToDate')}+ </Button>+ );+ }+ default: {+ return (+ <Button block={mobile} onClick={() => void autoUpdateService.checkUpdate()}>+ {t('checkForUpdates')}+ </Button>+ );+ }+ }+ };+return (<Flexboxalign={mobile ? 'stretch' : 'center'}@@ -72,18 +143,7 @@ const Version = memo<{ mobile?: boolean }>(({ mobile }) => {<a href={CHANGELOG_URL} rel="noreferrer" style={{ flex: 1 }} target="_blank"><Button block={mobile}>{t('changelog')}</Button></a>- {isDesktop && !hasNewVersion && (- <Button block={mobile} onClick={() => void autoUpdateService.checkUpdate()}>- {t('checkForUpdates')}- </Button>- )}- {hasNewVersion && !isDesktop && (- <a href={MANUAL_UPGRADE_URL} rel="noreferrer" style={{ flex: 1 }} target="_blank">- <Button block={mobile} type={'primary'}>- {t('upgradeVersion.action')}- </Button>- </a>- )}+ {renderUpdateButton()}</Flexbox></Flexbox>);diff --git a/src/routes/(main)/settings/beta/features/UpdateChannel.tsx b/src/routes/(main)/settings/beta/features/UpdateChannel.tsxnew file mode 100644index 00000000000..52c45a9cd62--- /dev/null+++ b/src/routes/(main)/settings/beta/features/UpdateChannel.tsx@@ -0,0 +1,56 @@+'use client';++import { FORM_STYLE } from '@lobechat/const';+import { Form } from '@lobehub/ui';+import { Select } from '@lobehub/ui/base-ui';+import { memo, useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { autoUpdateService } from '@/services/electron/autoUpdate';++type UpdateChannelValue = 'canary' | 'nightly' | 'stable';++const UpdateChannel = memo(() => {+ const { t } = useTranslation('setting');+ const [channel, setChannel] = useState<UpdateChannelValue>('stable');++ useEffect(() => {+ autoUpdateService+ .getUpdateChannel()+ .then(setChannel)+ .catch(() => {});+ }, []);++ const handleChange = useCallback((value: UpdateChannelValue) => {+ setChannel(value);+ autoUpdateService.setUpdateChannel(value);+ }, []);++ const channelOptions = [+ { label: t('tab.beta.updateChannel.stable'), value: 'stable' as const },+ { label: t('tab.beta.updateChannel.nightly'), value: 'nightly' as const },+ { label: t('tab.beta.updateChannel.canary'), value: 'canary' as const },+ ];++ return (+ <Form+ itemsType={'group'}+ variant={'filled'}+ {...FORM_STYLE}+ items={[+ {+ children: [+ {+ children: <Select options={channelOptions} value={channel} onChange={handleChange} />,+ desc: t('tab.beta.updateChannel.desc'),+ label: t('tab.beta.updateChannel.title'),+ },+ ],+ title: t('tab.beta'),+ },+ ]}+ />+ );+});++export default UpdateChannel;diff --git a/src/routes/(main)/settings/beta/index.tsx b/src/routes/(main)/settings/beta/index.tsxnew file mode 100644index 00000000000..e46e2d6ca9e--- /dev/null+++ b/src/routes/(main)/settings/beta/index.tsx@@ -0,0 +1,17 @@+import { useTranslation } from 'react-i18next';++import SettingHeader from '@/routes/(main)/settings/features/SettingHeader';++import UpdateChannel from './features/UpdateChannel';++const Page = () => {+ const { t } = useTranslation('setting');+ return (+ <>+ <SettingHeader title={t('tab.beta')} />+ <UpdateChannel />+ </>+ );+};++export default Page;diff --git a/src/routes/(main)/settings/features/componentMap.desktop.ts b/src/routes/(main)/settings/features/componentMap.desktop.tsindex 2841faf3043..8507f6190ac 100644--- a/src/routes/(main)/settings/features/componentMap.desktop.ts+++ b/src/routes/(main)/settings/features/componentMap.desktop.ts@@ -8,6 +8,7 @@ import { SettingsTabs } from '@/store/global/initialState';import About from '../about';import Agent from '../agent';import APIKey from '../apikey';+import Beta from '../beta';import ChatAppearance from '../chat-appearance';import Common from '../common';import Hotkey from '../hotkey';@@ -24,6 +25,7 @@ import SystemTools from '../system-tools';import TTS from '../tts';export const componentMap = {+ [SettingsTabs.Beta]: Beta,[SettingsTabs.Common]: Common,[SettingsTabs.ChatAppearance]: ChatAppearance,[SettingsTabs.Provider]: Provider,diff --git a/src/routes/(main)/settings/hooks/useCategory.tsx b/src/routes/(main)/settings/hooks/useCategory.tsxindex a24657b7611..acaf8bda55a 100644--- a/src/routes/(main)/settings/hooks/useCategory.tsx+++ b/src/routes/(main)/settings/hooks/useCategory.tsx@@ -9,6 +9,7 @@ import {CreditCard,Database,EthernetPort,+ FlaskConical,Gift,Image as ImageIcon,Info,@@ -220,6 +221,11 @@ export const useCategory = () => {key: SettingsTabs.SystemTools,label: t('tab.systemTools'),},+ isDesktop && {+ icon: FlaskConical,+ key: SettingsTabs.Beta,+ label: t('tab.beta'),+ },{icon: Database,key: SettingsTabs.Storage,diff --git a/src/services/electron/autoUpdate.ts b/src/services/electron/autoUpdate.tsindex 5ada3f4380e..6f26eec35b8 100644--- a/src/services/electron/autoUpdate.ts+++ b/src/services/electron/autoUpdate.ts@@ -1,3 +1,5 @@+import type { UpdateChannel, UpdaterState } from '@lobechat/electron-client-ipc';+import { ensureElectronIpc } from '@/utils/electron/ipc';class AutoUpdateService {@@ -16,6 +18,18 @@ class AutoUpdateService {downloadUpdate() {return ensureElectronIpc().autoUpdate.downloadUpdate();}++ getUpdateChannel = async (): Promise<UpdateChannel> => {+ return ensureElectronIpc().autoUpdate.getUpdateChannel();+ };++ setUpdateChannel = async (channel: UpdateChannel): Promise<void> => {+ return ensureElectronIpc().autoUpdate.setUpdateChannel(channel);+ };++ getUpdaterState = async (): Promise<UpdaterState> => {+ return ensureElectronIpc().autoUpdate.getUpdaterState();+ };}export const autoUpdateService = new AutoUpdateService();diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex f66fb48ea90..4d4a1bcbb23 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -40,6 +40,7 @@ export enum SettingsTabs {About = 'about',Agent = 'agent',APIKey = 'apikey',+ Beta = 'beta',Billing = 'billing',ChatAppearance = 'chat-appearance',Common = 'common',