Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions astrbot/dashboard/services/update_service.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import asyncio
import os
import traceback
import uuid
from collections.abc import Awaitable, Callable
Expand Down Expand Up @@ -174,6 +175,20 @@ async def _run_update_project(
reboot: Whether to restart AstrBot after applying files.
proxy: Optional GitHub proxy URL.
"""
if os.environ.get("ASTRBOT_CLI") == "1":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium · CLI installs show generic update errors

When ASTRBOT_CLI is truthy but not exactly "1", or ASTRBOT_LAUNCHER is set, the CLI check skips the guidance branch, then the updater rejects the installation and the exception handler reports a generic update failure instead of package-manager instructions.

Use the updater’s CLI-managed installation conditions for the guidance check, including truthy ASTRBOT_CLI values and a set ASTRBOT_LAUNCHER.

Prompt for AI agents
In `astrbot/dashboard/services/update_service.py` at line 183:

**CLI installs show generic update errors**

When `ASTRBOT_CLI` is truthy but not exactly `"1"`, or `ASTRBOT_LAUNCHER` is set, the CLI check skips the guidance branch, then the updater rejects the installation and the exception handler reports a generic update failure instead of package-manager instructions.

Use the updater’s CLI-managed installation conditions for the guidance check, including truthy `ASTRBOT_CLI` values and a set `ASTRBOT_LAUNCHER`.

self.update_progress[progress_id].update(
status="error",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium · Older polls overwrite terminal guidance

When an older running poll returns after a newer poll has returned the terminal CLI error, applyUpdateProgress replaces the terminal error with the older running response after polling has stopped, so the panel remains stuck on a nonterminal message instead of showing upgrade instructions.

Prevent an older running response from replacing a terminal update state.

Prompt for AI agents
In `astrbot/dashboard/services/update_service.py` at line 185:

**Older polls overwrite terminal guidance**

When an older running poll returns after a newer poll has returned the terminal CLI error, `applyUpdateProgress` replaces the terminal error with the older running response after polling has stopped, so the panel remains stuck on a nonterminal message instead of showing upgrade instructions.

Prevent an older running response from replacing a terminal update state.

error_code="cli_update_required",
message=(
"AstrBot was started via the CLI and cannot be updated from the WebUI. "
"For a uv tool install, run uv tool upgrade astrbot. For a pip install, "
"run python -m pip install --upgrade astrbot in the original Python "
"environment. Then restart AstrBot. "
"Upgrade guide: https://docs.astrbot.app/en/deploy/update#package"
),
)
return

try:

async def observe_update(event: UpdateProgress) -> None:
Expand Down
4 changes: 3 additions & 1 deletion dashboard/src/i18n/locales/en-US/core/header.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@
"successReady": "Update successful",
"autoReloadIn": "Refreshing automatically in {seconds}s",
"reloadNow": "Refresh now",
"failed": "Update failed"
"failed": "Update failed",
"cliUpdateRequired": "AstrBot was started via the CLI and cannot be updated from the WebUI. For a uv tool install, run uv tool upgrade astrbot. For a pip install, run python -m pip install --upgrade astrbot in the original Python environment. Then restart AstrBot.",
"cliUpdateGuide": "Read the AstrBot upgrade guide"
},
"redirectConfirm": {
"title": "Leaving AstrBot",
Expand Down
4 changes: 3 additions & 1 deletion dashboard/src/i18n/locales/ja-JP/core/header.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@
"successReady": "更新に成功しました",
"autoReloadIn": "{seconds} 秒後にページを自動的に再読み込みします",
"reloadNow": "今すぐ再読み込み",
"failed": "更新に失敗しました"
"failed": "更新に失敗しました",
"cliUpdateRequired": "CLI から起動した AstrBot は WebUI では更新できません。uv tool でインストールした場合は uv tool upgrade astrbot を、pip の場合はインストール時の Python 環境で python -m pip install --upgrade astrbot を実行してください。更新後に AstrBot を再起動してください。",
"cliUpdateGuide": "AstrBot のアップグレードガイドを読む"
},
"redirectConfirm": {
"title": "公式アップデートガイドを開く",
Expand Down
4 changes: 3 additions & 1 deletion dashboard/src/i18n/locales/ru-RU/core/header.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@
"successReady": "Обновление успешно",
"autoReloadIn": "Автоматическое обновление через {seconds} с",
"reloadNow": "Обновить сейчас",
"failed": "Ошибка обновления"
"failed": "Ошибка обновления",
"cliUpdateRequired": "AstrBot запущен через CLI, поэтому обновление из WebUI недоступно. Если вы установили AstrBot через uv tool, выполните uv tool upgrade astrbot. При установке через pip выполните python -m pip install --upgrade astrbot в исходном окружении Python. Затем перезапустите AstrBot.",
"cliUpdateGuide": "Руководство по обновлению AstrBot"
},
"redirectConfirm": {
"title": "Переход по ссылке",
Expand Down
4 changes: 3 additions & 1 deletion dashboard/src/i18n/locales/zh-CN/core/header.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@
"successReady": "更新成功",
"autoReloadIn": "{seconds} 秒后自动刷新",
"reloadNow": "立即刷新",
"failed": "更新失败"
"failed": "更新失败",
"cliUpdateRequired": "通过 CLI 启动的 AstrBot 不能在 WebUI 中升级。请在终端使用原来的安装方式升级:uv tool 安装请运行 uv tool upgrade astrbot;pip 安装请在原 Python 环境中运行 python -m pip install --upgrade astrbot。升级后请重启 AstrBot。",
"cliUpdateGuide": "查看 AstrBot 更新指南"
},
"redirectConfirm": {
"title": "即将跳转",
Expand Down
46 changes: 22 additions & 24 deletions dashboard/src/layouts/full/vertical-header/VerticalHeader.vue
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type { Locale } from "@/i18n/types";
import AboutPage from "@/views/AboutPage.vue";
import { authApi, isLegacyFallbackError, statsApi, updatesApi } from "@/api/v1";
import { getDesktopRuntimeInfo } from "@/utils/desktopRuntime";
import { getUpdateProgressMessage } from "@/utils/updateProgressMessage";

enableKatex();
enableMermaid();
Expand Down Expand Up @@ -97,6 +98,7 @@ type UpdateProgress = {
stage: string;
version: string;
message: string;
error_code?: string;
overall_percent: number;
stages: Record<string, DownloadStage>;
};
Expand Down Expand Up @@ -234,30 +236,9 @@ const updateStageItems = computed(() => [
progress: updateProgress.value.stages.core || createEmptyDownloadStage(),
},
]);
const updateProgressMessage = computed(() => {
if (updateProgress.value.status === "error") {
return (
updateProgress.value.message ||
t("core.header.updateDialog.progress.failed")
);
}
if (updateProgress.value.status === "success") {
return (
updateProgress.value.message ||
t("core.header.updateDialog.progress.completed")
);
}
if (updateProgress.value.stage === "dependencies") {
return t("core.header.updateDialog.progress.dependencies");
}
if (updateProgress.value.stage === "restart") {
return t("core.header.updateDialog.progress.restart");
}
return (
updateProgress.value.message ||
t("core.header.updateDialog.progress.preparing")
);
});
const updateProgressMessage = computed(() =>
getUpdateProgressMessage(updateProgress.value, t),
);
// Form validation
const formValid = ref(true);
const passwordRules = computed(() => [
Expand Down Expand Up @@ -1075,6 +1056,11 @@ const languages = computed(() =>
})),
);
const currentLocale = computed(() => locale.value);
const cliUpdateGuideUrl = computed(() =>
currentLocale.value === "zh-CN"
? "https://docs.astrbot.app/deploy/update#package"
: "https://docs.astrbot.app/en/deploy/update#package",
);
const changeLanguage = async (langCode: string) => {
await switchLanguage(langCode as Locale);
mainMenuOpen.value = false;
Expand Down Expand Up @@ -1540,6 +1526,18 @@ onMounted(async () => {
<div class="text-subtitle-1 font-weight-medium">
{{ updateProgressMessage }}
</div>
<a
v-if="
updateProgress.status === 'error' &&
updateProgress.error_code === 'cli_update_required'
"
:href="cliUpdateGuideUrl"
target="_blank"
rel="noopener noreferrer"
class="text-primary"
>
{{ t("core.header.updateDialog.progress.cliUpdateGuide") }}
</a>
<div class="text-caption text-medium-emphasis">
{{ t("core.header.updateDialog.progress.target") }}
{{ updateProgress.version || "latest" }}
Expand Down
20 changes: 20 additions & 0 deletions dashboard/src/utils/updateProgressMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
type MessageFields = { status: string; stage: string; message: string; error_code?: string };

export function getUpdateProgressMessage(progress: MessageFields, t: (key: string) => string): string {
if (progress.status === "error") {
if (progress.error_code === "cli_update_required") {
return t("core.header.updateDialog.progress.cliUpdateRequired");
}
return progress.message || t("core.header.updateDialog.progress.failed");
}
if (progress.status === "success") {
return progress.message || t("core.header.updateDialog.progress.completed");
}
if (progress.stage === "dependencies") {
return t("core.header.updateDialog.progress.dependencies");
}
if (progress.stage === "restart") {
return t("core.header.updateDialog.progress.restart");
}
return progress.message || t("core.header.updateDialog.progress.preparing");
}
45 changes: 41 additions & 4 deletions tests/test_dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,22 +157,27 @@ async def _wait_for_update_progress(
test_client,
authenticated_header: dict,
progress_id: str,
*,
use_v1: bool = False,
) -> dict:
"""Wait until a dashboard update task reaches a terminal status.

Args:
test_client: Quart/FastAPI adapter test client.
authenticated_header: Headers for authenticated dashboard requests.
progress_id: Update progress id to poll.
use_v1: Poll the current WebUI endpoint instead of its legacy fallback.

Returns:
The progress response payload.
"""
path = (
f"/api/v1/updates/progress/{progress_id}"
if use_v1
else f"/api/update/progress?id={progress_id}"
)
for _ in range(100):
response = await test_client.get(
f"/api/update/progress?id={progress_id}",
headers=authenticated_header,
)
response = await test_client.get(path, headers=authenticated_header)
data = await response.get_json()
if data["data"].get("status") in {"success", "error"}:
return data
Expand Down Expand Up @@ -3219,6 +3224,38 @@ async def mock_update(*args, **kwargs):
assert calls == ["update"]


@pytest.mark.asyncio
async def test_cli_update_guidance_in_polled_progress(
app: FastAPIAppAdapter,
authenticated_header: dict,
core_lifecycle_td: AstrBotCoreLifecycle,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("ASTRBOT_CLI", "1")
update = AsyncMock(side_effect=RuntimeError("unexpected download"))
monkeypatch.setattr(core_lifecycle_td.astrbot_updater, "update", update)
client = app.test_client()
response = await client.post(
"/api/v1/updates/core",
headers=authenticated_header,
json={"version": "v4.30.2", "progress_id": "cli-progress"},
)
started = await response.get_json()
assert started["status"] == "ok"
polled = await _wait_for_update_progress(
client, authenticated_header, started["data"]["id"], use_v1=True
)
progress = polled["data"]
assert progress["status"] == "error"
assert progress.get("error_code") == "cli_update_required"
assert "uv tool upgrade astrbot" in progress["message"]
assert "python -m pip install --upgrade astrbot" in progress["message"]
assert "original Python environment" in progress["message"]
assert "https://docs.astrbot.app/en/deploy/update#package" in progress["message"]
assert progress["overall_percent"] == 0
update.assert_not_awaited()


@pytest.mark.asyncio
async def test_do_update_rejects_desktop_managed_backend(
app: FastAPIAppAdapter,
Expand Down
Loading