Skip to content

🤯 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.

🐛 fix(desktop): preserve OTA state and confirm protected reloads (#20627)

Inneid65f485941cc
diff --git a/apps/desktop/src/main/controllers/RendererOtaCtr.ts b/apps/desktop/src/main/controllers/RendererOtaCtr.ts
index 8960f2b96eb..28cf07fd26c 100644
--- a/apps/desktop/src/main/controllers/RendererOtaCtr.ts
+++ b/apps/desktop/src/main/controllers/RendererOtaCtr.ts
@@ -1,4 +1,5 @@
import { shellInfo } from '@/const/shell';
+import { getIpcContext } from '@/utils/ipc';
import { ControllerModule, IpcMethod } from './index';
@@ -9,7 +10,7 @@ export default class RendererOtaCtr extends ControllerModule {
@IpcMethod()
async bootPing(stage?: 'loaded' | 'mounted') {
- this.app.coreUpdateManager.handleBootPing(stage);
+ this.app.coreUpdateManager.handleBootPing(stage, getIpcContext()?.sender.id);
if (stage === 'loaded' || this.coreMarkedHealthy) return;
this.coreMarkedHealthy = true;
shellInfo?.markHealthy();
@@ -20,6 +21,16 @@ export default class RendererOtaCtr extends ControllerModule {
return this.app.coreUpdateManager.applyStagedNow();
}
+ @IpcMethod()
+ async resolveUnloadConfirmation(proceed: boolean) {
+ const sender = getIpcContext()?.sender;
+ if (!sender) return;
+ const browser = [...this.app.browserManager.browsers.values()].find(
+ (item) => item.webContents?.id === sender.id,
+ );
+ browser?.resolveUnloadConfirmation(proceed);
+ }
+
@IpcMethod()
async getStatus() {
return this.app.coreUpdateManager.getStatus();
diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.ts
index 636a50d1a8c..7ec1155360b 100644
--- a/apps/desktop/src/main/core/App.ts
+++ b/apps/desktop/src/main/core/App.ts
@@ -176,8 +176,8 @@ export class App {
webContents.on('render-process-gone', () => {
this.coreUpdateManager.handleRendererCrash();
});
- webContents.on('will-prevent-unload', () => {
- this.coreUpdateManager.handleUnloadPrevented();
+ webContents.on('destroyed', () => {
+ this.coreUpdateManager.handleRendererDestroyed(webContents.id);
});
});
diff --git a/apps/desktop/src/main/core/browser/Browser.ts b/apps/desktop/src/main/core/browser/Browser.ts
index 60c7fa86ce6..88e5646efd5 100644
--- a/apps/desktop/src/main/core/browser/Browser.ts
+++ b/apps/desktop/src/main/core/browser/Browser.ts
@@ -88,6 +88,9 @@ export default class Browser {
private _browserWindow?: BrowserWindow;
private hasPresentedFirstFrame = false;
private ignoreNextPreventUnload = false;
+ private promptBeforeUnload = true;
+ private unloadOperation: (() => void) | null = null;
+ private pendingUnloadConfirmation: { ota: boolean; resume: () => void } | null = null;
private resolveFirstFrame!: () => void;
private readonly firstFramePromise = new Promise<void>((resolve) => {
this.resolveFirstFrame = resolve;
@@ -107,17 +110,54 @@ export default class Browser {
return this._browserWindow?.webContents ?? null;
}
- reloadIgnoringCache = (ignoreBeforeUnload = false) => {
- const webContents = this.browserWindow.webContents;
+ reloadIgnoringCache = (ignoreBeforeUnload = false, promptBeforeUnload = true) => {
+ this.runWithUnloadConfirmation(
+ () => this.browserWindow.webContents.reloadIgnoringCache(),
+ promptBeforeUnload,
+ ignoreBeforeUnload,
+ );
+ };
+
+ runWithUnloadConfirmation = (
+ operation: () => void,
+ promptBeforeUnload = true,
+ ignoreBeforeUnload = false,
+ ) => {
+ if (this.pendingUnloadConfirmation) return;
+ this.unloadOperation = operation;
+ this.promptBeforeUnload = promptBeforeUnload;
this.ignoreNextPreventUnload = ignoreBeforeUnload;
try {
- webContents.reloadIgnoringCache();
+ operation();
} catch (error) {
+ this.unloadOperation = null;
this.ignoreNextPreventUnload = false;
+ this.promptBeforeUnload = true;
throw error;
}
};
+ cancelUnloadConfirmation = () => {
+ if (!this.pendingUnloadConfirmation) return;
+ this.pendingUnloadConfirmation = null;
+ this.broadcast('reloadConfirmationCancelled');
+ };
+
+ resolveUnloadConfirmation = (proceed: boolean) => {
+ const pending = this.pendingUnloadConfirmation;
+ this.pendingUnloadConfirmation = null;
+ if (!pending) return;
+ if (
+ pending.ota &&
+ !this.app.coreUpdateManager.resolveUnloadConfirmation(
+ this.browserWindow.webContents.id,
+ proceed,
+ )
+ )
+ return;
+ if (proceed) this.runWithUnloadConfirmation(pending.resume, true, true);
+ };
+
// ==================== Constructor ====================
constructor(options: BrowserWindowOpts, application: App) {
@@ -336,19 +376,42 @@ export default class Browser {
private setupWillPreventUnloadListener(browserWindow: BrowserWindow): void {
logger.debug(`[${this.identifier}] Setting up 'will-prevent-unload' event listener.`);
- browserWindow.webContents.on('did-start-loading', () => {
+ // Loading starts before beforeunload; clear approval only after navigation commits.
+ browserWindow.webContents.on('did-navigate', () => {
+ this.unloadOperation = null;
this.ignoreNextPreventUnload = false;
+ this.promptBeforeUnload = true;
});
browserWindow.webContents.on('will-prevent-unload', (event) => {
logger.debug(
`[${this.identifier}] 'will-prevent-unload' fired. isQuiting: ${this.app.isQuiting}`,
);
+ const resume = this.unloadOperation;
+ this.unloadOperation = null;
+ const promptBeforeUnload = this.promptBeforeUnload;
+ this.promptBeforeUnload = true;
const ignorePreventUnload = this.ignoreNextPreventUnload;
this.ignoreNextPreventUnload = false;
if (this.app.isQuiting || ignorePreventUnload) {
logger.info(`[${this.identifier}] Ignoring beforeunload cancellation.`);
event.preventDefault();
+ return;
}
+ if (promptBeforeUnload) {
+ // An unload event has no continuation; only replay operations captured at their source.
+ if (!resume) return;
+ if (!this.pendingUnloadConfirmation) {
+ this.pendingUnloadConfirmation = {
+ resume,
+ ota: this.app.coreUpdateManager.pauseForUnloadConfirmation(
+ browserWindow.webContents.id,
+ ),
+ };
+ this.broadcast('reloadConfirmationRequested');
+ }
+ return;
+ }
+ this.app.coreUpdateManager.handleUnloadPrevented();
});
}
@@ -380,7 +443,16 @@ export default class Browser {
onCleanup: () => this.themeManager.cleanup(),
onHide: () => this.hide(),
});
- browserWindow.on('close', closeHandler);
+ browserWindow.on('close', (event) => {
+ if (this.pendingUnloadConfirmation && !this.app.isQuiting) {
+ event.preventDefault();
+ return;
+ }
+ closeHandler(event);
+ if (!event.defaultPrevented && !this.options.keepAlive) {
+ this.unloadOperation = () => browserWindow.close();
+ }
+ });
}
private setupFocusListener(browserWindow: BrowserWindow): void {
diff --git a/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts b/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
index 8e3ddfb3dc3..62a33068250 100644
--- a/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
+++ b/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
@@ -209,6 +209,12 @@ describe('Browser', () => {
};
mockApp = {
+ i18n: { ns: () => (key: string) => key },
+ coreUpdateManager: {
+ pauseForUnloadConfirmation: vi.fn(() => false),
+ resolveUnloadConfirmation: vi.fn(() => true),
+ handleUnloadPrevented: vi.fn(),
+ },
browserManager: {
retrieveByIdentifier: vi.fn(),
},
@@ -944,6 +950,132 @@ describe('Browser', () => {
expect(mockEvent.preventDefault).not.toHaveBeenCalled();
});
+ it('continues a protected window close without reloading the page', () => {
+ const closeHandler = mockBrowserWindow.on.mock.calls.find((call) => call[0] === 'close')?.[1];
+ const event = { preventDefault: vi.fn() };
+ closeHandler(event);
+ willPreventUnloadHandler(event);
+ mockBrowserWindow.close.mockImplementationOnce(() => {
+ closeHandler(event);
+ willPreventUnloadHandler(event);
+ });
+
+ browser.resolveUnloadConfirmation(true);
+ browser.resolveUnloadConfirmation(true);
+
+ expect(mockBrowserWindow.close).toHaveBeenCalledOnce();
+ expect(mockBrowserWindow.webContents.reloadIgnoringCache).not.toHaveBeenCalled();
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ });
+
+ it('keeps a protected window open when closing is cancelled', () => {
+ const closeHandler = mockBrowserWindow.on.mock.calls.find((call) => call[0] === 'close')?.[1];
+ closeHandler({ preventDefault: vi.fn() });
+ willPreventUnloadHandler({ preventDefault: vi.fn() });
+ browser.resolveUnloadConfirmation(false);
+
+ expect(mockBrowserWindow.close).not.toHaveBeenCalled();
+ expect(mockBrowserWindow.webContents.reloadIgnoringCache).not.toHaveBeenCalled();
+ });
+
+ it('requests one UI confirmation and retries only after approval', () => {
+ const event = { preventDefault: vi.fn() };
+ mockBrowserWindow.webContents.reloadIgnoringCache.mockImplementation(() => {
+ const loadingHandler = mockBrowserWindow.webContents.on.mock.calls.find(
+ (call) => call[0] === 'did-start-loading',
+ )?.[1];
+ loadingHandler?.();
+ willPreventUnloadHandler(event);
+ });
+ browser.reloadIgnoringCache();
+ browser.reloadIgnoringCache();
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ expect(
+ mockBrowserWindow.webContents.send.mock.calls.filter(
+ ([name]) => name === 'reloadConfirmationRequested',
+ ),
+ ).toHaveLength(1);
+ expect(mockBrowserWindow.webContents.reloadIgnoringCache).toHaveBeenCalledOnce();
+ browser.resolveUnloadConfirmation(true);
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ browser.resolveUnloadConfirmation(true);
+ expect(mockBrowserWindow.webContents.reloadIgnoringCache).toHaveBeenCalledTimes(2);
+ });
+
+ it('cancels a stale prompt and registers a fresh confirmation on retry', () => {
+ mockApp.coreUpdateManager.pauseForUnloadConfirmation = vi.fn(() => true);
+ const event = { preventDefault: vi.fn() };
+ mockBrowserWindow.webContents.reloadIgnoringCache.mockImplementation(() =>
+ willPreventUnloadHandler(event),
+ );
+ browser.reloadIgnoringCache();
+ browser.cancelUnloadConfirmation();
+ expect(mockBrowserWindow.webContents.send).toHaveBeenCalledWith(
+ 'reloadConfirmationCancelled',
+ undefined,
+ );
+ browser.resolveUnloadConfirmation(true);
+ expect(mockBrowserWindow.webContents.reloadIgnoringCache).toHaveBeenCalledOnce();
+ browser.reloadIgnoringCache();
+ expect(mockApp.coreUpdateManager.pauseForUnloadConfirmation).toHaveBeenCalledTimes(2);
+ browser.resolveUnloadConfirmation(true);
+ expect(mockBrowserWindow.webContents.reloadIgnoringCache).toHaveBeenCalledTimes(3);
+ });
+
+ it('keeps the page when the confirmation is dismissed', () => {
+ mockBrowserWindow.webContents.reloadIgnoringCache.mockImplementation(() =>
+ willPreventUnloadHandler({ preventDefault: vi.fn() }),
+ );
+ browser.reloadIgnoringCache();
+ browser.resolveUnloadConfirmation(false);
+ expect(mockBrowserWindow.webContents.reloadIgnoringCache).toHaveBeenCalledOnce();
+ });
+
+ it('does not replace an unknown unload operation with a reload', () => {
+ const event = { preventDefault: vi.fn() };
+ willPreventUnloadHandler(event);
+ browser.resolveUnloadConfirmation(true);
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ expect(mockBrowserWindow.webContents.send).not.toHaveBeenCalledWith(
+ 'reloadConfirmationRequested',
+ undefined,
+ );
+ expect(mockBrowserWindow.webContents.reloadIgnoringCache).not.toHaveBeenCalled();
+ });
+
+ it('does not replace a pending reload confirmation with a close', () => {
+ const event = { preventDefault: vi.fn() };
+ mockBrowserWindow.webContents.reloadIgnoringCache.mockImplementation(() =>
+ willPreventUnloadHandler(event),
+ );
+ browser.reloadIgnoringCache();
+ const closeEvent = { preventDefault: vi.fn() };
+ const closeHandler = mockBrowserWindow.on.mock.calls.find((call) => call[0] === 'close')?.[1];
+ closeHandler(closeEvent);
+ expect(closeEvent.preventDefault).toHaveBeenCalledOnce();
+ browser.resolveUnloadConfirmation(true);
+ expect(mockBrowserWindow.webContents.reloadIgnoringCache).toHaveBeenCalledTimes(2);
+ expect(mockBrowserWindow.close).not.toHaveBeenCalled();
+ });
+
+ it('silently defers automatic reloads without requesting a modal', () => {
+ const event = { preventDefault: vi.fn() };
+ mockBrowserWindow.webContents.reloadIgnoringCache.mockImplementationOnce(() => {
+ const loadingHandler = mockBrowserWindow.webContents.on.mock.calls.find(
+ (call) => call[0] === 'did-start-loading',
+ )?.[1];
+ loadingHandler?.();
+ willPreventUnloadHandler(event);
+ });
+ browser.reloadIgnoringCache(false, false);
+ expect(mockBrowserWindow.webContents.send).not.toHaveBeenCalledWith(
+ 'reloadConfirmationRequested',
+ undefined,
+ );
+ expect(event.preventDefault).not.toHaveBeenCalled();
+ expect(mockApp.coreUpdateManager.handleUnloadPrevented).toHaveBeenCalledOnce();
+ });
+
it('should bypass beforeunload once for a renderer OTA reload', () => {
const reloadEvent = { preventDefault: vi.fn() };
const laterEvent = { preventDefault: vi.fn() };
diff --git a/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts b/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts
index 9ae9609c247..0fad68dfbe5 100644
--- a/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/coreOta/CoreUpdateManager.ts
@@ -66,17 +66,22 @@ export class CoreUpdateManager {
private lastError: string | null = null;
private needsFullRelease = false;
private unloadPrevented = false;
+ private rollbackPointer: CorePointer | null = null;
private rollbackRenderer: RendererSource | null = null;
private pendingBootCheck = false;
private coldBootCheck = false;
private deferredColdBootCheck = false;
private mountedSeen = false;
+ private mountedRenderers = new Set<number | undefined>();
+ private unloadConfirmations = new Set<number>();
+ private pendingRenderers = new Set<number | undefined>();
private bootCrashCount = 0;
private bootCheckTimer: NodeJS.Timeout | null = null;
private loadPingTimer: NodeJS.Timeout | null = null;
private checkTimer: NodeJS.Timeout | null = null;
private checkInterval: NodeJS.Timeout | null = null;
private scheduledChecksStarted = false;
+ private appliedVersion: string | null = null;
private idleTimer: NodeJS.Timeout | null = null;
private gcTask: Promise<void> = Promise.resolve();
private checkTask: Promise<void> = Promise.resolve();
@@ -216,23 +221,58 @@ export class CoreUpdateManager {
if (this.scheduledChecksStarted && this.enabled) this.scheduleChecks();
};
- handleBootPing = (stage?: 'loaded' | 'mounted') => {
- if (stage !== 'loaded') this.mountedSeen = true;
+ handleBootPing = (stage?: 'loaded' | 'mounted', senderId?: number) => {
+ if (stage !== 'loaded') {
+ this.mountedSeen = true;
+ this.mountedRenderers.add(senderId);
+ }
if (!this.pendingBootCheck) return;
if (stage === 'loaded') {
this.clearLoadPingTimer();
return;
}
+ if (!this.coldBootCheck) {
+ this.pendingRenderers.delete(senderId);
+ if (this.pendingRenderers.size > 0) return;
+ }
+ this.completeBootCheck();
+ };
+
+ handleRendererDestroyed = (senderId: number) => {
+ if (
+ this.unloadConfirmations.delete(senderId) &&
+ this.unloadConfirmations.size === 0 &&
+ this.pendingBootCheck
+ )
+ this.armBootCheck();
+ this.mountedRenderers.delete(senderId);
+ if (
+ this.pendingRenderers.delete(senderId) &&
+ this.pendingRenderers.size === 0 &&
+ this.pendingBootCheck &&
+ !this.coldBootCheck
+ ) {
+ this.completeBootCheck();
+ }
+ };
+
+ private completeBootCheck() {
logger.info(`Core ${this.pointer.current} boot check passed`);
+ if (!this.coldBootCheck && this.pointer.current) {
+ this.appliedVersion = this.pointer.current;
+ this.app.browserManager.broadcastToAllWindows('coreUpdateApplied', this.appliedVersion);
+ }
this.clearBootTimers();
const shouldRunDeferredCheck = this.deferredColdBootCheck;
this.pendingBootCheck = false;
this.deferredColdBootCheck = false;
this.bootCrashCount = 0;
this.rollbackRenderer = null;
+ this.rollbackPointer = null;
+ this.unloadConfirmations.clear();
this.gc();
if (shouldRunDeferredCheck) this.checkForUpdates();
- };
+ }
handleRendererCrash = () => {
if (!this.pendingBootCheck) return;
@@ -244,13 +284,41 @@ export class CoreUpdateManager {
handleUnloadPrevented = () => {
this.unloadPrevented = true;
if (!this.pendingBootCheck || this.coldBootCheck) return;
- logger.info('Reload cancelled by renderer, cancelling boot check');
+ logger.info('Reload cancelled by renderer, restoring staged update');
+ this.app.browserManager.browsers.forEach((browser) => browser.cancelUnloadConfirmation());
+ this.unloadConfirmations.clear();
this.clearBootTimers();
this.pendingBootCheck = false;
+ this.app.rendererUrlManager.setActiveRenderer(this.rollbackRenderer);
this.rollbackRenderer = null;
+ if (this.rollbackPointer) {
+ const version = this.rollbackPointer.staged;
+ this.savePointer(this.rollbackPointer);
+ this.rollbackPointer = null;
+ this.staged = version ? { applyMode: 'reload', version } : null;
+ this.announceStaged();
+ this.app.browserManager.broadcastToAllWindows('coreUpdateDeferred', undefined);
+ }
+ };
+
+ pauseForUnloadConfirmation = (senderId: number) => {
+ if (!this.pendingBootCheck || this.coldBootCheck) return false;
+ this.unloadConfirmations.add(senderId);
+ this.clearBootTimers();
+ return true;
+ };
+
+ resolveUnloadConfirmation = (senderId: number, proceed: boolean) => {
+ if (!this.unloadConfirmations.delete(senderId) || !this.pendingBootCheck) return false;
+ if (!proceed) {
+ this.handleUnloadPrevented();
+ return false;
+ }
+ if (this.unloadConfirmations.size === 0) this.armBootCheck();
+ return true;
};
- applyStagedNow = () => {
+ applyStagedNow = ({ automatic = false } = {}) => {
if (!this.staged) return false;
if (this.staged.applyMode === 'relaunch') {
this.relaunchIntoCore();
@@ -272,15 +340,22 @@ export class CoreUpdateManager {
this.staged = null;
return false;
}
+ this.rollbackPointer = this.pointer;
this.savePointer({ current: version, previous: this.pointer.current, staged: null });
this.staged = null;
this.clearIdleTimer();
- this.reloadAllWindows();
+ this.pendingRenderers = new Set(
+ [...this.app.browserManager.browsers.values()]
+ .map((browser) => browser.browserWindow.webContents.id)
+ .filter((id) => this.mountedRenderers.has(id)),
+ );
this.armBootCheck();
+ this.reloadAllWindows(!automatic);
return true;
};
getStatus = () => ({
+ appliedVersion: this.appliedVersion,
applyMode: this.staged?.applyMode ?? null,
current: this.pointer.current,
disabledReasons: this.disabledReasons,
@@ -303,7 +378,7 @@ export class CoreUpdateManager {
logger.info('Core OTA check skipped', { reason: !this.enabled ? 'disabled' : 'busy' });
return;
}
- if (this.pendingBootCheck && this.coldBootCheck) {
+ if (this.pendingBootCheck) {
this.deferredColdBootCheck = true;
logger.info('Core OTA check deferred', { reason: 'cold-boot-check' });
return;
@@ -487,7 +562,8 @@ export class CoreUpdateManager {
if (BrowserWindow.getAllWindows().some((window) => window.isFocused())) return;
this.clearIdleTimer();
this.idleTimer = setTimeout(() => {
- if (this.staged?.applyMode === 'reload' && !this.unloadPrevented) this.applyStagedNow();
+ if (this.staged?.applyMode === 'reload' && !this.unloadPrevented)
+ this.applyStagedNow({ automatic: true });
}, IDLE_APPLY_DELAY);
this.idleTimer.unref?.();
};
@@ -515,6 +591,8 @@ export class CoreUpdateManager {
}
this.app.rendererUrlManager.setActiveRenderer(this.rollbackRenderer);
this.rollbackRenderer = null;
+ this.rollbackPointer = null;
+ this.unloadConfirmations.clear();
this.gc();
this.reloadAllWindows();
}
@@ -547,10 +625,10 @@ export class CoreUpdateManager {
this.bootCheckTimer = null;
}
- private reloadAllWindows() {
+ private reloadAllWindows(promptBeforeUnload = false) {
this.app.browserManager.browsers.forEach((browser) => {
try {
- browser.browserWindow.webContents.reloadIgnoringCache();
+ browser.reloadIgnoringCache(false, promptBeforeUnload);
} catch {}
});
}
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.ts
index a03e81a3ebb..09e20b541a6 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
@@ -73,7 +73,18 @@ const makeApp = () => ({
browserManager: {
broadcastToAllWindows: vi.fn(),
browsers: new Map([
- ['main', { browserWindow: { webContents: { reloadIgnoringCache: vi.fn() } } }],
+ [
+ 'main',
+ {
+ browserWindow: { webContents: { id: 1, reloadIgnoringCache: vi.fn() } },
+ cancelUnloadConfirmation: vi.fn(),
+ reloadIgnoringCache: vi.fn(function (this: {
+ browserWindow: { webContents: { reloadIgnoringCache: () => void } };
+ }) {
+ this.browserWindow.webContents.reloadIgnoringCache();
+ }),
+ },
+ ],
]),
},
isQuiting: false,
@@ -613,6 +624,52 @@ describe('CoreUpdateManager checkForUpdates', () => {
expect(existsSync(coreDir('1.0.1'))).toBe(false);
});
+ it('retains a healthy hot update for late subscribers without changing the booted core', async () => {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const { app, manager } = await loadManager();
+ const running = manager.getStatus().running;
+ await manager.checkForUpdates();
+ expect(manager.getStatus().appliedVersion).toBeNull();
+ manager.applyStagedNow();
+ manager.handleBootPing('loaded');
+ expect(manager.getStatus().appliedVersion).toBeNull();
+ expect(app.browserManager.broadcastToAllWindows).not.toHaveBeenCalledWith(
+ 'coreUpdateApplied',
+ expect.anything(),
+ );
+ manager.handleBootPing('mounted');
+ expect(manager.getStatus()).toMatchObject({ appliedVersion: '1.0.1', running, staged: null });
+ expect(app.browserManager.broadcastToAllWindows).toHaveBeenCalledWith(
+ 'coreUpdateApplied',
+ '1.0.1',
+ );
+ manager.handleBootPing('mounted');
+ expect(
+ app.browserManager.broadcastToAllWindows.mock.calls.filter(
+ ([event]) => event === 'coreUpdateApplied',
+ ),
+ ).toHaveLength(1);
+ });
+
+ it('does not announce a failed hot update as completed', async () => {
+ vi.useFakeTimers();
+ try {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const { app, manager } = await loadManager();
+ await manager.checkForUpdates();
+ manager.applyStagedNow();
+ await vi.advanceTimersByTimeAsync(60_000);
+ manager.handleBootPing('mounted');
+ expect(manager.getStatus().appliedVersion).toBeNull();
+ expect(app.browserManager.broadcastToAllWindows).not.toHaveBeenCalledWith(
+ 'coreUpdateApplied',
+ expect.anything(),
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('stages a renderer-only update as core-reload and applies it in place', async () => {
const remote = rendererOnly('1.0.1', 1);
serveLatest(remote);
@@ -857,18 +914,111 @@ describe('CoreUpdateManager checkForUpdates', () => {
expect(readdirSync(path.join(otaRoot(), 'cores')).sort()).toEqual(['0.9.5', '1.0.1', '1.0.2']);
});
- it('cancels the boot check instead of blacklisting when the renderer vetoes reload', async () => {
+ it('waits for all mounted windows and retains retry when a later window vetoes', async () => {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const app = makeApp();
+ app.browserManager.browsers.set('second', {
+ browserWindow: { webContents: { id: 2, reloadIgnoringCache: vi.fn() } },
+ cancelUnloadConfirmation: vi.fn(),
+ reloadIgnoringCache: vi.fn(function (this: {
+ browserWindow: { webContents: { reloadIgnoringCache: () => void } };
+ }) {
+ this.browserWindow.webContents.reloadIgnoringCache();
+ }),
+ });
+ const { manager } = await loadManager(app);
+ manager.handleBootPing('mounted', 1);
+ manager.handleBootPing('mounted', 2);
+ await manager.checkForUpdates();
+ manager.applyStagedNow();
+ manager.handleBootPing('mounted', 1);
+ expect(manager.getStatus().appliedVersion).toBeNull();
+ manager.handleUnloadPrevented();
+ expect(manager.getStatus()).toMatchObject({ appliedVersion: null, staged: '1.0.1' });
+ expect(app.browserManager.broadcastToAllWindows).not.toHaveBeenCalledWith(
+ 'coreUpdateApplied',
+ expect.anything(),
+ );
+ manager.applyStagedNow();
+ manager.handleBootPing('mounted', 2);
+ expect(manager.getStatus().appliedVersion).toBeNull();
+ manager.handleBootPing('mounted', 1);
+ expect(manager.getStatus().appliedVersion).toBe('1.0.1');
+ });
+
+ it('does not roll back when a remaining update participant closes', async () => {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const app = makeApp();
+ app.browserManager.browsers.set('second', {
+ browserWindow: { webContents: { id: 2, reloadIgnoringCache: vi.fn() } },
+ cancelUnloadConfirmation: vi.fn(),
+ reloadIgnoringCache: vi.fn(function (this: {
+ browserWindow: { webContents: { reloadIgnoringCache: () => void } };
+ }) {
+ this.browserWindow.webContents.reloadIgnoringCache();
+ }),
+ });
+ const { manager } = await loadManager(app);
+ manager.handleBootPing('mounted', 1);
+ manager.handleBootPing('mounted', 2);
+ await manager.checkForUpdates();
+ manager.applyStagedNow();
+ manager.handleBootPing('mounted', 1);
+ manager.handleRendererDestroyed(2);
+ expect(manager.getStatus().appliedVersion).toBe('1.0.1');
+ expect(readPointer(otaRoot(), ABI).blacklist).toEqual([]);
+ });
+
+ it('pauses the boot deadline while awaiting UI confirmation and restores staging on cancel', async () => {
vi.useFakeTimers();
try {
serveLatest(rendererOnly('1.0.1', 1));
const { manager } = await loadManager();
await manager.checkForUpdates();
manager.applyStagedNow();
+ expect(manager.pauseForUnloadConfirmation(1)).toBe(true);
+ vi.advanceTimersByTime(60_000);
+ expect(readPointer(otaRoot(), ABI).blacklist).toEqual([]);
+ expect(manager.resolveUnloadConfirmation(1, false)).toBe(false);
+ expect(manager.getStatus()).toMatchObject({ staged: '1.0.1', appliedVersion: null });
+ expect(manager.resolveUnloadConfirmation(1, true)).toBe(false);
+ manager.applyStagedNow();
+ manager.pauseForUnloadConfirmation(1);
+ expect(manager.resolveUnloadConfirmation(1, true)).toBe(true);
+ manager.handleBootPing('mounted');
+ expect(manager.getStatus().appliedVersion).toBe('1.0.1');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+ it('preserves the update for retry when the renderer vetoes reload', async () => {
+ vi.useFakeTimers();
+ try {
+ serveLatest(rendererOnly('1.0.1', 1));
+ const { app, manager } = await loadManager();
+ const originalRenderer = { resolve: () => null };
+ app.rendererUrlManager.activeRenderer = originalRenderer;
+ await manager.checkForUpdates();
+ const before = readPointer(otaRoot(), ABI);
+ manager.applyStagedNow();
manager.handleUnloadPrevented();
vi.advanceTimersByTime(20_000);
- expect(readPointer(otaRoot(), ABI)).toMatchObject({ blacklist: [], current: '1.0.1' });
+ expect(app.browserManager.broadcastToAllWindows).toHaveBeenCalledWith(
+ 'coreUpdateDeferred',
+ undefined,
+ );
+ expect(readPointer(otaRoot(), ABI)).toEqual(before);
+ expect(app.rendererUrlManager.activeRenderer).toBe(originalRenderer);
+ expect(manager.getStatus()).toMatchObject({
+ appliedVersion: null,
+ applyMode: 'reload',
+ staged: '1.0.1',
+ });
+ expect(manager.applyStagedNow()).toBe(true);
+ manager.handleBootPing('mounted');
+ expect(manager.getStatus()).toMatchObject({ appliedVersion: '1.0.1', staged: null });
} finally {
vi.useRealTimers();
}
diff --git a/apps/desktop/src/main/menus/impls/BaseMenuPlatform.test.ts b/apps/desktop/src/main/menus/impls/BaseMenuPlatform.test.ts
index 7571b3c7d30..488b70adfcb 100644
--- a/apps/desktop/src/main/menus/impls/BaseMenuPlatform.test.ts
+++ b/apps/desktop/src/main/menus/impls/BaseMenuPlatform.test.ts
@@ -6,7 +6,11 @@ import type { App } from '@/core/App';
import { BaseMenuPlatform } from './BaseMenuPlatform';
// Create a concrete implementation for testing
-class TestMenuPlatform extends BaseMenuPlatform {}
+class TestMenuPlatform extends BaseMenuPlatform {
+ buildReloadItem(ignoreCache = false) {
+ return this.buildReloadMenuItem('Reload', ignoreCache);
+ }
+}
class TestDevToolsMenuPlatform extends BaseMenuPlatform {
buildDevToolsItem(label = 'Developer Tools', accelerator = 'F12') {
return this.buildDevToolsMenuItem(label, accelerator);
@@ -40,6 +44,8 @@ const createBrowserWindow = ({
isDevToolsFocused: vi.fn(() => isDevToolsFocused),
isDevToolsOpened: vi.fn(() => isDevToolsOpened),
openDevTools: vi.fn(),
+ reload: vi.fn(),
+ reloadIgnoringCache: vi.fn(),
setDevToolsWebContents: vi.fn(),
},
}) as unknown as ElectronBrowserWindow;
@@ -50,6 +56,7 @@ const mockApp = {
ns: vi.fn(),
},
browserManager: {
+ browsers: new Map(),
getMainWindow: vi.fn(),
showMainWindow: vi.fn(),
retrieveByIdentifier: vi.fn(),
@@ -95,6 +102,30 @@ describe('BaseMenuPlatform', () => {
});
});
+ describe('reload confirmation', () => {
+ it.each([false, true])(
+ 'preserves the requested cache behavior (ignoreCache=%s)',
+ (ignoreCache) => {
+ const target = createBrowserWindow({});
+ const runWithUnloadConfirmation = vi.fn();
+ mockApp.browserManager.browsers.set('test', {
+ webContents: target.webContents,
+ runWithUnloadConfirmation,
+ } as any);
+ const item = menuPlatform.buildReloadItem(ignoreCache);
+ item.click?.(undefined as any, target, undefined as any);
+ expect(target.webContents.reload).not.toHaveBeenCalled();
+ expect(target.webContents.reloadIgnoringCache).not.toHaveBeenCalled();
+
+ const originalOperation = runWithUnloadConfirmation.mock.calls[0][0];
+ originalOperation();
+ expect(target.webContents.reload).toHaveBeenCalledTimes(ignoreCache ? 0 : 1);
+ expect(target.webContents.reloadIgnoringCache).toHaveBeenCalledTimes(ignoreCache ? 1 : 0);
+ mockApp.browserManager.browsers.clear();
+ },
+ );
+ });
+
describe('buildDevToolsMenuItem', () => {
let devToolsMenuPlatform: TestDevToolsMenuPlatform;
diff --git a/apps/desktop/src/main/menus/impls/BaseMenuPlatform.ts b/apps/desktop/src/main/menus/impls/BaseMenuPlatform.ts
index 9c4f95dd104..8916b2326ab 100644
--- a/apps/desktop/src/main/menus/impls/BaseMenuPlatform.ts
+++ b/apps/desktop/src/main/menus/impls/BaseMenuPlatform.ts
@@ -35,6 +35,27 @@ export abstract class BaseMenuPlatform {
];
}
+ protected buildReloadMenuItem(label: string, ignoreCache = false): MenuItemConstructorOptions {
+ return {
+ accelerator: ignoreCache ? 'CmdOrCtrl+Shift+R' : 'CmdOrCtrl+R',
+ click: (_item, win) => {
+ const target =
+ win && 'webContents' in win ? (win as BrowserWindow) : BrowserWindow.getFocusedWindow();
+ if (!target) return;
+ const operation = () => {
+ if (ignoreCache) target.webContents.reloadIgnoringCache();
+ else target.webContents.reload();
+ };
+ const browser = [...this.app.browserManager.browsers.values()].find(
+ (browser) => browser.webContents === target.webContents,
+ );
+ if (browser) browser.runWithUnloadConfirmation(operation);
+ else operation();
+ },
+ label,
+ };
+ }
+
protected buildDevToolsMenuItem(label: string, accelerator?: string): MenuItemConstructorOptions {
return {
accelerator,
diff --git a/apps/desktop/src/main/menus/impls/linux.ts b/apps/desktop/src/main/menus/impls/linux.ts
index ea8c20f97a9..1bdbe161d53 100644
--- a/apps/desktop/src/main/menus/impls/linux.ts
+++ b/apps/desktop/src/main/menus/impls/linux.ts
@@ -257,8 +257,8 @@ export class LinuxMenu extends BaseMenuPlatform implements IMenuPlatform {
template.push({
label: t('dev.title'),
submenu: [
- { label: t('dev.reload'), role: 'reload' },
- { label: t('dev.forceReload'), role: 'forceReload' },
+ this.buildReloadMenuItem(t('dev.reload')),
+ this.buildReloadMenuItem(t('dev.forceReload'), true),
this.buildDevToolsMenuItem(t('dev.devTools')),
{ type: 'separator' },
{
diff --git a/apps/desktop/src/main/menus/impls/macOS.ts b/apps/desktop/src/main/menus/impls/macOS.ts
index 1d4c017b378..b66bf5f02dc 100644
--- a/apps/desktop/src/main/menus/impls/macOS.ts
+++ b/apps/desktop/src/main/menus/impls/macOS.ts
@@ -202,8 +202,8 @@ export class MacOSMenu extends BaseMenuPlatform implements IMenuPlatform {
{
label: t('view.title'),
submenu: [
- { label: t('view.reload'), role: 'reload' },
- { label: t('view.forceReload'), role: 'forceReload' },
+ this.buildReloadMenuItem(t('view.reload')),
+ this.buildReloadMenuItem(t('view.forceReload'), true),
this.buildDevToolsMenuItem(t('dev.devTools'), 'F12'),
{ type: 'separator' },
this.buildZoomMenuItem('reset', t('view.resetZoom'), 'CmdOrCtrl+0'),
diff --git a/apps/desktop/src/main/menus/impls/windows.ts b/apps/desktop/src/main/menus/impls/windows.ts
index 8ac0c26ce4e..fcf8bda0a6d 100644
--- a/apps/desktop/src/main/menus/impls/windows.ts
+++ b/apps/desktop/src/main/menus/impls/windows.ts
@@ -243,8 +243,8 @@ export class WindowsMenu extends BaseMenuPlatform implements IMenuPlatform {
template.push({
label: t('dev.title'),
submenu: [
- { label: t('dev.reload'), role: 'reload' },
- { label: t('dev.forceReload'), role: 'forceReload' },
+ this.buildReloadMenuItem(t('dev.reload')),
+ this.buildReloadMenuItem(t('dev.forceReload'), true),
this.buildDevToolsMenuItem(t('dev.devTools')),
{ type: 'separator' },
{
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.json
index 63afad3978e..3580c5b85ad 100644
--- a/locales/en-US/electron.json
+++ b/locales/en-US/electron.json
@@ -147,6 +147,9 @@
"tab.unread": "New message",
"updater.checkingUpdate": "Checking for updates",
"updater.checkingUpdateDesc": "Retrieving version information...",
+ "updater.confirmReloadContinue": "Continue anyway",
+ "updater.confirmReloadDescription": "You may have unsaved changes or work in progress. Continuing may lose that work.",
+ "updater.confirmReloadTitle": "Leave this page?",
"updater.downloadNewVersion": "Download new version",
"updater.downloadingUpdate": "Downloading update",
"updater.downloadingUpdateDesc": "The update is downloading, please wait...",
@@ -158,7 +161,9 @@
"updater.newVersionAvailable": "New version available",
"updater.newVersionAvailableDesc": "A new version {{version}} has been found, would you like to download it now?",
"updater.rendererReady": "Version {{version}} is ready",
+ "updater.rendererUpdateDeferred": "A page prevented reloading. Finish your current work, then try updating again.",
"updater.rendererUpdateError": "Couldn't install the update. Try again.",
+ "updater.rendererUpdated": "Updated to version {{version}}",
"updater.restartAndInstall": "Install updates and restart",
"updater.updateError": "Update error",
"updater.updateReady": "A new version is available",
diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.json
index afc40aa5609..2c6c45e795f 100644
--- a/locales/zh-CN/electron.json
+++ b/locales/zh-CN/electron.json
@@ -147,6 +147,9 @@
"tab.unread": "新消息",
"updater.checkingUpdate": "检查新版本",
"updater.checkingUpdateDesc": "正在获取版本信息…",
+ "updater.confirmReloadContinue": "仍然继续",
+ "updater.confirmReloadDescription": "页面可能有未保存的内容或正在进行的操作,继续可能导致这些内容丢失。",
+ "updater.confirmReloadTitle": "要离开当前页面吗?",
"updater.downloadNewVersion": "下载新版本",
"updater.downloadingUpdate": "正在下载更新",
"updater.downloadingUpdateDesc": "更新正在下载中,请稍候…",
@@ -158,7 +161,9 @@
"updater.newVersionAvailable": "新版本可用",
"updater.newVersionAvailableDesc": "发现新版本 {{version}},是否立即下载?",
"updater.rendererReady": "新版本 {{version}} 已就绪",
+ "updater.rendererUpdateDeferred": "页面阻止了刷新,请完成当前操作后重试更新。",
"updater.rendererUpdateError": "更新失败,请重试。",
+ "updater.rendererUpdated": "已更新至版本 {{version}}",
"updater.restartAndInstall": "安装更新并重启",
"updater.updateError": "更新错误",
"updater.updateReady": "有新版本可用",
diff --git a/packages/electron-client-ipc/src/events/update.ts b/packages/electron-client-ipc/src/events/update.ts
index dd449505d6f..6464c0eb3a4 100644
--- a/packages/electron-client-ipc/src/events/update.ts
+++ b/packages/electron-client-ipc/src/events/update.ts
@@ -1,6 +1,10 @@
import type { ProgressInfo, UpdateChannel, UpdateInfo, UpdaterState } from '../types';
export interface UpdateBroadcastEvents {
+ coreUpdateApplied: (version: string) => void;
+ coreUpdateDeferred: () => void;
+ reloadConfirmationCancelled: () => void;
+ reloadConfirmationRequested: () => void;
updateChannelChanged: (channel: UpdateChannel) => void;
updateDownloadProgress: (progress: ProgressInfo) => void;
updateError: (message: string) => void;
diff --git a/packages/electron-client-ipc/src/types/update.ts b/packages/electron-client-ipc/src/types/update.ts
index 1af7bf194a8..8349777d568 100644
--- a/packages/electron-client-ipc/src/types/update.ts
+++ b/packages/electron-client-ipc/src/types/update.ts
@@ -27,6 +27,8 @@ export interface UpdateInfo {
}
export interface CoreUpdateStatus {
+ /** Renderer update confirmed healthy in this process, including after hot reload. */
+ appliedVersion?: string | null;
applyMode: 'reload' | 'relaunch' | null;
current: string | null;
disabledReasons: string[];
diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.ts
index 3206c8340fb..7eb69f3a80d 100644
--- a/packages/locales/src/default/electron.ts
+++ b/packages/locales/src/default/electron.ts
@@ -161,6 +161,13 @@ export default {
'updater.newVersionAvailableDesc':
'A new version {{version}} has been found, would you like to download it now?',
'updater.rendererReady': 'Version {{version}} is ready',
+ 'updater.confirmReloadTitle': 'Leave this page?',
+ 'updater.confirmReloadDescription':
+ 'You may have unsaved changes or work in progress. Continuing may lose that work.',
+ 'updater.confirmReloadContinue': 'Continue anyway',
+ 'updater.rendererUpdateDeferred':
+ 'A page prevented reloading. Finish your current work, then try updating again.',
+ 'updater.rendererUpdated': 'Updated to version {{version}}',
'updater.rendererUpdateError': "Couldn't install the update. Try again.",
'updater.restartAndInstall': 'Install updates and restart',
'updater.updateError': 'Update error',
diff --git a/src/features/Electron/updater/UpdateNotification.tsx b/src/features/Electron/updater/UpdateNotification.tsx
index 8a2eda04e28..06e129945fb 100644
--- a/src/features/Electron/updater/UpdateNotification.tsx
+++ b/src/features/Electron/updater/UpdateNotification.tsx
@@ -5,10 +5,11 @@ import { Button as BaseButton, createModal, toast, useModalContext } from '@lobe
import { createStaticStyles, cssVar } from 'antd-style';
import { t } from 'i18next';
import { X } from 'lucide-react';
-import React, { memo, useState } from 'react';
+import React, { memo, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { autoUpdateService } from '@/services/electron/autoUpdate';
+import { rendererOtaService } from '@/services/electron/rendererOta';
import { useUserStore } from '@/store/user';
import { userGeneralSettingsSelectors } from '@/store/user/selectors';
@@ -142,9 +143,46 @@ export const UpdateNotification: React.FC = () => {
'unconfirm' | 'installLater' | 'installNow' | null
>('unconfirm');
const [isInstalling, setIsInstalling] = useState(false);
+ const [appliedVersion, setAppliedVersion] = useState<string | null>(null);
+ const receivedUpdateEvent = useRef(false);
+ useEffect(() => {
+ let active = true;
+ rendererOtaService
+ .getStatus()
+ .then((status) => {
+ if (!active || receivedUpdateEvent.current) return;
+ setAppliedVersion((version) => version ?? status.appliedVersion ?? null);
+ if (status.staged && status.applyMode) {
+ setUpdateInfo(
+ (current) =>
+ current ?? {
+ kind: status.applyMode === 'relaunch' ? 'core-relaunch' : 'core-reload',
+ version: status.staged!,
+ },
+ );
+ }
+ })
+ .catch(console.error);
+ return () => {
+ active = false;
+ };
+ }, []);
+ useWatchBroadcast('coreUpdateApplied', (version) => {
+ receivedUpdateEvent.current = true;
+ setAppliedVersion(version);
+ setUpdateInfo((current) =>
+ current?.version === version && current.kind !== 'app' ? null : current,
+ );
+ setIsInstalling(false);
+ });
+ useWatchBroadcast('coreUpdateDeferred', () => {
+ setIsInstalling(false);
+ toast.info(tElectron('updater.rendererUpdateDeferred'));
+ });
const isDevMode = useUserStore((s) => userGeneralSettingsSelectors.config(s).isDevMode);
useWatchBroadcast('updateReady', (info) => {
+ receivedUpdateEvent.current = true;
setUpdateInfo((current) => selectUpdateInfo(current, info));
if (info.kind === 'app' || info.kind === 'core-relaunch') setInstallConfirmMode('unconfirm');
});
@@ -204,7 +242,15 @@ export const UpdateNotification: React.FC = () => {
);
}
- if (!updateInfo) return null;
+ if (!updateInfo)
+ return appliedVersion ? (
+ <div className={styles.installLaterToast}>
+ <span>{tElectron('updater.rendererUpdated', { version: appliedVersion })}</span>
+ <BaseButton size={'small'} type={'text'} onClick={() => setAppliedVersion(null)}>
+ {tElectron('updater.ignore')}
+ </BaseButton>
+ </div>
+ ) : null;
if (installConfirmMode === 'installLater') {
return (
diff --git a/src/features/Settings/about/features/Version.tsx b/src/features/Settings/about/features/Version.tsx
index 76219c5b699..a06a0b3757c 100644
--- a/src/features/Settings/about/features/Version.tsx
+++ b/src/features/Settings/about/features/Version.tsx
@@ -5,9 +5,9 @@ import {
useWatchBroadcast,
} from '@lobechat/electron-client-ipc';
import { Block, Flexbox, Tooltip } from '@lobehub/ui';
-import { Button, Skeleton, Tag } from '@lobehub/ui/base-ui';
+import { Button, Tag } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
-import { memo, Suspense, use, useEffect, useMemo, useRef, useState } from 'react';
+import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ProductLogo } from '@/components/Branding';
@@ -27,19 +27,23 @@ import {
import { APP_VERSION } from './appVersion';
import { formatOtaVersionLabel, getDisplayedOtaVersion } from './otaVersion';
-let otaVersionPromise: Promise<string | null> | undefined;
-
-const getOtaVersion = () => {
- otaVersionPromise ??= rendererOtaService.getStatus().then(getDisplayedOtaVersion);
-
- return otaVersionPromise;
-};
-
const OtaVersionTag = memo(() => {
- const otaVersion = use(getOtaVersion());
+ const [otaVersion, setOtaVersion] = useState<string | null>(null);
+ useEffect(() => {
+ let active = true;
+ rendererOtaService
+ .getStatus()
+ .then((status) => {
+ if (active) setOtaVersion((version) => version ?? getDisplayedOtaVersion(status));
+ })
+ .catch(console.error);
+ return () => {
+ active = false;
+ };
+ }, []);
+ useWatchBroadcast('coreUpdateApplied', setOtaVersion);
if (!otaVersion) return null;
-
return <Tag style={{ minWidth: 60 }}>{formatOtaVersionLabel(otaVersion)}</Tag>;
});
@@ -212,11 +216,7 @@ const Version = memo<{ mobile?: boolean }>(({ mobile }) => {
v{APP_VERSION}
</Tag>
- {isDesktop && (
- <Suspense fallback={<Skeleton height={22} radius={6} width={60} />}>
- <OtaVersionTag />
- </Suspense>
- )}
+ {isDesktop && <OtaVersionTag />}
{buildChannel && buildChannel !== 'stable' && (
<Tag color={'gold'}>
diff --git a/src/features/Settings/about/features/otaVersion.test.ts b/src/features/Settings/about/features/otaVersion.test.ts
index 3c86ed5cd77..e982c674bb0 100644
--- a/src/features/Settings/about/features/otaVersion.test.ts
+++ b/src/features/Settings/about/features/otaVersion.test.ts
@@ -17,6 +17,32 @@ const status = (patch: Partial<CoreUpdateStatus>): CoreUpdateStatus => ({
});
describe('getDisplayedOtaVersion', () => {
+ it('shows a confirmed hot update without requiring a main-process restart', () => {
+ expect(
+ getDisplayedOtaVersion(
+ status({ appliedVersion: '1.0.2', current: '1.0.2', running: '1.0.1' }),
+ ),
+ ).toBe('1.0.2');
+ });
+
+ it('keeps the applied version while a newer update awaits relaunch', () => {
+ expect(
+ getDisplayedOtaVersion(
+ status({
+ appliedVersion: '1.0.2',
+ applyMode: 'relaunch',
+ current: '1.0.3',
+ running: '1.0.1',
+ staged: '1.0.3',
+ }),
+ ),
+ ).toBe('1.0.2');
+ });
+
+ it('does not show an unconfirmed hot update as applied', () => {
+ expect(getDisplayedOtaVersion(status({ current: '1.0.2', running: '1.0.1' }))).toBe('1.0.1');
+ });
+
it('uses the running core version when present', () => {
expect(
getDisplayedOtaVersion(status({ current: '2.2.13', running: '2.2.14', staged: '2.2.15' })),
diff --git a/src/features/Settings/about/features/otaVersion.ts b/src/features/Settings/about/features/otaVersion.ts
index 710a79a97e4..65f498869a8 100644
--- a/src/features/Settings/about/features/otaVersion.ts
+++ b/src/features/Settings/about/features/otaVersion.ts
@@ -1,7 +1,7 @@
import type { CoreUpdateStatus } from '@lobechat/electron-client-ipc';
export const getDisplayedOtaVersion = (status: CoreUpdateStatus | null): string | null =>
- status?.running ?? status?.current ?? null;
+ status?.appliedVersion ?? status?.running ?? status?.current ?? null;
export const formatOtaVersionLabel = (version: string): string =>
`OTA ${version.replace('-core.', '-')}`;
diff --git a/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx b/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx
index 7b50f4f23e6..b95ae5389c6 100644
--- a/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx
+++ b/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx
@@ -1,7 +1,10 @@
'use client';
import { useWatchBroadcast } from '@lobechat/electron-client-ipc';
-import { useEffect } from 'react';
+import { Flexbox } from '@lobehub/ui';
+import { Button, createModal } from '@lobehub/ui/base-ui';
+import { useEffect, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
import { useMacWindowFullscreen } from '@/features/Electron/system/useMacWindowFullscreen';
import { rendererOtaService } from '@/services/electron/rendererOta';
@@ -20,6 +23,61 @@ import { useElectronStore } from '@/store/electron';
*/
const ElectronAppStateSync = () => {
useMacWindowFullscreen();
+ const { t: tElectron } = useTranslation('electron');
+ const { t } = useTranslation('common');
+ const dismissConfirmation = useRef<(() => void) | null>(null);
+ useWatchBroadcast('reloadConfirmationRequested', () => {
+ dismissConfirmation.current?.();
+ let resolved = false;
+ const resolve = (proceed: boolean) => {
+ if (resolved) return;
+ resolved = true;
+ return rendererOtaService.resolveUnloadConfirmation(proceed).catch(console.error);
+ };
+ const modal = createModal({
+ title: tElectron('updater.confirmReloadTitle'),
+ content: tElectron('updater.confirmReloadDescription'),
+ footer: (
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button
+ onClick={() => {
+ void resolve(false);
+ modal.close();
+ }}
+ >
+ {t('cancel')}
+ </Button>
+ <Button
+ type={'primary'}
+ onClick={() => {
+ void resolve(true);
+ modal.close();
+ }}
+ >
+ {tElectron('updater.confirmReloadContinue')}
+ </Button>
+ </Flexbox>
+ ),
+ onOpenChange: (open) => {
+ if (!open) void resolve(false);
+ },
+ });
+ dismissConfirmation.current = () => {
+ resolved = true;
+ modal.close();
+ };
+ });
+
+ useWatchBroadcast('reloadConfirmationCancelled', () => {
+ dismissConfirmation.current?.();
+ dismissConfirmation.current = null;
+ });
+ useEffect(
+ () => () => {
+ dismissConfirmation.current?.();
+ },
+ [],
+ );
const [useInitElectronAppState, updateElectronAppState] = useElectronStore((s) => [
s.useInitElectronAppState,
diff --git a/src/services/electron/rendererOta.ts b/src/services/electron/rendererOta.ts
index 0bcb1697be8..839320f9220 100644
--- a/src/services/electron/rendererOta.ts
+++ b/src/services/electron/rendererOta.ts
@@ -11,6 +11,10 @@ class RendererOtaService {
return ensureElectronIpc().rendererOta.applyNow();
};
+ resolveUnloadConfirmation = async (proceed: boolean) => {
+ return ensureElectronIpc().rendererOta.resolveUnloadConfirmation(proceed);
+ };
+
getStatus = async (): Promise<CoreUpdateStatus> => {
return ensureElectronIpc().rendererOta.getStatus();
};