Skip to content

fix: sync the desktop startup theme with the dashboard - #198

Merged
zouyonghe merged 11 commits into
AstrBotDevs:mainfrom
zouyonghe:fix/startup-theme-sync
Nov 24, 2026
Merged

zouyonghe merged 11 commits into
AstrBotDevs:mainfrom
zouyonghe:fix/startup-theme-sync

Conversation

@zouyonghe

@zouyonghe zouyonghe commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Closes #197.

Summary / 改动概述

  • 保存 Dashboard 中的浅色、深色和跟随系统偏好,桌面端重启时直接使用该设置。
  • 启动页在绘制前应用主题。未保存偏好时跟随系统,启动失败页也使用对应配色。
  • 旧版 Dashboard 的 uiTheme 设置可在首次打开 Dashboard 时同步。

Verification / 验证方式

  • Linux Tauri 冒烟测试通过。用 Dashboard 测试页选择深色,确认桌面端持久化设置,重启后启动页实际绘制深色背景。
  • Chromium 验证通过。系统浅色下显示显式深色,系统深色下显示显式浅色,未指定时跟随系统。深色启动失败页的状态和修复按钮正常显示。
  • pnpm test:prepare-resources(226 项)、LC_ALL=C cargo test --locked(273 项)、Python CI 脚本测试(95 项)通过。cargo fmt --check、cargo clippy --locked --all-targets -- -D warnings 和 cargo build --locked 通过。
  • Windows 安装包的首屏仍待实机验证。

Checklist / 检查清单

  • 此改动不是破坏性变更。
  • 已在本地验证,结果见上文。
  • 此 PR 不包含恶意代码。

Summary by Sourcery

Synchronize the desktop startup experience with the Dashboard theme preference and defer window presentation until the themed Dashboard is ready.

New Features:

  • Persist the Dashboard’s light, dark, or system theme preference for use during desktop startup.
  • Apply the selected or system theme before rendering the startup page, including startup error states.
  • Synchronize legacy Dashboard theme settings when the Dashboard first opens.

Bug Fixes:

  • Prevent stale Dashboard documents and interrupted storage or IPC operations from overwriting newer startup theme preferences.
  • Keep startup failures visible with appropriately themed recovery messaging when the Dashboard cannot load.

Enhancements:

  • Coordinate startup-page and Dashboard loading so the main window is shown only after the themed Dashboard is ready, with timeout and fallback handling.

Tests:

  • Add coverage for theme synchronization, legacy preference migration, retries, concurrent changes, document revisions, startup rendering, and loading state transitions.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src-tauri/src/bridge_bootstrap.js" line_range="1134" />
<code_context>
+        }
+        if (requestedTheme === theme) return;
+        requestedTheme = theme;
+        const result = await invokeBridge(BRIDGE_COMMANDS.SET_STARTUP_THEME, { theme });
+        if (result?.ok === false && requestedTheme === theme) requestedTheme = undefined;
+      };
</code_context>
<issue_to_address>
**Older theme overwrites latest choice**

When the Dashboard theme changes again while an earlier startup-theme invocation is still in flight, `sync` starts `invokeBridge` calls independently, and `desktop_bridge_set_startup_theme` persists requests without checking their order; an older request can overwrite the newer choice, so the next launch uses the wrong theme.

Serialize startup-theme writes or prevent stale requests from overwriting newer choices.

Also at `src-tauri/src/bridge/commands.rs:558-559`, `src-tauri/src/bridge/commands.rs:562-563`.
</issue_to_address>

### Comment 2
<location path="src-tauri/src/bridge_bootstrap.js" line_range="1139-1144" />
<code_context>
+      };
+
+      // Storage methods live on the prototype. Keep sessionStorage and other keys untouched.
+      for (const method of ['setItem', 'removeItem', 'clear']) {
+        const original = target[method];
+        target[method] = function (...args) {
+          original.apply(this, args);
+          if (this === storage && (method === 'clear' || args[0] === 'themeMode' || args[0] === 'uiTheme')) {
+            void sync().catch(() => {});
+          }
+        };
</code_context>
<issue_to_address>
**Dashboard changes never reach startup preference**

When the browser allows `patchLocalStorageBridgeSync` to install own methods on the `localStorage` instance, `patchLocalStorageBridgeSync` installs own methods that shadow the wrapped prototype methods and call bound native methods directly, bypassing the wrappers that call `sync`; the saved startup theme stays outdated.

Ensure startup-theme syncing also wraps the own storage methods installed on the `localStorage` instance.
</issue_to_address>

### Comment 3
<location path="src-tauri/src/bridge_bootstrap.js" line_range="1135" />
<code_context>
+        if (requestedTheme === theme) return;
+        requestedTheme = theme;
+        const result = await invokeBridge(BRIDGE_COMMANDS.SET_STARTUP_THEME, { theme });
+        if (result?.ok === false && requestedTheme === theme) requestedTheme = undefined;
+      };
+
</code_context>
<issue_to_address>
**Failed saves leave startup theme stale**

When a theme-save call fails and no later theme-key mutation occurs, `invokeBridge` returns `{ ok: false }`, and `sync` clears `requestedTheme` without retrying or reporting the failure; the Dashboard gives no indication that saving failed, and the next launch uses the previous startup theme.

Retry failed saves or surface the persistence failure to the Dashboard.

Also at `src-tauri/src/bridge_bootstrap.js:1145`.
</issue_to_address>

### Comment 4
<location path="src-tauri/src/window/startup_loading.rs" line_range="12" />
<code_context>
+    let (fragment, color) = match theme {
+        StartupTheme::Light => ("#startup-theme=light", Color(244, 247, 251, 255)),
+        StartupTheme::Dark => ("#startup-theme=dark", Color(26, 26, 26, 255)),
+        StartupTheme::System => return,
+    };
+    // Pass the theme to the page before paint and cover the native background before HTML loads.
</code_context>
<issue_to_address>
**System theme can flash light**

When the saved mode is system, the OS is using dark mode, and the platform's default webview background is light, `configure_startup_theme` returns without setting `WindowConfig.background_color`, so on platforms whose native webview background defaults to light, the window shows a light blank area before the startup script applies the dark system theme.

Resolve the system color scheme before creating the window and set its native background to the matching color, or otherwise ensure the native background follows the system scheme.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and if the storage-to-theme mapping is wrong, the bridge can save an incorrect startup theme in desktop settings, so reverting the code would not undo that saved preference. The effect is limited to startup appearance and can be corrected by changing the theme preference.

Blocking findings: src-tauri/src/bridge_bootstrap.js:1134, src-tauri/src/bridge_bootstrap.js:1144, src-tauri/src/bridge_bootstrap.js:1135, src-tauri/src/window/startup_loading.rs:12


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src-tauri/src/bridge_bootstrap.js Resolved
Comment thread src-tauri/src/bridge_bootstrap.js Resolved
Comment thread src-tauri/src/bridge_bootstrap.js Resolved
Comment thread src-tauri/src/window/startup_loading.rs Resolved
@zouyonghe

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@sourcery-ai

sourcery-ai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 15b6224

#197 [Bug] 建议把黑白主题设置同步到启动页面 · 0 of 1 met · 1 to check by hand

# Requirement Status Notes
1 将黑白主题设置同步到启动页面;设置为黑色时,启动页面也应为黑色。 👀 Check by hand (runtime) 请在 Windows amd64 Release 安装包上实机确认启动页首次绘制前已应用保存的主题、不会闪出白屏;PR 说明 Windows 首屏仍待实机验证。

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src-tauri/src/bridge_bootstrap.js" line_range="1146" />
<code_context>
+              savedTheme = theme;
+            } else if (readTheme() === theme) {
+              console.warn('[astrbotDesktop] Failed to save startup theme', result.reason);
+              break;
+            }
+          }
</code_context>
<issue_to_address>
**Startup theme remains stale**

When both startup-theme IPC attempts fail while the selected theme remains unchanged, `invokeBridge` returns `{ok:false}` for command failures, and `sync` retries only once before breaking. The persisted startup theme stays stale, so the next launch uses the old theme.

Schedule further retries until the startup theme is saved successfully.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and a theme-sync bug could persist the wrong startup preference in desktop settings, and reverting the code would not remove that saved value. The impact is limited to the startup appearance and can be corrected by changing the preference.

Blocking findings: src-tauri/src/bridge_bootstrap.js:1146


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src-tauri/src/bridge_bootstrap.js Resolved
@zouyonghe

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src-tauri/src/app_runtime.rs" line_range="250" />
<code_context>
+      removeItem(key) { this.values.delete(String(key)); },
+      clear() { this.values.clear(); },
+    });
+  }
+  const makeStorage = (values) => sharedState.nativeStorage
+    ? (sharedState.allowStorageOverrides
</code_context>
<issue_to_address>
**Backend startup stalls after page-load failure**

When the initial main-window document fails to load without emitting `PageLoadEvent::Finished`, `startup_task::spawn_startup_task` runs only from the main webview’s `Finished` handler, so a startup document that fails before that event leaves the backend unstarted and the initially hidden window never shown.

Start the backend independently of page-load completion, or add a load-failure fallback that starts it and presents an error.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and the bridge persists the theme inferred from Dashboard storage in desktop settings, so a bad sync can leave the wrong startup appearance across restarts and survive a code revert. It is a bounded preference that can be corrected by choosing another theme; no irreversible data or access change is introduced.

Blocking findings: src-tauri/src/app_runtime.rs:250


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src-tauri/src/app_runtime.rs Resolved
@zouyonghe

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src-tauri/src/bridge_bootstrap.js" line_range="1133-1148" />
<code_context>
+        return 'system';
+      };
+      const sync = async () => {
+        if (saving) return;
+        saving = true;
+        const initialRetryDelay = 1_000;
+        let retryDelay = initialRetryDelay;
+        try {
+          // Read the latest choice after each write so changes during IPC are coalesced.
+          for (let theme = readTheme(); theme !== savedTheme; theme = readTheme()) {
+            const result = await invokeBridge(BRIDGE_COMMANDS.SET_STARTUP_THEME, { theme });
+            if (result?.ok !== false) {
+              savedTheme = theme;
+              retryDelay = initialRetryDelay;
+            } else if (readTheme() === theme) {
+              if (retryDelay === initialRetryDelay) {
+                console.warn('[astrbotDesktop] Retrying startup theme save', result.reason);
+              }
+              await new Promise((resolve) => window.setTimeout(resolve, retryDelay));
+              retryDelay = Math.min(retryDelay * 2, 30_000);
+            }
</code_context>
<issue_to_address>
**Theme changes wait through retry backoff**

When a save fails and the user changes the Dashboard theme while a retry delay is pending, `sync` returns because `saving` is still true, while the existing retry timer remains pending; the latest choice is not sent until that backoff expires, leaving the saved startup theme stale for up to 30 seconds.

Make a theme change interrupt or reschedule the pending retry so the latest preference is saved promptly.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and if the Dashboard theme is read or mapped incorrectly, the desktop settings file can retain the wrong startup theme, so reverting the code would not undo that saved preference. The effect is bounded to startup appearance and can be corrected by changing the theme again.

Blocking findings: src-tauri/src/bridge_bootstrap.js:1148


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src-tauri/src/bridge_bootstrap.js Resolved
@zouyonghe

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="scripts/prepare-resources/bridge-bootstrap-updater-contract.test.mjs" line_range="52" />
<code_context>
+  }
+  const makeStorage = (values) => sharedState.nativeStorage
+    ? (sharedState.allowStorageOverrides
+      ? Object.assign(new Storage(), { values })
+      : Object.preventExtensions(Object.assign(new Storage(), { values })))
+    : createStorage(values);
</code_context>
<issue_to_address>
**Own storage methods remain untested**

When `allowStorageOverrides` is true, the `bridge saves theme changes with own storage methods` case still creates a storage object with only a `values` own property; its methods remain on `Storage.prototype`. A bridge that fails to wrap own storage methods therefore passes both variants.

Assign own `setItem`, `removeItem`, and `clear` methods in that branch so the test exercises the own-method path.
</issue_to_address>

### Comment 2
<location path="scripts/prepare-resources/startup-shell-copy.test.mjs" line_range="18" />
<code_context>
+  for (const [hash, prefersDark, expected] of [
+    ['#startup-theme=dark', false, 'dark'],
+    ['#startup-theme=light', true, 'light'],
+    ['#startup-theme=unknown', true, 'dark'],
+    ['', false, 'light'],
+  ]) {
</code_context>
<issue_to_address>
**Unknown themes pass as dark**

When the hash is unknown and the system prefers light, the `startup shell applies an explicit theme before styles and follows system without a preference` test uses a dark system preference for its unknown-hash row, so an implementation that hard-codes dark for unknown hashes passes that assertion despite not following a light system preference.

Use a light system preference for the unknown-hash case, or test the unknown hash under both system preferences.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and if theme detection or persistence is wrong, the desktop can save an incorrect startup theme that remains after this code is reverted. It is a bounded preference and can be corrected by changing the Dashboard theme; the startup timing or display issues are also reversible through a normal fix.

Blocking findings: scripts/prepare-resources/bridge-bootstrap-updater-contract.test.mjs:52, scripts/prepare-resources/startup-shell-copy.test.mjs:18


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

@zouyonghe

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src-tauri/src/ui_dispatch.rs" line_range="47-55" />
<code_context>
+        tauri::async_runtime::spawn_blocking(move || {
+            // Wait briefly for the themed page to avoid a flash, then recover if it never loads.
+            let startup_page_loaded = startup_page.recv_timeout(Duration::from_secs(2)).is_ok();
+            if !startup_page_loaded {
+                append_startup_log(
+                    "startup page did not finish loading; continuing backend startup",
+                );
+            }
+
+            if let Err(error) = crate::ui_dispatch::run_on_main_thread_dispatch(
</code_context>
<issue_to_address>
**Repair option disappears on fallback**

When the startup page has not finished loading when a packaged-resource or stale-WebUI error occurs, `show_startup_error` displays only a message dialog and returns before checking whether the error is repairable. For packaged-resource or stale-WebUI failures, users therefore get no repair-install action when the startup page did not finish loading.

Provide a repair-install action in the fallback error flow, or otherwise ensure repairable errors can reach the startup-shell repair action.
</issue_to_address>

### Comment 2
<location path="src-tauri/src/app_runtime.rs" line_range="288" />
<code_context>
-        startup_task::spawn_startup_task(app_handle.clone(), append_startup_log);
+        tauri::async_runtime::spawn_blocking(move || {
+            // Wait briefly for the themed page to avoid a flash, then recover if it never loads.
+            let startup_page_loaded = startup_page.recv_timeout(Duration::from_secs(2)).is_ok();
+            if !startup_page_loaded {
+                append_startup_log(
</code_context>
<issue_to_address>
**Late startup pages stay unusable**

When the local startup page takes longer than two seconds to load, `startup_page_loaded` remains false after `recv_timeout`, so setup exposes a blank themed background; if the page then loads before the backend result, `spawn_startup_task` still uses direct navigation, leaving the startup page in browser history and routing failures to a native dialog instead of the themed error and repair UI.

Avoid exposing a blank page during timeout recovery and preserve late load completion when choosing startup navigation.

Also at `src-tauri/src/app_runtime.rs:250`, `src-tauri/src/app_runtime.rs:289`, `src-tauri/src/startup_task.rs:28-32`.
</issue_to_address>

### Comment 3
<location path="src-tauri/src/bridge_bootstrap.js" line_range="1148" />
<code_context>
+          }
+          // Read the latest choice after each write so changes during IPC are coalesced.
+          for (let theme = latestTheme; theme !== savedTheme; theme = readTheme()) {
+            const result = await invokeBridge(BRIDGE_COMMANDS.SET_STARTUP_THEME, { theme });
+            if (result?.ok !== false) {
+              savedTheme = theme;
</code_context>
<issue_to_address>
**Older theme save overwrites newer choice**

When a Dashboard reload overlaps a pending save and the older command acquires the settings lock after the newer command, an older Dashboard context can have a theme-save command still in flight while a reloaded context saves the current choice. If the newer command persists first and the older one persists afterward, the settings file records the stale theme, so the next desktop launch uses the wrong theme.

Associate saves with a monotonic revision and reject stale revisions when persisting, or otherwise ensure an older context cannot overwrite the latest stored choice.

Also at `src-tauri/src/bridge/commands.rs:559-560`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and if the theme sync saves the wrong choice, it persists as startupTheme in desktop settings, and reverting this code will not restore the prior preference. The setting is bounded and can be corrected by choosing another theme.

Blocking findings: src-tauri/src/ui_dispatch.rs:55, src-tauri/src/app_runtime.rs:288, src-tauri/src/bridge_bootstrap.js:1148


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src-tauri/src/ui_dispatch.rs Resolved
Comment thread src-tauri/src/app_runtime.rs Resolved
Comment thread src-tauri/src/bridge_bootstrap.js Resolved
@zouyonghe

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="scripts/prepare-resources/bridge-bootstrap-updater-contract.test.mjs" line_range="133" />
<code_context>
       .replace('{CHAT_TRANSPORT_MODE_STORAGE_KEY}', 'chat_transport_mode')
-      .replace('{CHAT_TRANSPORT_MODE_WEBSOCKET}', 'websocket'),
+      .replace('{CHAT_TRANSPORT_MODE_WEBSOCKET}', 'websocket')
+      .replace('{STARTUP_THEME_REVISION}', String(sharedState.themeRevision ?? 1)),
     {
       window,
</code_context>
<issue_to_address>
**Revision injection regression goes unnoticed**

When rust’s bridge injection stops replacing `{STARTUP_THEME_REVISION}`, `runBootstrap` replaces the revision placeholder itself, so the assertion passes even if Rust’s bridge injection stops supplying the native revision; the real request then carries an invalid revision and stale-write protection fails.

Test the revision substitution performed by Rust, or separately assert the bootstrap receives the production-injected script.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and the Dashboard’s theme choice is now written to desktop settings, so a wrong choice can remain after reverting this change; it is bounded and can be corrected by changing the preference. Startup navigation or visibility bugs would affect normal use and can be fixed by reverting.

Blocking findings: scripts/prepare-resources/bridge-bootstrap-updater-contract.test.mjs:133


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

.replace('{CHAT_TRANSPORT_MODE_STORAGE_KEY}', 'chat_transport_mode')
.replace('{CHAT_TRANSPORT_MODE_WEBSOCKET}', 'websocket'),
.replace('{CHAT_TRANSPORT_MODE_WEBSOCKET}', 'websocket')
.replace('{STARTUP_THEME_REVISION}', String(sharedState.themeRevision ?? 1)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Revision injection regression goes unnoticed

When rust’s bridge injection stops replacing {STARTUP_THEME_REVISION}, runBootstrap replaces the revision placeholder itself, so the assertion passes even if Rust’s bridge injection stops supplying the native revision; the real request then carries an invalid revision and stale-write protection fails.

Test the revision substitution performed by Rust, or separately assert the bootstrap receives the production-injected script.

Prompt for AI agents
In `scripts/prepare-resources/bridge-bootstrap-updater-contract.test.mjs` at line 133:

**Revision injection regression goes unnoticed**

When rust’s bridge injection stops replacing `{STARTUP_THEME_REVISION}`, `runBootstrap` replaces the revision placeholder itself, so the assertion passes even if Rust’s bridge injection stops supplying the native revision; the real request then carries an invalid revision and stale-write protection fails.

Test the revision substitution performed by Rust, or separately assert the bootstrap receives the production-injected script.

@zouyonghe

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src-tauri/src/app_runtime.rs" line_range="219-225" />
<code_context>

     if action == app_runtime_events::PageLoadAction::InjectDesktopBridge {
+        if webview.label() == "main" {
+            // A canceled startup load can report Finished with the Dashboard URL before commit.
+            webview
+                .app_handle()
+                .state::<Mutex<startup_task::StartupPage>>()
+                .lock()
+                .unwrap()
+                .dashboard_committed();
+        }
         crate::inject_desktop_bridge(webview);
</code_context>
<issue_to_address>
**Canceled navigation corrupts startup state**

When a main-window Dashboard navigation is canceled before commit, leaving the old document active, and still reports Finished with the Dashboard URL, `handle_page_load_started` calls `StartupPage::dashboard_committed` and advances the revision at navigation start. The later URL-based `finish(true)` can reveal an uncommitted page, while the old document’s sync closure keeps a stale revision and its saves are discarded; users see a blank page and theme changes are not persisted.

Defer the committed-page and revision transitions until the Dashboard document actually commits, so a canceled navigation leaves the active document’s state and revision unchanged.

Also at `src-tauri/src/app_runtime.rs:204-209`, `src-tauri/src/bridge_bootstrap.js:1116-1117`, `src-tauri/src/bridge/desktop.rs:33-38`.
</issue_to_address>

### Comment 2
<location path="src-tauri/src/app_runtime.rs" line_range="278" />
<code_context>
+                    .state::<Mutex<startup_task::StartupPage>>()
+                    .lock()
+                    .unwrap()
+                    .finish(is_dashboard);
+                if show && !backend.is_quitting() {
+                    let settings = app.state::<DesktopSettingsCache>().get();
</code_context>
<issue_to_address>
**Stalled Dashboard stays hidden**

When the backend reports ready but the Dashboard navigation never finishes, `StartupPage::finish` keeps the window hidden while waiting for the Dashboard to finish loading. After `navigate_main_window_to_backend` returns, no timeout or load-failure path reveals the window, so a Dashboard request that stalls leaves the desktop app inaccessible.

Add a bounded recovery path for Dashboard navigation that displays a usable startup error or fallback page if loading does not finish.

Also at `src-tauri/src/startup_task.rs:82-84`.
</issue_to_address>

### Comment 3
<location path="src-tauri/src/window/startup_loading.rs" line_range="8-14" />
<code_context>
-use crate::{startup_mode, BackendState};
+use crate::{desktop_settings::StartupTheme, startup_mode, BackendState};
+
+pub(crate) fn configure_startup_theme(config: &mut WindowConfig, theme: StartupTheme) {
+    let (fragment, native_theme) = match theme {
+        StartupTheme::Light => ("#startup-theme=light", Theme::Light),
+        StartupTheme::Dark => ("#startup-theme=dark", Theme::Dark),
+        StartupTheme::System => return,
+    };
+    // Pass the theme to the page before paint and cover the native background before HTML loads.
+    config.url = WebviewUrl::App(fragment.into());
+    config.background_color = Some(startup_background(native_theme));
</code_context>
<issue_to_address>
**Development server gets bypassed**

When a developer runs the app with a saved Light or Dark preference, `configure_startup_theme` replaces the configured main-window URL with `WebviewUrl::App` whenever an explicit theme is saved. In development, that redirects startup away from the configured dev server, so developers see the packaged frontend or a missing local page instead of their live UI.

Preserve the configured development URL when adding the startup-theme fragment, and use the app URL only for packaged startup.
</issue_to_address>

### Comment 4
<location path="src-tauri/src/bridge_bootstrap.js" line_range="1166-1167" />
<code_context>
+              return;
+            }
+          }
+        } catch (error) {
+          console.warn('[astrbotDesktop] Failed to read Dashboard theme', error);
+        } finally {
+          saving = false;
</code_context>
<issue_to_address>
**Theme sync stops after storage read errors**

When a localStorage read throws transiently while the Dashboard is open and no subsequent watched theme mutation occurs, `sync` catches the `readTheme` error, logs it, and schedules no retry; the chosen theme is not persisted unless another watched storage mutation triggers `sync` again.

Schedule a bounded retry when reading the theme fails, or retry when storage becomes available.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and a theme choice is persisted in desktop settings, so reverting the code would not remove that stored value; it is bounded and can be corrected by choosing another theme. A defect in the startup-page wait or window visibility behavior would be fixed by reverting the change.

Blocking findings: src-tauri/src/app_runtime.rs:225, src-tauri/src/app_runtime.rs:278, src-tauri/src/window/startup_loading.rs:14, src-tauri/src/bridge_bootstrap.js:1167


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src-tauri/src/app_runtime.rs Outdated
Comment on lines +219 to +225
// A canceled startup load can report Finished with the Dashboard URL before commit.
webview
.app_handle()
.state::<Mutex<startup_task::StartupPage>>()
.lock()
.unwrap()
.dashboard_committed();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Canceled navigation corrupts startup state

When a main-window Dashboard navigation is canceled before commit, leaving the old document active, and still reports Finished with the Dashboard URL, handle_page_load_started calls StartupPage::dashboard_committed and advances the revision at navigation start. The later URL-based finish(true) can reveal an uncommitted page, while the old document’s sync closure keeps a stale revision and its saves are discarded; users see a blank page and theme changes are not persisted.

Defer the committed-page and revision transitions until the Dashboard document actually commits, so a canceled navigation leaves the active document’s state and revision unchanged.

Also at src-tauri/src/app_runtime.rs:204-209, src-tauri/src/bridge_bootstrap.js:1116-1117, src-tauri/src/bridge/desktop.rs:33-38.

Prompt for AI agents
In `src-tauri/src/app_runtime.rs` at lines 219-225:

**Canceled navigation corrupts startup state**

When a main-window Dashboard navigation is canceled before commit, leaving the old document active, and still reports Finished with the Dashboard URL, `handle_page_load_started` calls `StartupPage::dashboard_committed` and advances the revision at navigation start. The later URL-based `finish(true)` can reveal an uncommitted page, while the old document’s sync closure keeps a stale revision and its saves are discarded; users see a blank page and theme changes are not persisted.

Defer the committed-page and revision transitions until the Dashboard document actually commits, so a canceled navigation leaves the active document’s state and revision unchanged.

Also at `src-tauri/src/app_runtime.rs:204-209`, `src-tauri/src/bridge_bootstrap.js:1116-1117`, `src-tauri/src/bridge/desktop.rs:33-38`.

Comment thread src-tauri/src/app_runtime.rs Resolved
Comment thread src-tauri/src/window/startup_loading.rs Resolved
Comment thread src-tauri/src/bridge_bootstrap.js Resolved
@zouyonghe

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src-tauri/src/startup_task.rs" line_range="132-138" />
<code_context>
-            }
+                let page = app.state::<Mutex<StartupPage>>();
+                let result = startup_result.and_then(|cache_version| {
+                    let completion = page.lock().unwrap().begin_dashboard_fallback();
+                    navigate_main_window_to_backend(
+                        app,
+                        cache_version.as_deref(),
+                        completion.is_none(),
+                    )?;
+                    if let Some(completion) = completion {
+                        watch_dashboard_load(app.clone(), completion, log);
+                    }
</code_context>
<issue_to_address>
**Dashboard load can hang indefinitely**

When the startup shell finishes loading but the subsequent Dashboard navigation never finishes, `begin_dashboard_fallback()` returns `None` after the startup shell has loaded, so `watch_dashboard_load()` is never started on the normal startup path. If navigation to the Dashboard then stalls, no timeout reports the failure and the user is left waiting indefinitely.

Start the Dashboard load timeout for both the normal navigation path and the direct-navigation fallback.
</issue_to_address>

### Comment 2
<location path="src-tauri/src/startup_task.rs" line_range="38-40" />
<code_context>
+        match self {
+            Self::Waiting => {}
+            Self::WaitingForDashboard {
+                committed: true,
+                finished,
+            } if is_dashboard => {
+                let _ = finished.try_send(());
+            }
</code_context>
<issue_to_address>
**Stale load reveals window early**

When a Dashboard navigation is superseded after its `Started` event and its delayed `Finished` event arrives after the replacement navigation starts but before it finishes, a late `Finished` event from an earlier Dashboard navigation satisfies the shared `committed` flag, so `StartupPage::finish` marks the startup page loaded and reveals the window while a newer Dashboard navigation is still loading.

Associate the committed/finished state with a navigation generation or URL and only finish the startup page for the currently active Dashboard navigation.
</issue_to_address>

### Comment 3
<location path="src-tauri/src/app_runtime.rs" line_range="205-209" />
<code_context>
 fn handle_page_load_started(webview: &tauri::Webview<tauri::Wry>, payload: &PageLoadPayload<'_>) {
     append_desktop_log(&format!("page-load started: {}", payload.url()));
+    // Wry emits Started on commit (GTK/macOS) or ContentLoading (WebView2).
+    if webview.label() == "main" {
+        webview
+            .app_handle()
+            .state::<bridge::desktop::StartupThemeWrites>()
+            .advance();
+    }
     let state = webview.app_handle().state::<BackendState>();
</code_context>
<issue_to_address>
**Canceled navigation blocks theme saves**

When a main-window Dashboard navigation starts on WebView2 and is canceled before replacing the current document, the old Dashboard keeps its theme-sync closure with the previous revision, while `StartupThemeWrites::save_current` silently skips requests carrying that revision and returns success. The closure then marks the theme saved, so the preference is lost on the next restart.

Advance the write revision only for a committed document, or update the active document’s sync closure to use the new revision when a navigation is canceled.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and the Dashboard now persists startup-theme choices, so an incorrect preference can remain in desktop settings after this change is reverted, though it is bounded and can be changed again. The startup-loading changes could also cause a launch or visibility regression, but reverting would restore the previous startup flow.

Blocking findings: src-tauri/src/startup_task.rs:138, src-tauri/src/startup_task.rs:40, src-tauri/src/app_runtime.rs:209


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src-tauri/src/startup_task.rs Resolved
Comment thread src-tauri/src/startup_task.rs Outdated
Comment on lines +38 to +40
committed: true,
finished,
} if is_dashboard => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Stale load reveals window early

When a Dashboard navigation is superseded after its Started event and its delayed Finished event arrives after the replacement navigation starts but before it finishes, a late Finished event from an earlier Dashboard navigation satisfies the shared committed flag, so StartupPage::finish marks the startup page loaded and reveals the window while a newer Dashboard navigation is still loading.

Associate the committed/finished state with a navigation generation or URL and only finish the startup page for the currently active Dashboard navigation.

Prompt for AI agents
In `src-tauri/src/startup_task.rs` at lines 38-40:

**Stale load reveals window early**

When a Dashboard navigation is superseded after its `Started` event and its delayed `Finished` event arrives after the replacement navigation starts but before it finishes, a late `Finished` event from an earlier Dashboard navigation satisfies the shared `committed` flag, so `StartupPage::finish` marks the startup page loaded and reveals the window while a newer Dashboard navigation is still loading.

Associate the committed/finished state with a navigation generation or URL and only finish the startup page for the currently active Dashboard navigation.

Comment on lines +205 to +209
if webview.label() == "main" {
webview
.app_handle()
.state::<bridge::desktop::StartupThemeWrites>()
.advance();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Canceled navigation blocks theme saves

When a main-window Dashboard navigation starts on WebView2 and is canceled before replacing the current document, the old Dashboard keeps its theme-sync closure with the previous revision, while StartupThemeWrites::save_current silently skips requests carrying that revision and returns success. The closure then marks the theme saved, so the preference is lost on the next restart.

Advance the write revision only for a committed document, or update the active document’s sync closure to use the new revision when a navigation is canceled.

Prompt for AI agents
In `src-tauri/src/app_runtime.rs` at lines 205-209:

**Canceled navigation blocks theme saves**

When a main-window Dashboard navigation starts on WebView2 and is canceled before replacing the current document, the old Dashboard keeps its theme-sync closure with the previous revision, while `StartupThemeWrites::save_current` silently skips requests carrying that revision and returns success. The closure then marks the theme saved, so the preference is lost on the next restart.

Advance the write revision only for a committed document, or update the active document’s sync closure to use the new revision when a navigation is canceled.

@zouyonghe

Copy link
Copy Markdown
Member Author

@sourcery-ai review

@zouyonghe
zouyonghe merged commit 0264b50 into AstrBotDevs:main Nov 24, 2026
4 checks passed

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src-tauri/src/bridge/commands.rs" line_range="580" />
<code_context>
+    app.state::<crate::bridge::desktop::StartupThemeWrites>()
+        .save_current(revision, || {
+            settings.update(|_| {
+                desktop_settings::write_startup_theme(packaged_root_dir.as_deref(), theme)
+            })
+        })
</code_context>
<issue_to_address>
**Theme saves freeze the UI**

When a theme sync or preference change needs to persist settings while the state filesystem is slow or stalled, the synchronous command performs the settings read and persistence inline, including `sync_all`, so a slow or stalled settings filesystem blocks the Dashboard’s UI thread until the operation completes.

Run the filesystem read-modify-write on a blocking worker rather than in the synchronous command handler.

Also at `src-tauri/src/desktop_settings.rs:336-351`.
</issue_to_address>

### Comment 2
<location path="src-tauri/src/startup_task.rs" line_range="104" />
<code_context>
+                    ui_dispatch::show_startup_error(
+                    app,
+                    "The Dashboard did not finish loading. Restart AstrBot to try again.\n管理面板加载超时,请重启 AstrBot 后重试。",
+                    false,
+                    log,
+                );
</code_context>
<issue_to_address>
**Recovered Dashboard still shows restart error**

When the Dashboard finishes loading after the timeout dialog appears, `StartupPage` remains `WaitingForDashboard`, so `dashboard_loaded` accepts the same revision, changes the state to `Loaded`, and shows the main window while the restart error remains visible.

Move the startup page out of `WaitingForDashboard` when the timeout fires so a late load for that revision is ignored.
</issue_to_address>

### Comment 3
<location path="src-tauri/src/startup_task.rs" line_range="101-104" />
<code_context>
+                    StartupPage::WaitingForDashboard { .. }
+                ) && !app.state::<BackendState>().is_quitting()
+                {
+                    ui_dispatch::show_startup_error(
+                    app,
+                    "The Dashboard did not finish loading. Restart AstrBot to try again.\n管理面板加载超时,请重启 AstrBot 后重试。",
+                    false,
+                    log,
+                );
</code_context>
<issue_to_address>
**Reload triggers stale timeout**

When the Dashboard reloads during startup and the original load’s 10-second timeout expires before the reloaded document finishes, `watch_dashboard_load` keeps the original navigation’s timeout receiver, and the `WaitingForDashboard` check does not distinguish a reloaded document from the one whose timer expired. The timeout therefore displays a restart error while the newer Dashboard is still loading.

Reset or replace the Dashboard-load timeout for each document revision, and only report a timeout if the revision it was created for is still current.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and a theme-sync bug could save the wrong startup theme in desktop settings, so that preference can remain after a revert, but it is bounded and can be corrected by changing the theme. The new startup-load coordination could also delay or hide the window if faulty; reverting restores the previous startup flow.

Blocking findings: src-tauri/src/bridge/commands.rs:580, src-tauri/src/startup_task.rs:104, src-tauri/src/startup_task.rs:104


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

app.state::<crate::bridge::desktop::StartupThemeWrites>()
.save_current(revision, || {
settings.update(|_| {
desktop_settings::write_startup_theme(packaged_root_dir.as_deref(), theme)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Theme saves freeze the UI

When a theme sync or preference change needs to persist settings while the state filesystem is slow or stalled, the synchronous command performs the settings read and persistence inline, including sync_all, so a slow or stalled settings filesystem blocks the Dashboard’s UI thread until the operation completes.

Run the filesystem read-modify-write on a blocking worker rather than in the synchronous command handler.

Also at src-tauri/src/desktop_settings.rs:336-351.

Prompt for AI agents
In `src-tauri/src/bridge/commands.rs` at line 580:

**Theme saves freeze the UI**

When a theme sync or preference change needs to persist settings while the state filesystem is slow or stalled, the synchronous command performs the settings read and persistence inline, including `sync_all`, so a slow or stalled settings filesystem blocks the Dashboard’s UI thread until the operation completes.

Run the filesystem read-modify-write on a blocking worker rather than in the synchronous command handler.

Also at `src-tauri/src/desktop_settings.rs:336-351`.

ui_dispatch::show_startup_error(
app,
"The Dashboard did not finish loading. Restart AstrBot to try again.\n管理面板加载超时,请重启 AstrBot 后重试。",
false,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Recovered Dashboard still shows restart error

When the Dashboard finishes loading after the timeout dialog appears, StartupPage remains WaitingForDashboard, so dashboard_loaded accepts the same revision, changes the state to Loaded, and shows the main window while the restart error remains visible.

Move the startup page out of WaitingForDashboard when the timeout fires so a late load for that revision is ignored.

Prompt for AI agents
In `src-tauri/src/startup_task.rs` at line 104:

**Recovered Dashboard still shows restart error**

When the Dashboard finishes loading after the timeout dialog appears, `StartupPage` remains `WaitingForDashboard`, so `dashboard_loaded` accepts the same revision, changes the state to `Loaded`, and shows the main window while the restart error remains visible.

Move the startup page out of `WaitingForDashboard` when the timeout fires so a late load for that revision is ignored.

Comment on lines +101 to +104
ui_dispatch::show_startup_error(
app,
"The Dashboard did not finish loading. Restart AstrBot to try again.\n管理面板加载超时,请重启 AstrBot 后重试。",
false,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Reload triggers stale timeout

When the Dashboard reloads during startup and the original load’s 10-second timeout expires before the reloaded document finishes, watch_dashboard_load keeps the original navigation’s timeout receiver, and the WaitingForDashboard check does not distinguish a reloaded document from the one whose timer expired. The timeout therefore displays a restart error while the newer Dashboard is still loading.

Reset or replace the Dashboard-load timeout for each document revision, and only report a timeout if the revision it was created for is still current.

Prompt for AI agents
In `src-tauri/src/startup_task.rs` at lines 101-104:

**Reload triggers stale timeout**

When the Dashboard reloads during startup and the original load’s 10-second timeout expires before the reloaded document finishes, `watch_dashboard_load` keeps the original navigation’s timeout receiver, and the `WaitingForDashboard` check does not distinguish a reloaded document from the one whose timer expired. The timeout therefore displays a restart error while the newer Dashboard is still loading.

Reset or replace the Dashboard-load timeout for each document revision, and only report a timeout if the revision it was created for is still current.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] 建议把黑白主题设置同步到启动页面

1 participant