Skip to content

feat: sync dashboard theme to plugin pages and prevent flash on load#8377

Merged
0 commit merged into
AstrBotDevs:masterfrom
lxfight:master
May 28, 2026
Merged

feat: sync dashboard theme to plugin pages and prevent flash on load#8377
0 commit merged into
AstrBotDevs:masterfrom
lxfight:master

Conversation

@lxfight
Copy link
Copy Markdown
Member

@lxfight lxfight commented May 27, 2026

Plugin pages embedded via iframe had no awareness of the dashboard's light/dark theme state, causing two problems:

  1. Plugin UIs always rendered in light mode regardless of the dashboard theme
  2. When entering a plugin page in dark mode, there was a visible flash of light mode before the bridge SDK initialized

This PR adds an end-to-end theme sync mechanism so plugin pages automatically match the dashboard theme on load and react to live theme switching, with the initial theme applied server-side to eliminate flash.

Modifications / 改动点

  • Backend (plugin.py): Added theme query parameter propagation through the plugin page asset pipeline. The _get_plugin_page_initial_context now includes isDark. The HTML rewriter injects data-theme on and a tag server-side to prevent initial flash.

  • Bridge SDK (plugin_page_bridge.js): applyContext() now sets data-theme on document.documentElement when context includes isDark, enabling live theme switching.

  • Frontend (PluginPagePage.vue): Appends &theme=dark/light to iframe URL and includes isDark in postMessage context. Watches uiTheme to re-send context on theme toggle.

  • Store (customizer.ts): Added isDark getter.

  • Tests: Added tests for isDark in bridge SDK initial context (dark/light/absent/invalid params) and theme propagation in rewritten HTML (data-theme, color-scheme meta).

  • Docs: Added light/dark theme adaptation section to plugin-pages guide (zh + en).

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

Testing on the astrbot_plugin_livingmemory plugin showed that switching between light and dark themes using AstrBot's built-in theme switching function resulted in the Livingmemory WebUI switching themes accordingly. Furthermore, the WebUI could be switched back to the opposite theme without affecting the display of the AstrBot WebUI.

The current default behavior is to maintain the same light/dark theme as the AstrBot WebUI when entering the plugin's WebUI.


Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
    / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。

  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
    / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”

  • 🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml.
    / 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到 requirements.txtpyproject.toml 文件相应位置。

  • 😮 My changes do not introduce malicious code.
    / 我的更改没有引入恶意代码。

Summary by Sourcery

Synchronize the dashboard’s light/dark theme with plugin pages and eliminate initial theme flash for iframe-embedded plugin UIs.

New Features:

  • Propagate the dashboard light/dark theme into plugin page contexts via an isDark flag and theme query parameter so plugin pages can render with the correct theme on load.
  • Automatically apply and update a data-theme attribute on plugin page HTML and the bridge SDK to keep plugin UIs in sync with live theme changes from the dashboard.

Bug Fixes:

  • Remove a duplicated plugin response append in the plugin processing logic.

Enhancements:

  • Extend the plugin page asset rewriting pipeline to carry through theme parameters and inject a color-scheme meta tag for browser-level dark/light defaults.
  • Expose an isDark getter in the customizer store and ensure plugin iframe URLs include the current theme so the initial render matches the dashboard state.

Documentation:

  • Update English and Chinese plugin page guides to document isDark in the bridge context and describe how to adapt CSS/JS to light/dark theme changes.

Tests:

  • Add backend tests covering isDark handling in the bridge SDK script and theme propagation into rewritten HTML, including data-theme and color-scheme meta behavior.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. area:webui The bug / feature is about webui(dashboard) of astrbot. feature:plugin The bug / feature is about AstrBot plugin system. labels May 27, 2026
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces light and dark theme adaptation for AstrBot plugin pages, allowing the theme state to sync automatically. It updates the bridge SDK, backend routes, frontend views, and documentation, and adds corresponding tests. Feedback on the changes suggests using a case-insensitive regular expression to search for the <head> tag in the HTML rewriter to prevent duplicate tag injection when dealing with uppercase tags or tags with attributes.

Comment thread astrbot/dashboard/routes/plugin.py Outdated
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

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, and left some high level feedback:

  • The isDark getter in customizer.ts hardcodes PurpleThemeDark, which will break if additional dark themes are introduced; consider deriving darkness from a more generic rule (e.g., a mode field or a naming convention like endsWith('Dark')).
  • When uiTheme changes you only resend context to the iframe, but the iframe src (and theme= query param) is not updated, so server-side HTML/asset rendering remains on the original theme; consider updating iframeSrc (or reloading the iframe) on theme toggle so server-side theme hints stay in sync with the live context.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `isDark` getter in `customizer.ts` hardcodes `PurpleThemeDark`, which will break if additional dark themes are introduced; consider deriving darkness from a more generic rule (e.g., a `mode` field or a naming convention like `endsWith('Dark')`).
- When `uiTheme` changes you only resend context to the iframe, but the iframe `src` (and `theme=` query param) is not updated, so server-side HTML/asset rendering remains on the original theme; consider updating `iframeSrc` (or reloading the iframe) on theme toggle so server-side theme hints stay in sync with the live context.

## Individual Comments

### Comment 1
<location path="astrbot/dashboard/routes/plugin.py" line_range="608-609" />
<code_context>
+            color_scheme_meta = (
+                f'<meta name="color-scheme" content="{theme}">'
+            )
+            if "<head>" in rewritten_html:
+                rewritten_html = rewritten_html.replace(
+                    "<head>",
+                    f"<head>\n    {color_scheme_meta}",
</code_context>
<issue_to_address>
**issue (bug_risk):** Head-tag detection is case- and format-sensitive and can cause duplicate <head> insertion.

This plain-string `"<head>"` check will miss variants like `<head>\n`, `<head >`, or different casing, so the later `<html>` branch may inject a second `<head>` even when one already exists. Use a case‑insensitive regex such as `re.search(r"<head\b[^>]*>", rewritten_html, re.IGNORECASE)` to detect and reuse the existing `<head>` tag rather than creating a new one.
</issue_to_address>

### Comment 2
<location path="astrbot/dashboard/routes/plugin.py" line_range="280" />
<code_context>
             self._get_by_path(locale_data, f"pages.{page_name}.title") or page_name
         )

+        theme = request.args.get("theme", "").strip()
+
         return {
</code_context>
<issue_to_address>
**issue (complexity):** Consider extracting shared theme parsing and HTML mutation into dedicated helpers to keep the main route logic simpler and more maintainable.

You can reduce the added complexity by centralizing theme handling and encapsulating the HTML mutation logic.

### 1. Centralize theme parsing/validation

The `request.args.get("theme", "").strip()` + `theme in ("dark", "light")` logic now appears in multiple places. Extract it into a helper to keep the rules in one place and simplify call sites.

```python
def _get_request_theme() -> str | None:
    theme = request.args.get("theme", "").strip()
    return theme if theme in ("dark", "light") else None
```

Use it where you need `isDark`:

```python
# before
theme = request.args.get("theme", "").strip()
return {
    ...
    "i18n": plugin_i18n,
    "isDark": theme == "dark",
}

# after
theme = _get_request_theme()
return {
    ...
    "i18n": plugin_i18n,
    "isDark": theme == "dark" if theme else False,
}
```

And in `_prepare_plugin_page_query_params`:

```python
def _prepare_plugin_page_query_params(... ) -> dict[str, str] | None:
    params: dict[str, str] = {}

    asset_token = request.args.get("asset_token", "").strip()
    if not asset_token:
        asset_token = self._issue_plugin_page_asset_token(plugin_name, page_name) or ""
    if asset_token:
        params["asset_token"] = asset_token

    theme = _get_request_theme()
    if theme:
        params["theme"] = theme

    return params or None
```

### 2. Extract and simplify HTML theme application

The inline block that mutates `rewritten_html` is doing several regex/string operations with nested conditionals. Moving this into a focused helper makes the main flow easier to follow and gives you one place to reason about the behavior.

```python
def _apply_theme_to_html(html: str, theme: str) -> str:
    # add data-theme to <html ...>
    html = re.sub(
        r"(<html\b[^>]*?)>",
        rf'\1 data-theme="{theme}">',
        html,
        count=1,
        flags=re.IGNORECASE,
    )

    color_scheme_meta = f'<meta name="color-scheme" content="{theme}">'

    # ensure <head> gets the meta tag (create <head> if missing)
    if "<head>" in html:
        return html.replace(
            "<head>",
            f"<head>\n    {color_scheme_meta}",
            1,
        )

    return re.sub(
        r"(<html\b[^>]*?>)",
        rf"\1\n  <head>\n    {color_scheme_meta}\n  </head>",
        html,
        count=1,
        flags=re.IGNORECASE,
    )
```

Then the main HTML rewriting logic becomes:

```python
rewritten_html = _HTML_ASSET_ATTR_RE.sub(replace_attr, html_text)

theme = (extra_query_params or {}).get("theme") or _get_request_theme()
if theme:
    rewritten_html = _apply_theme_to_html(rewritten_html, theme)
```

This keeps the existing behavior (validated theme, `data-theme` on `<html>`, `color-scheme` meta in `<head>` or newly created `<head>`) but:

- removes duplicated theme validation logic;
- isolates all HTML/regex manipulation in one helper;
- simplifies the main function to a straightforward “if theme: apply theme”.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread astrbot/dashboard/routes/plugin.py Outdated
Comment thread astrbot/dashboard/routes/plugin.py Outdated
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 28, 2026
@lxfight lxfight closed this pull request by merging all changes into AstrBotDevs:master in e960c14 May 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:webui The bug / feature is about webui(dashboard) of astrbot. feature:plugin The bug / feature is about AstrBot plugin system. size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant