🤯 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
🐛 fix(desktop): keep canary ahead of stable and stop installing stale updates (#20529)
Innei6aa2a0dd96fb
diff --git a/.github/scripts/desktop-core-gate.test.mjs b/.github/scripts/desktop-core-gate.test.mjsnew file mode 100644index 00000000000..eb2bb01d644--- /dev/null+++ b/.github/scripts/desktop-core-gate.test.mjs@@ -0,0 +1,92 @@+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { test } from 'node:test';++// Exercise the shipped Bash step, including its outputs, without network access+// or a desktop dependency install. Only the tag lookup and ABI lookup are fixtures.+const workflow = readFileSync(+ new URL('../workflows/release-desktop-core-ota.yml', import.meta.url),+ 'utf8',+);+const gate = workflow.match(+ / {6}- name: Gate on shellAbi\n[\s\S]*? {8}run: \|\n((?: {10}.*\n|\n)+)/,+)?.[1];+assert.ok(gate, 'the release workflow must expose its shell ABI gate');+const script = gate.replaceAll(/^ {10}/gm, '');++const cases = [+ ['same-base canary', '2.2.19-canary.39', '2.2.19', 'stable-ahead'],+ ['same-base beta', '2.2.19-beta.1', '2.2.19', 'stable-ahead'],+ ['next-patch canary', '2.2.20-canary.1', '2.2.19', null],+ ['exact stable', '2.2.19', '2.2.19', null],+ ['older stable', '2.2.18', '2.2.19', 'stable-ahead'],+ ['newer stable', '2.2.20', '2.2.19', null],+ ['two-digit patch', '2.2.9-canary.1', '2.2.19', 'stable-ahead'],+ ['newer minor', '2.3.0-canary.1', '2.2.19', null],+ ['older major', '1.99.99', '2.2.19', 'stable-ahead'],+ ['no stable tags yet', '2.2.19-canary.1', '', null],+ ['missing shell', '', '2.2.19', 'abi-changed', { FOUND: 'false' }],+ [+ 'ABI change takes precedence',+ '2.2.19-canary.1',+ '2.2.19',+ 'abi-changed',+ { BASE_SHELL_ABI: 'old-abi' },+ ],+];++for (const [name, shellVersion, stableVersion, reason, overrides] of cases) {+ test(`core OTA gate: ${name}`, () => {+ const dir = mkdtempSync(path.join(os.tmpdir(), 'desktop-core-gate-'));+ const output = path.join(dir, 'output');+ try {+ const result = spawnSync(+ 'bash',+ [+ '-c',+ `+node() { printf '%s\\n' 'test-abi'; }+git() {+ if [ -n "$TEST_STABLE" ]; then+ printf 'abc\\trefs/tags/v%s\\n' "$TEST_STABLE"+ fi+ printf 'abc\\trefs/tags/v2.2.1\\nabc\\trefs/tags/v99.0.0-canary.1\\n' | {+ if [ -n "$TEST_STABLE" ]; then cat; else cat >/dev/null; fi+ }+}+${script}`,+ ],+ {+ encoding: 'utf8',+ env: {+ ...process.env,+ BASE_SHELL_ABI: 'test-abi',+ FOUND: 'true',+ GITHUB_OUTPUT: output,+ SHELL_VERSION: shellVersion,+ TEST_STABLE: stableVersion,+ ...overrides,+ },+ },+ );+ assert.equal(result.status, 0, result.stderr || result.stdout);+ const values = Object.fromEntries(+ readFileSync(output, 'utf8')+ .trim()+ .split('\n')+ .map((line) => line.split('=')),+ );+ assert.deepEqual(values, {+ shell_abi: 'test-abi',+ allowed: reason ? 'false' : 'true',+ requires_full_release: reason ? 'true' : 'false',+ ...(reason ? { reason } : {}),+ });+ } finally {+ rmSync(dir, { force: true, recursive: true });+ }+ });+}diff --git a/.github/workflows/release-desktop-canary.yml b/.github/workflows/release-desktop-canary.ymlindex de5f17d4184..161797a979a 100644--- a/.github/workflows/release-desktop-canary.yml+++ b/.github/workflows/release-desktop-canary.yml@@ -9,8 +9,8 @@ name: Release Desktop Canary# 2. 手动触发 (workflow_dispatch)## core-only 优先:-# 先跑 release-desktop-core-ota.yml;只有 shellAbi 变了 (requires_full_release)-# 或 core 没有变化 (skipped) 或手动 force_full 时才走全量打包。+# 先跑 release-desktop-core-ota.yml;只有 shellAbi 变了或 stable 已追上当前壳版本+# (requires_full_release)、core 没有变化 (skipped)、手动 force_full 时才走全量打包。## 并发策略:# 运行中的发布不会被后续 push 取消;等待队列仅保留最新一次运行diff --git a/.github/workflows/release-desktop-core-ota.yml b/.github/workflows/release-desktop-core-ota.ymlindex f7549333ba8..98ce530f382 100644--- a/.github/workflows/release-desktop-core-ota.yml+++ b/.github/workflows/release-desktop-core-ota.yml@@ -4,6 +4,7 @@ name: Release Desktop Core OTA# core-only 发布(壳不变,只发 main/preload/renderer/cli)# ============================================# 门禁: HEAD 的 shellAbi 必须等于 <channel>/shell.json 的 shellAbi,+# 且 shell.json 的 shellVersion 必须比最新 stable tag 新(或就是该 stable),# 否则 requires_full_release=true,由调用方走全量发版。# 产物: <channel>/<appVersion>/core-v4/<platform>/packs/<sha>.pack 独立 Zstd 块# <channel>/<appVersion>/core-v4/<platform>/versions/<version>.json 签名快照@@ -125,17 +126,31 @@ jobs:BASE_SHELL_ABI: ${{ steps.base.outputs.shell_abi }}FOUND: ${{ steps.base.outputs.found }}RENDERER_OTA_PUBLIC_KEY: ${{ secrets.RENDERER_OTA_PUBLIC_KEY }}+ SHELL_VERSION: ${{ steps.base.outputs.app_version }}run: |set -euo pipefailSHELL_ABI=$(node apps/desktop/scripts/shellAbi.mjs)echo "shell_abi=$SHELL_ABI" >> "$GITHUB_OUTPUT"echo "HEAD shellAbi: $SHELL_ABI"echo "Shipped shellAbi: ${BASE_SHELL_ABI:-<none>}"+ LATEST_STABLE=$(git ls-remote --tags --refs origin 'v*' | sed -n 's|.*refs/tags/v\([0-9]*\.[0-9]*\.[0-9]*\)$|\1|p' | sort -V | tail -n 1)+ echo "Shipped shell: ${SHELL_VERSION:-<none>} (latest stable: ${LATEST_STABLE:-<none>})"+ # 2.2.19-canary.39 在 v2.2.19 发布后已落后于 stable,继续叠 -core.N 会让版本号断档,必须全量发一次 2.2.20-canary.1+ STABLE_AHEAD=false+ if [ -n "$LATEST_STABLE" ] && [ -n "$SHELL_VERSION" ] && [ "$SHELL_VERSION" != "$LATEST_STABLE" ] \+ && [ "$(printf '%s\n%s\n' "${SHELL_VERSION%%-*}" "$LATEST_STABLE" | sort -V | tail -n 1)" = "$LATEST_STABLE" ]; then+ STABLE_AHEAD=true+ fiif [ "$FOUND" != "true" ] || [ "$SHELL_ABI" != "$BASE_SHELL_ABI" ]; thenecho "::warning::shell changed since last full release — core-only release is not allowed"echo "allowed=false" >> "$GITHUB_OUTPUT"echo "reason=abi-changed" >> "$GITHUB_OUTPUT"echo "requires_full_release=true" >> "$GITHUB_OUTPUT"+ elif [ "$STABLE_AHEAD" = "true" ]; then+ echo "::warning::shell $SHELL_VERSION is not newer than stable v$LATEST_STABLE — core-only release is not allowed"+ echo "allowed=false" >> "$GITHUB_OUTPUT"+ echo "reason=stable-ahead" >> "$GITHUB_OUTPUT"+ echo "requires_full_release=true" >> "$GITHUB_OUTPUT"elseecho "allowed=true" >> "$GITHUB_OUTPUT"echo "requires_full_release=false" >> "$GITHUB_OUTPUT"diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 3d20d216621..3193d2438bd 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -66,7 +66,8 @@ jobs:.github/scripts/vercel-ignored-build-step.test.cjs \.github/scripts/bundle-size-gate.test.cjs \.github/scripts/size-gate-comment.test.cjs \- .github/scripts/mergeAllowBuilds.test.mjs+ .github/scripts/mergeAllowBuilds.test.mjs \+ .github/scripts/desktop-core-gate.test.mjs- name: Setup environmentuses: ./.github/actions/setup-envdiff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex bfac9aeeb76..272040cc0da 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -56,7 +56,7 @@"@lobehub/fluent-emoji": "^4.1.1","@lydell/node-pty": "1.2.0-beta.15","electron-log": "^5.4.4",- "electron-sparkle-updater": "0.5.2",+ "electron-sparkle-updater": "0.5.3","font-list": "^2.1.0","get-windows": "^9.3.0","node-screenshots": "^0.2.8"diff --git a/apps/desktop/patches/[email protected] b/apps/desktop/patches/[email protected]deleted file mode 100644index 118d4604ce0..00000000000--- a/apps/desktop/patches/[email protected]+++ /dev/null@@ -1,59 +0,0 @@-diff --git a/native/src/sparkle_bridge.mm b/native/src/sparkle_bridge.mm-index f7c962c73d..645f0a64a6 100644---- a/native/src/sparkle_bridge.mm-+++ b/native/src/sparkle_bridge.mm-@@ -20,0 +21,4 @@ static void EmitSparkleEvent(NSDictionary *payload) {-+ if (env == nullptr || jsCallback.IsEmpty()) {-+ delete json;-+ return;-+ }-@@ -43,0 +48,2 @@ @interface SparkleBridgeLogDelegate : NSObject <SPUUpdaterDelegate>-+@property(nonatomic, copy, nullable) NSString *appcastUrl;-+@property(nonatomic, assign) BOOL checkWhenReady;-@@ -47,0 +54,4 @@ @implementation SparkleBridgeLogDelegate-+- (nullable NSString *)feedURLStringForUpdater:(SPUUpdater *)updater {-+ return self.appcastUrl;-+}-+-@@ -55,0 +66,4 @@ - (void)updater:(SPUUpdater *)updater-+ if (self.checkWhenReady) {-+ self.checkWhenReady = NO;-+ dispatch_async(dispatch_get_main_queue(), ^{ [updater checkForUpdates]; });-+ }-@@ -262,0 +277,8 @@ - (void)showUpdateInFocus {-+ if (![g_logDelegate.appcastUrl isEqualToString:appcastUrl] && g_userDriver.readyToInstallReply != nil) {-+ // Discard an uninstalled download from the previous channel. User-initiated-+ // checks can still find this version if the user switches back later.-+ void (^reply)(SPUUserUpdateChoice) = g_userDriver.readyToInstallReply;-+ g_userDriver.readyToInstallReply = nil;-+ reply(SPUUserUpdateChoiceSkip);-+ }-+ g_logDelegate.appcastUrl = appcastUrl;-@@ -268,0 +291 @@ - (void)showUpdateInFocus {-+ g_logDelegate.appcastUrl = appcastUrl;-@@ -355,0 +379,4 @@ void RunOnMain(void (^work)(void)) {-+ if (g_updater.sessionInProgress) {-+ g_logDelegate.checkWhenReady = YES;-+ return;-+ }-@@ -433,2 +460,2 @@ void RunOnMain(void (^work)(void)) {-- if (info.Length() < 1 || !info[0].IsFunction()) {-- Napi::TypeError::New(env, "setEventHandler(fn) requires a function").ThrowAsJavaScriptException();-+ if (info.Length() < 1 || (!info[0].IsFunction() && !info[0].IsNull())) {-+ Napi::TypeError::New(env, "setEventHandler(fn) requires a function or null").ThrowAsJavaScriptException();-@@ -439 +466 @@ void RunOnMain(void (^work)(void)) {-- g_eventTsfn.Release();-+ g_eventTsfn.Abort();-@@ -440,0 +468 @@ void RunOnMain(void (^work)(void)) {-+ if (info[0].IsNull()) return env.Undefined();-diff --git a/dist/index.d.ts b/dist/index.d.ts-index cc2445ca83..4b5d16e0fa 100644---- a/dist/index.d.ts-+++ b/dist/index.d.ts-@@ -25 +25 @@ export interface SparkleBridge {-- setEventHandler(handler: (event: SparkleBridgeEvent) => void): void;-+ setEventHandler(handler: ((event: SparkleBridgeEvent) => void) | null): void;-@@ -42 +42 @@ export {};--//# sourceMappingURL=index.d.ts.map-\ No newline at end of file-+//# sourceMappingURL=index.d.ts.mapdiff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yamlindex abae493ccd1..fcb5541f2c5 100644--- a/apps/desktop/pnpm-lock.yaml+++ b/apps/desktop/pnpm-lock.yaml@@ -11,9 +11,6 @@ overrides:vitest: 5.0.3zod@^4: 4.6.5-patchedDependencies:- [email protected]: 6f583444e425a99e21e374a9afab303612eb8255ee21194afdb77f347c6cc045-importers:.:@@ -34,8 +31,8 @@ importers:specifier: ^5.4.4version: 5.4.4electron-sparkle-updater:- specifier: 0.5.2- version: 0.5.2(patch_hash=6f583444e425a99e21e374a9afab303612eb8255ee21194afdb77f347c6cc045)([email protected]([email protected]))+ specifier: 0.5.3+ version: 0.5.3([email protected]([email protected]))font-list:specifier: ^2.1.0version: 2.1.0@@ -4896,8 +4893,8 @@ packages:resolution: {integrity: sha512-Vt3KzQIiw9BImvNOYtndg9Mjki+tl4+1sQiC/+G5j8khWaENOJFWodiB+sUl6yyHwtd37avehskdtPw7f8y/+Q==}- resolution: {integrity: sha512-S7C35axw51hTYer9/TSx28/1QyAxARFJZHIDpXrTDM2owxAeGlqnvcPduzk4FJhNkEah1tF/f3ko21/r/TwvoQ==}+ resolution: {integrity: sha512-mEN+cKZ+oujw/kDTc0XbToVg0dNNZVELttD0xuFo/v3tw8b0aocWF0phcW1XvpUTFHpr4HRApfT3H9QzJgZs5w==}engines: {node: '>=20.19'}hasBin: truepeerDependencies:@@ -12790,7 +12787,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](patch_hash=6f583444e425a99e21e374a9afab303612eb8255ee21194afdb77f347c6cc045)([email protected]([email protected])):dependencies:node-addon-api: 8.9.2node-gyp: 12.4.0diff --git a/apps/desktop/pnpm-workspace.yaml b/apps/desktop/pnpm-workspace.yamlindex a20694247e7..6907326f93c 100644--- a/apps/desktop/pnpm-workspace.yaml+++ b/apps/desktop/pnpm-workspace.yaml@@ -73,6 +73,4 @@ minimumReleaseAgeExclude:- '@auv-js/[email protected]'- '@auv-js/[email protected]'- '@auv-js/[email protected]'-patchedDependencies:- [email protected]: patches/[email protected]diff --git a/apps/desktop/scripts/core-ota-test/README.md b/apps/desktop/scripts/core-ota-test/README.mdindex 0d18c14200e..2fbf35269cb 100644--- a/apps/desktop/scripts/core-ota-test/README.md+++ b/apps/desktop/scripts/core-ota-test/README.md@@ -92,6 +92,43 @@ printf 'provider: generic\nurl: http://127.0.0.1:8787/canary\n' > $R/app-update.## 辅助+### 已暂存更新被新版本替换++完成第 1 步构建并启动本地 feed 后,用 `staged <b|c> <reload|relaunch>` 发布两份基于内置 v1 的签名更新。B 为 `1.0.0-core.10`,C 为 `1.0.0-core.11`;renderer 带有 `STAGED B/C` 标记,relaunch 版本还会输出对应的 main 日志。不要先应用 B。++每组从独立测试 App 的干净 userData 开始(`reset` 只用于该测试 App),依次验证下表三种组合:++| B | C | 应用 C 的预期 |+| -------- | -------- | ---------------------------------------- |+| reload | reload | 原进程刷新到 C |+| relaunch | relaunch | 重启直接运行 C,B 不作为回滚目标且被清理 |+| relaunch | reload | 原进程刷新到 C,退出后冷启动也不运行 B |++以下以第三组为例,另两组替换 `staged` 的 mode 参数:++```bash+node scripts/core-ota-test/run.mjs kill+node scripts/core-ota-test/run.mjs reset+node scripts/core-ota-test/run.mjs staged b relaunch+node scripts/core-ota-test/run.mjs launch+# 等待日志确认 B staged;再次检查同一 B 应保留暂存状态+node scripts/core-ota-test/run.mjs eval "window.electronAPI.invoke('rendererOta.checkNow')"+node scripts/core-ota-test/run.mjs eval "window.electronAPI.invoke('rendererOta.getStatus')"+node scripts/core-ota-test/run.mjs state+node scripts/core-ota-test/run.mjs staged c reload+node scripts/core-ota-test/run.mjs eval "window.electronAPI.invoke('rendererOta.checkNow')"+node scripts/core-ota-test/run.mjs eval "window.electronAPI.invoke('rendererOta.getStatus')"+node scripts/core-ota-test/run.mjs state+node scripts/core-ota-test/run.mjs eval "window.electronAPI.invoke('rendererOta.applyNow')"+# 截图应显示 STAGED C reload;main 日志不应出现 STAGED B relaunch+node scripts/core-ota-test/run.mjs eval --shot /tmp/core-ota-staged-c.png+node scripts/core-ota-test/run.mjs kill+node scripts/core-ota-test/run.mjs launch+node scripts/core-ota-test/run.mjs state+```++记录 B/C manifest tree、暂存前后状态、pointer、main 日志和进程 PID,并打开截图确认实际加载的是 C。`relaunch → reload` 在应用前应恢复 `current/previous` 为内置基线、`staged` 为 C;`relaunch → relaunch` 应直接把 `current` 指向 C、`previous` 保留真正运行过的版本,不能指向 B。这里通过真实 IPC 加速检查,不修改更新逻辑,也不声称覆盖一小时定时器或已登录后的通知 UI。+`launch` 带 `--remote-debugging-port=9333`,`run.mjs eval "<js>"` 在主窗口里求值(`window.electronAPI.invoke('rendererOta.<applyNow|checkNow|getStatus>')`),`run.mjs eval --shot <file.png>` 截主窗口。`tamper` 改 `cores/1.0.0-core.2/dist/main/index.js` 一行。onboarding 页不挂 UpdateNotification,toast 要登录后才看得到;用 `eval` 触发 IPC 即可。diff --git a/apps/desktop/scripts/core-ota-test/run.mjs b/apps/desktop/scripts/core-ota-test/run.mjsindex 7ad73630312..c439834a46e 100644--- a/apps/desktop/scripts/core-ota-test/run.mjs+++ b/apps/desktop/scripts/core-ota-test/run.mjs@@ -131,6 +131,33 @@ const steps = {publish('v3', { previous: 'v2', seq: 2, version: `${APP_VERSION}-core.2` });},+ staged() {+ const [slot, mode] = process.argv.slice(3);+ if (!['b', 'c'].includes(slot) || !['reload', 'relaunch'].includes(mode))+ throw new Error('usage: staged <b|c> <reload|relaunch>');+ // Both candidates are based on the running builtin core, so C can revert+ // B's main change and exercise relaunch -> reload without ever applying B.+ const tag = `staged-${slot}`;+ const marker = `STAGED ${slot.toUpperCase()} ${mode}`;+ rmSync(coreDir(tag), { force: true, recursive: true });+ cpSync(coreDir('v1'), coreDir(tag), { recursive: true });+ const html = path.join(coreDir(tag), 'dist/renderer/apps/desktop/index.html');+ writeFileSync(+ html,+ readFileSync(html, 'utf8').replace(+ /<body[^>]*>/,+ `$&<div id="core-ota-e2e" style="position:fixed;top:8px;right:8px;z-index:99999;background:#173;color:#fff;padding:6px 10px;font:bold 14px sans-serif">${marker}</div>`,+ ),+ );+ if (mode === 'relaunch')+ appendFileSync(+ path.join(coreDir(tag), 'dist/main/index.js'),+ `\nconsole.log(${JSON.stringify(marker)});\n`,+ );+ const seq = slot === 'b' ? 10 : 11;+ publish(tag, { previous: 'v1', seq, version: `${APP_VERSION}-core.${seq}` });+ },+v4() {rmSync(coreDir('v4'), { force: true, recursive: true });cpSync(coreDir('v3'), coreDir('v4'), { recursive: true });@@ -160,9 +187,12 @@ const steps = {},launch() {+ const env = { ...process.env, RENDERER_OTA_CHECK_DELAY: '3000' };+ // Electron-based terminals may export this; the packaged fixture must run as an app.+ delete env.ELECTRON_RUN_AS_NODE;const child = spawn(APP, [`--remote-debugging-port=${CDP_PORT}`], {detached: true,- env: { ...process.env, RENDERER_OTA_CHECK_DELAY: '3000' },+ env,stdio: 'ignore',});child.unref();diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts b/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.tsindex 75c1fadb88f..9ae9609c247 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts@@ -299,10 +299,8 @@ export class CoreUpdateManager {};private async runCheck() {- if (!this.enabled || this.busy || this.staged) {- logger.info('Core OTA check skipped', {- reason: !this.enabled ? 'disabled' : this.busy ? 'busy' : 'already-staged',- });+ if (!this.enabled || this.busy) {+ logger.info('Core OTA check skipped', { reason: !this.enabled ? 'disabled' : 'busy' });return;}if (this.pendingBootCheck && this.coldBootCheck) {@@ -323,6 +321,7 @@ export class CoreUpdateManager {if (this.needsFullRelease) throw new SkipCheck('needs-full-release');if (remote.channel === this.running.channel && remote.seq <= this.running.seq)throw new SkipCheck('up-to-date');+ if (version === this.staged?.version) throw new SkipCheck('already-staged');if (version === this.pointer.current) throw new SkipCheck('already-current');if (this.pointer.blacklist.includes(version)) throw new SkipCheck('blacklisted');if (!this.inRollout(version, remote.rollout)) throw new SkipCheck('rollout-excluded');@@ -355,6 +354,9 @@ export class CoreUpdateManager {if (generation !== this.checkGeneration) throw new SkipCheck('superseded');const applyMode = computeApplyMode(this.running.tree, remote.tree);logger.info('Core OTA staged', { applyMode, version, ...staged.downloaded });+ if (this.staged?.applyMode === 'relaunch') {+ this.pointer = { ...this.pointer, current: this.pointer.previous, previous: null };+ }this.staged = { applyMode, version };this.unloadPrevented = false;this.savePointer(diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.tsindex b04195c2619..a03e81a3ebb 100644--- a/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts+++ b/apps/desktop/src/main/core/infrastructure/coreOta/__tests__/CoreUpdateManager.int.test.ts@@ -688,6 +688,63 @@ describe('CoreUpdateManager checkForUpdates', () => {});});+ it('replaces a staged reload core when a newer one is published', async () => {+ serveLatest(rendererOnly('1.0.1', 1));+ const { app, manager } = await loadManager();+ await manager.checkForUpdates();++ serveLatest(rendererOnly('1.0.2', 2));+ await manager.checkForUpdates();++ expect(manager.getStatus()).toMatchObject({ applyMode: 'reload', staged: '1.0.2' });+ expect(readPointer(otaRoot(), ABI)).toMatchObject({ current: null, staged: '1.0.2' });+ expect(app.browserManager.broadcastToAllWindows).toHaveBeenLastCalledWith('updateReady', {+ kind: 'core-reload',+ version: '1.0.2',+ });++ expect(manager.applyStagedNow()).toBe(true);+ expectAppliedRenderer(app, 'index-1.0.2');+ });++ it('replaces a staged relaunch core without keeping the stale one as rollback', async () => {+ serveLatest(mainChanged('1.0.1', 1));+ const { app, manager } = await loadManager();+ await manager.checkForUpdates();++ serveLatest(mainChanged('1.0.2', 2));+ await manager.checkForUpdates();+ await flushGc(manager);++ expect(manager.getStatus()).toMatchObject({ applyMode: 'relaunch', staged: '1.0.2' });+ expect(readPointer(otaRoot(), ABI)).toMatchObject({+ current: '1.0.2',+ previous: null,+ staged: null,+ });+ expect(existsSync(coreDir('1.0.1'))).toBe(false);+ expect(app.browserManager.broadcastToAllWindows).toHaveBeenLastCalledWith('updateReady', {+ kind: 'core-relaunch',+ version: '1.0.2',+ });+ });++ it('reverts a staged relaunch when the newer core only needs a reload', async () => {+ serveLatest(mainChanged('1.0.1', 1));+ const { manager } = await loadManager();+ await manager.checkForUpdates();++ serveLatest(rendererOnly('1.0.2', 2));+ await manager.checkForUpdates();++ expect(manager.getStatus()).toMatchObject({ applyMode: 'reload', staged: '1.0.2' });+ expect(readPointer(otaRoot(), ABI)).toMatchObject({+ current: null,+ previous: null,+ staged: '1.0.2',+ });+ });+it('stages a main-process change as core-relaunch and switches pointer immediately', async () => {serveLatest(mainChanged('1.0.1', 1));const { app, manager } = await loadManager();diff --git a/apps/desktop/src/main/modules/updater/__tests__/sparkleEngine.test.ts b/apps/desktop/src/main/modules/updater/__tests__/sparkleEngine.test.tsindex e87577fa5a9..7c26ea46821 100644--- a/apps/desktop/src/main/modules/updater/__tests__/sparkleEngine.test.ts+++ b/apps/desktop/src/main/modules/updater/__tests__/sparkleEngine.test.ts@@ -3,14 +3,18 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { SparkleEngine } from '../sparkleEngine';-const { mockLoadBridge, mockAppOn } = vi.hoisted(() => ({+const { mockLoadBridge, mockAppOn, mockFetch } = vi.hoisted(() => ({mockAppOn: vi.fn(),+ mockFetch: vi.fn(),mockLoadBridge: vi.fn(),}));vi.mock('electron-sparkle-updater', () => ({ loadSparkleBridge: mockLoadBridge }));-vi.mock('electron', () => ({ app: { isPackaged: true, on: mockAppOn } }));+vi.mock('electron', () => ({+ app: { isPackaged: true, on: mockAppOn },+ net: { fetch: mockFetch },+}));vi.mock('@/utils/logger', () => ({createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),@@ -20,6 +24,7 @@ const createBridge = () => {let handler: ((event: SparkleBridgeEvent) => void) | null | undefined;const bridge: SparkleBridge = {checkForUpdates: vi.fn(),+ discardDownloadedUpdate: vi.fn(),init: vi.fn().mockReturnValue(true),installUpdateNow: vi.fn(),installUpdateOnQuit: vi.fn(),@@ -120,6 +125,71 @@ describe('SparkleEngine', () => {expect(complete).toHaveBeenCalledOnce();});+ describe('with an update already downloaded', () => {+ const appcast = (...versions: string[]) =>+ new Response(+ `<rss><channel>${versions+ .map((v) => `<item><sparkle:shortVersionString>${v}</sparkle:shortVersionString></item>`)+ .join('')}</channel></rss>`,+ );++ const downloadedSetup = async () => {+ const ctx = setup();+ ctx.engine.configure('canary');+ const check = ctx.engine.checkForUpdates();+ ctx.emit({ type: 'update-available', version: '2.0.0-canary.1' });+ ctx.emit({ type: 'update-downloaded', version: '2.0.0-canary.1' });+ await check;+ vi.mocked(ctx.bridge.checkForUpdates).mockClear();+ return ctx;+ };++ beforeEach(() => mockFetch.mockReset());++ it('discards the stale download and checks again when the appcast has a newer release', async () => {+ const { bridge, emit, engine } = await downloadedSetup();+ mockFetch.mockResolvedValue(appcast('2.0.0-canary.2', '2.0.0-canary.1'));+ const downloaded = vi.fn();+ engine.on('update-downloaded', downloaded);++ const check = engine.checkForUpdates();+ await vi.waitFor(() => expect(bridge.checkForUpdates).toHaveBeenCalledOnce());+ expect(mockFetch).toHaveBeenCalledWith(+ expect.stringMatching(/\/canary\/appcast-[^/]+\.xml$/),+ { cache: 'no-store' },+ );+ expect(bridge.discardDownloadedUpdate).toHaveBeenCalledOnce();+ expect(downloaded).not.toHaveBeenCalled();++ emit({ type: 'update-available', version: '2.0.0-canary.2' });+ emit({ type: 'update-downloaded', version: '2.0.0-canary.2' });+ await check;+ expect(downloaded).toHaveBeenCalledWith(+ expect.objectContaining({ version: '2.0.0-canary.2' }),+ );+ });++ it.each(['the appcast has nothing newer', 'the appcast is unavailable'])(+ 'keeps the download when %s',+ async (scenario) => {+ const { bridge, engine } = await downloadedSetup();+ if (scenario.includes('nothing newer'))+ mockFetch.mockResolvedValue(appcast('2.0.0-canary.1'));+ else mockFetch.mockResolvedValue(new Response('nope', { status: 503 }));+ const downloaded = vi.fn();+ engine.on('update-downloaded', downloaded);++ await engine.checkForUpdates();++ expect(bridge.discardDownloadedUpdate).not.toHaveBeenCalled();+ expect(bridge.checkForUpdates).not.toHaveBeenCalled();+ expect(downloaded).toHaveBeenCalledWith(+ expect.objectContaining({ version: '2.0.0-canary.1' }),+ );+ },+ );+ });+it('maps the Sparkle lifecycle onto electron-updater events', () => {const { emit, engine } = setup();const events: Array<[string, unknown]> = [];diff --git a/apps/desktop/src/main/modules/updater/sparkleEngine.ts b/apps/desktop/src/main/modules/updater/sparkleEngine.tsindex 64cc4c682fa..323a5261868 100644--- a/apps/desktop/src/main/modules/updater/sparkleEngine.ts+++ b/apps/desktop/src/main/modules/updater/sparkleEngine.ts@@ -2,9 +2,10 @@ import { EventEmitter } from 'node:events';import path from 'node:path';import type { ProgressInfo, UpdateChannel, UpdateInfo } from '@lobechat/electron-client-ipc';-import { app } from 'electron';+import { app, net } from 'electron';import type { SparkleBridge, SparkleBridgeEvent } from 'electron-sparkle-updater';import { loadSparkleBridge } from 'electron-sparkle-updater';+import semver from 'semver';import { createLogger } from '@/utils/logger';@@ -82,8 +83,16 @@ export class SparkleEngine extends EventEmitter<UpdateEngineEvents> implements UcheckForUpdates = async () => {if (this.downloaded && this.available) {- this.emit('update-downloaded', this.available);- return;+ if (!(await this.hasNewerRelease(this.available.version))) {+ this.emit('update-downloaded', this.available);+ return;+ }+ // Sparkle resumes a staged update without reading the appcast, so a download that sat+ // unattended would otherwise be installed even after a newer release shipped.+ logger.info(`Discarding downloaded ${this.available.version} for a newer release`);+ this.bridge.discardDownloadedUpdate();+ this.available = null;+ this.downloaded = false;}// The bridge starts an asynchronous native cycle. Keep it in flight through download// so a channel switch cannot reuse the old cycle's events for the new channel.@@ -160,6 +169,21 @@ export class SparkleEngine extends EventEmitter<UpdateEngineEvents> implements U}};+ private async hasNewerRelease(downloadedVersion: string) {+ if (!this.feedUrl) return false;+ try {+ const response = await net.fetch(this.feedUrl, { cache: 'no-store' });+ if (!response.ok) return false;+ const appcast = await response.text();+ return [...appcast.matchAll(/<sparkle:shortVersionString>([^<]+)</g)].some(+ ([, version]) => semver.valid(version) && semver.gt(version, downloadedVersion),+ );+ } catch (error) {+ logger.warn('Failed to read the appcast for a newer release:', error);+ return false;+ }+ }+private handleProgress(event: SparkleBridgeEvent) {if (event.phase !== 'download') return;