From d898998c47d39f14a2b0e238826210d9de0ac80f Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Thu, 24 Sep 2026 15:37:18 +0800 Subject: [PATCH] feat(webui): invite returning users to star nanobot (#5895) * feat(webui): invite returning users to star nanobot * fix(webui): place About Star link in settings list * fix(webui): use neutral About repository label * fix(webui): add localized Star link to About footer * fix(webui): align Star invitation with existing dialog styling * fix(webui): shorten and localize Star invitation copy * fix(webui): skip Star invitation after user interaction * fix(webui): align Star invitation meaning across locales * fix(webui): clarify Star reminder dismissal errors --- .../tests/test_websocket_http_routes.py | 30 +++++ nanobot/session/webui_turns.py | 8 ++ nanobot/webui/star_prompt.py | 69 ++++++++++ nanobot/webui/ws_http.py | 14 ++ tests/webui/test_star_prompt.py | 101 ++++++++++++++ webui/src/App.tsx | 2 + webui/src/components/StarPrompt.tsx | 125 ++++++++++++++++++ .../src/components/settings/SettingsPage.tsx | 2 + .../settings/overview/OverviewSettings.tsx | 10 +- webui/src/i18n/locales/en/common.json | 9 ++ webui/src/i18n/locales/es/common.json | 9 ++ webui/src/i18n/locales/fr/common.json | 9 ++ webui/src/i18n/locales/id/common.json | 9 ++ webui/src/i18n/locales/ja/common.json | 9 ++ webui/src/i18n/locales/ko/common.json | 9 ++ webui/src/i18n/locales/pt-BR/common.json | 9 ++ webui/src/i18n/locales/vi/common.json | 9 ++ webui/src/i18n/locales/zh-CN/common.json | 9 ++ webui/src/i18n/locales/zh-TW/common.json | 9 ++ webui/src/lib/api.ts | 7 + webui/src/tests/star-prompt.test.tsx | 112 ++++++++++++++++ 21 files changed, 567 insertions(+), 3 deletions(-) create mode 100644 nanobot/webui/star_prompt.py create mode 100644 tests/webui/test_star_prompt.py create mode 100644 webui/src/components/StarPrompt.tsx create mode 100644 webui/src/tests/star-prompt.test.tsx diff --git a/nanobot/channels/websocket/tests/test_websocket_http_routes.py b/nanobot/channels/websocket/tests/test_websocket_http_routes.py index 617ce977b..e63a4131a 100644 --- a/nanobot/channels/websocket/tests/test_websocket_http_routes.py +++ b/nanobot/channels/websocket/tests/test_websocket_http_routes.py @@ -4204,3 +4204,33 @@ def test_bootstrap_secret_also_enforced_on_localhost(bus: MagicMock) -> None: channel = _ch(bus, host="0.0.0.0", tokenIssueSecret="s3cret") resp = channel.gateway.http._handle_bootstrap(_LOCAL, _NO_HEADERS) assert resp.status_code == 401 + + +@pytest.mark.asyncio +async def test_star_prompt_requires_authenticated_mutation_and_persists_dismissal( + bus: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from nanobot.webui.star_prompt import StarPromptState + + monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path) + state_path = tmp_path / "webui" / "star-prompt.json" + state_path.parent.mkdir() + state_path.write_text(StarPromptState( + completed_replies=10, active_days=["2026-09-20", "2026-09-21", "2026-09-22"] + ).model_dump_json(), encoding="utf-8") + channel = _ch(bus, port=29912) + server_task = asyncio.create_task(channel.start()) + try: + raw = await _http_get("http://127.0.0.1:29912/api/webui/star-prompt/claim") + assert raw.status_code in {401, 405} + first = await _webui_mutate(channel, "star_prompt.claim", {}) + assert first.status_code == 200 + assert first.json() == {"show": True} + second = await _webui_mutate(channel, "star_prompt.claim", {}) + assert second.json() == {"show": False} + dismissed = await _webui_mutate(channel, "star_prompt.dismiss", {}) + assert dismissed.status_code == 200 + assert StarPromptState.model_validate_json(state_path.read_text()).dismissed_forever + finally: + await channel.stop() + await server_task diff --git a/nanobot/session/webui_turns.py b/nanobot/session/webui_turns.py index 67b872fef..7c4e8d012 100644 --- a/nanobot/session/webui_turns.py +++ b/nanobot/session/webui_turns.py @@ -56,6 +56,7 @@ from nanobot.webui.metadata import ( WEBUI_TURN_METADATA_KEY, ) from nanobot.webui.session_identity import is_webui_session_key +from nanobot.webui.star_prompt import update_star_prompt from nanobot.webui.transcript import append_session_message_input WEBUI_SESSION_METADATA_KEY = "webui" @@ -705,6 +706,13 @@ class WebuiTurnCoordinator: ) if self.recovery is not None: await self.recovery.turn_completed(event.context.session_key) + if event.outcome == "completed" and is_webui_session_key(event.context.session_key): + turn_id = event.context.metadata.get(WEBUI_TURN_METADATA_KEY) + if isinstance(turn_id, str) and turn_id: + try: + update_star_prompt("completed", turn_id=turn_id) + except (OSError, ValueError, TimeoutError): + logger.warning("Could not persist Star invitation usage") self._schedule_title_update_from_event(event) async def _handle_goal_state_changed(self, event: GoalStateChanged) -> None: diff --git a/nanobot/webui/star_prompt.py b/nanobot/webui/star_prompt.py new file mode 100644 index 000000000..6c4ac6430 --- /dev/null +++ b/nanobot/webui/star_prompt.py @@ -0,0 +1,69 @@ +"""Instance-local usage and dismissal state for the optional GitHub invitation.""" + +from __future__ import annotations + +import time +from datetime import UTC, datetime +from typing import Literal + +from filelock import FileLock +from pydantic import BaseModel, Field + +from nanobot.config.paths import get_webui_dir +from nanobot.utils.helpers import _write_text_atomic # pyright: ignore[reportPrivateUsage] + +COOLDOWN_SECONDS = 30 * 24 * 60 * 60 + + +class StarPromptState(BaseModel): + completed_replies: int = Field(default=0, ge=0, le=10) + active_days: list[str] = Field(default_factory=list, max_length=3) + recent_turns: list[str] = Field(default_factory=list, max_length=10) + shown_count: int = Field(default=0, ge=0, le=2) + next_prompt_at: float = Field(default=0, ge=0, allow_inf_nan=False) + dismissed_forever: bool = False + + +def update_star_prompt( + action: Literal["completed", "claim", "dismiss"], + *, + turn_id: str = "", +) -> bool: + """Persist before granting a display; serialize claims across gateway processes. + + A claim starts the cooldown even if the browser closes before displaying it. + Invalid existing state raises instead of resetting a user's dismissal. + """ + path = get_webui_dir() / "star-prompt.json" + with FileLock(str(path) + ".lock", timeout=2): + state = ( + StarPromptState.model_validate_json(path.read_text(encoding="utf-8")) + if path.exists() else StarPromptState() + ) + if state.dismissed_forever or (state.shown_count >= 2 and action != "dismiss"): + return False + now = time.time() + granted = False + if action == "dismiss": + state.dismissed_forever = True + elif action == "completed": + if not turn_id or turn_id in state.recent_turns: + return False + day = datetime.fromtimestamp(now, UTC).date().isoformat() + if state.completed_replies >= 10 and len(state.active_days) >= 3: + return False + state.completed_replies = min(10, state.completed_replies + 1) + if day not in state.active_days and len(state.active_days) < 3: + state.active_days.append(day) + state.recent_turns = [*state.recent_turns[-9:], turn_id] + else: + if ( + state.completed_replies < 10 or len(state.active_days) < 3 + or now < state.next_prompt_at + ): + return False + state.shown_count += 1 + state.next_prompt_at = now + COOLDOWN_SECONDS + granted = True + _write_text_atomic(path, state.model_dump_json(indent=2)) + return granted diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py index c0d0f1f61..33b222258 100644 --- a/nanobot/webui/ws_http.py +++ b/nanobot/webui/ws_http.py @@ -127,6 +127,7 @@ from nanobot.webui.skills_marketplace import ( search_marketplace_skills, trending_marketplace_skills, ) +from nanobot.webui.star_prompt import update_star_prompt from nanobot.webui.thread_disk import delete_webui_thread from nanobot.webui.transcript import ( TranscriptReplayStats, @@ -171,6 +172,8 @@ _WEBUI_MUTATION_PATHS = { "skill.install": "/api/webui/skills/install", "skill.update": "/api/webui/skills/update", "skill.delete": "/api/webui/skills/delete", + "star_prompt.claim": "/api/webui/star-prompt/claim", + "star_prompt.dismiss": "/api/webui/star-prompt/dismiss", "sidebar.update": "/api/webui/sidebar-state/update", "workspace.pick_folder": "/api/workspaces/pick-folder", "recovery.continue": "/api/webui/recovery/continue", @@ -521,6 +524,8 @@ class GatewayHTTPHandler: "/api/webui/skills/install", "/api/webui/skills/update", "/api/webui/skills/delete", + "/api/webui/star-prompt/claim", + "/api/webui/star-prompt/dismiss", "/api/webui/sidebar-state/update", "/api/workspaces/pick-folder", } @@ -1450,6 +1455,15 @@ class GatewayHTTPHandler: m = re.match(r"^/api/webui/skills/([^/]+)$", got) if m: return self._handle_webui_skill_detail(request, m.group(1)) + if got in {"/api/webui/star-prompt/claim", "/api/webui/star-prompt/dismiss"}: + if not self.check_api_token(request): + return _http_error(401, "Unauthorized") + try: + show = update_star_prompt("claim" if got.endswith("/claim") else "dismiss") + except (OSError, ValueError, TimeoutError): + self._log.exception("failed to persist star invitation state") + return _http_error(500, "failed to save reminder preference") + return _http_json_response({"show": show}) if got == "/api/webui/sidebar-state": return self._handle_webui_sidebar_state(request) if got == "/api/webui/sidebar-state/update": diff --git a/tests/webui/test_star_prompt.py b/tests/webui/test_star_prompt.py new file mode 100644 index 000000000..424525143 --- /dev/null +++ b/tests/webui/test_star_prompt.py @@ -0,0 +1,101 @@ +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from nanobot.webui import star_prompt + + +@pytest.fixture +def state_path(tmp_path, monkeypatch): + monkeypatch.setattr(star_prompt, "get_webui_dir", lambda: tmp_path) + return tmp_path / "star-prompt.json" + + +def seed_eligible(path: Path): + state = star_prompt.StarPromptState( + completed_replies=10, active_days=["2026-09-20", "2026-09-21", "2026-09-22"] + ) + path.write_text(state.model_dump_json(), encoding="utf-8") + + +def test_requires_completed_replies_on_three_days(state_path, monkeypatch): + for day in range(2): + monkeypatch.setattr(star_prompt.time, "time", lambda: 1_800_000_000 + day * 86400) + for index in range(5): + star_prompt.update_star_prompt("completed", turn_id=f"{day}-{index}") + assert not star_prompt.update_star_prompt("claim") + monkeypatch.setattr(star_prompt.time, "time", lambda: 1_800_000_000 + 2 * 86400) + star_prompt.update_star_prompt("completed", turn_id="third-day") + assert star_prompt.update_star_prompt("claim") + assert not star_prompt.update_star_prompt("claim") + + +def test_duplicate_turns_do_not_count(state_path): + for _ in range(15): + star_prompt.update_star_prompt("completed", turn_id="same-turn") + state = star_prompt.StarPromptState.model_validate_json(state_path.read_text()) + assert state.completed_replies == 1 + + +def test_concurrent_claims_cooldown_and_limit_survive_reload(state_path, monkeypatch): + seed_eligible(state_path) + monkeypatch.setattr(star_prompt.time, "time", lambda: 1_800_000_000) + with ThreadPoolExecutor(max_workers=8) as pool: + assert sum(pool.map(lambda _: star_prompt.update_star_prompt("claim"), range(8))) == 1 + monkeypatch.setattr(star_prompt.time, "time", lambda: 1_800_000_000 + star_prompt.COOLDOWN_SECONDS - 1) + assert not star_prompt.update_star_prompt("claim") + monkeypatch.setattr(star_prompt.time, "time", lambda: 1_800_000_000 + star_prompt.COOLDOWN_SECONDS) + assert star_prompt.update_star_prompt("claim") + monkeypatch.setattr(star_prompt.time, "time", lambda: 1_900_000_000) + assert not star_prompt.update_star_prompt("claim") + + +def test_dismissal_is_permanent_even_before_eligibility(state_path): + star_prompt.update_star_prompt("dismiss") + for index in range(20): + star_prompt.update_star_prompt("completed", turn_id=str(index)) + assert not star_prompt.update_star_prompt("claim") + assert star_prompt.StarPromptState.model_validate_json(state_path.read_text()).dismissed_forever + + +def test_corruption_and_write_failure_never_grant_display(state_path, monkeypatch): + state_path.write_text("broken", encoding="utf-8") + with pytest.raises(ValidationError): + star_prompt.update_star_prompt("claim") + seed_eligible(state_path) + + def fail(*args): + raise OSError("disk full") + + monkeypatch.setattr(star_prompt, "_write_text_atomic", fail) + with pytest.raises(OSError): + star_prompt.update_star_prompt("claim") + + +async def test_only_successful_webui_turns_record_usage(state_path, tmp_path, monkeypatch): + from unittest.mock import AsyncMock, Mock + + from nanobot.bus.queue import MessageBus + from nanobot.bus.runtime_events import RuntimeEventContext, TurnCompleted + from nanobot.session.manager import SessionManager + from nanobot.session.webui_turns import WebuiTurnCoordinator + from nanobot.webui.metadata import WEBUI_TURN_METADATA_KEY + + bus = MessageBus() + coordinator = WebuiTurnCoordinator(bus, SessionManager(tmp_path), Mock()) + monkeypatch.setattr(coordinator, "handle_turn_end", AsyncMock()) + monkeypatch.setattr(coordinator, "_schedule_title_update_from_event", Mock()) + with coordinator.connected(): + for channel, outcome in [("websocket", "completed"), ("websocket", "failed"), + ("websocket", "cancelled"), ("telegram", "completed")]: + await bus.publish(TurnCompleted( + context=RuntimeEventContext( + channel=channel, chat_id="test", session_key=f"{channel}:test", + metadata={WEBUI_TURN_METADATA_KEY: f"{channel}-{outcome}"}, + ), + outcome=outcome, + )) + state = star_prompt.StarPromptState.model_validate_json(state_path.read_text()) + assert state.completed_replies == 1 diff --git a/webui/src/App.tsx b/webui/src/App.tsx index 7b743bf66..4a0d69224 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -11,6 +11,7 @@ import { import { ArrowRight, ChevronDown, Eye, EyeOff, Moon, ShieldCheck, Sun, X } from "lucide-react"; import { Trans, useTranslation } from "react-i18next"; import { channelUiPresentation } from "@/channel-plugins/registry"; +import { StarPrompt } from "@/components/StarPrompt"; import { Sidebar } from "@/components/Sidebar"; import { LanguageSwitcher } from "@/components/LanguageSwitcher"; import { SidebarResizeHandle, SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH } from "@/components/SidebarResizeHandle"; @@ -2708,6 +2709,7 @@ function Shell({ return ( +
void; + fullWidth?: boolean; +}) { + const { client } = useClient(); + const { t } = useTranslation(); + const [error, setError] = useState(false); + const dismiss = () => { + setError(false); + void starPromptAction(client, "dismiss").then(onSaved).catch(() => setError(true)); + }; + const link = ( + { if (event.button === 1) dismiss(); }}> + {!fullWidth && } + + {t(fullWidth ? "starPrompt.action" : "starPrompt.footerAction")} + + + + ); + return ( + <> + {fullWidth ? : link} + {error &&

{t("starPrompt.saveError")}

} + + ); +} + +export function StarPrompt({ ready }: { ready: boolean }) { + const { client } = useClient(); + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(false); + const attempted = useRef(false); + const interacted = useRef(false); + const previousFocus = useRef(null); + const titleRef = useRef(null); + + useEffect(() => { + const cancel = () => { interacted.current = true; }; + const events = ["pointerdown", "keydown", "input", "wheel"] as const; + for (const event of events) document.addEventListener(event, cancel, { capture: true, passive: true }); + return () => { + for (const event of events) document.removeEventListener(event, cancel, true); + }; + }, []); + + useEffect(() => { + if (!ready || attempted.current) return; + let cancelled = false; + const unsubscribe = client.onStatus((status) => { + if (status !== "open" || attempted.current) return; + attempted.current = true; + if (interacted.current || document.visibilityState !== "visible" + || document.querySelector('[role="dialog"], [role="alertdialog"]')) return; + void starPromptAction(client, "claim").then(({ show }) => { + if (cancelled || !show || interacted.current || document.visibilityState !== "visible" + || document.querySelector('[role="dialog"], [role="alertdialog"]')) return; + previousFocus.current = document.activeElement instanceof HTMLElement + ? document.activeElement : null; + setOpen(true); + }).catch(() => { /* Optional invitations stay hidden when storage is unavailable. */ }); + }); + return () => { cancelled = true; unsubscribe(); }; + }, [client, ready]); + + const dismissForever = async () => { + setSaving(true); + setError(false); + try { + await starPromptAction(client, "dismiss"); + setOpen(false); + } catch { + setError(true); + } finally { + setSaving(false); + } + }; + + return ( + + { + event.preventDefault(); + titleRef.current?.focus({ preventScroll: true }); + }} onCloseAutoFocus={(event) => { + event.preventDefault(); + previousFocus.current?.focus({ preventScroll: true }); + }}> + + + {t("starPrompt.title")} + + + {t("starPrompt.description")} + +
+ +
+ setOpen(false)} /> +
+
+ + {error &&

{t("starPrompt.saveError")}

} +
+
+ ); +} diff --git a/webui/src/components/settings/SettingsPage.tsx b/webui/src/components/settings/SettingsPage.tsx index d94aa4837..84093f7b8 100644 --- a/webui/src/components/settings/SettingsPage.tsx +++ b/webui/src/components/settings/SettingsPage.tsx @@ -751,6 +751,7 @@ export function SettingsPage({ "mx-auto w-full animate-in fade-in-0 slide-in-from-bottom-1 py-6 duration-200 ease-out", "motion-reduce:animate-none sm:py-8 lg:py-12", "settings-grid", + activeSection === "about" && "flex min-h-full flex-col", !showSidebar && "settings-feature-page", !showSidebar && activeSection === "automations" && "settings-automations-grid", hostChromeInset && "pt-[4.25rem] sm:pt-[4.25rem] lg:pt-[4.75rem]", @@ -789,6 +790,7 @@ export function SettingsPage({
+

nanobot

@@ -158,6 +159,9 @@ export function AboutSettings({ currentVersion }: { currentVersion?: string }) { ))} +
+ +
); } diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 073be5c4d..037a81967 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -29,6 +29,15 @@ "invalid": "This address cannot be previewed.", "frame": "Website preview: {{host}}" }, + "starPrompt": { + "footerAction": "Star nanobot on GitHub", + "title": "Thanks for using nanobot", + "description": "Star nanobot on GitHub to help us keep improving it.", + "action": "Star on GitHub", + "later": "Not now", + "never": "Don’t ask again", + "saveError": "There may be a network issue. This reminder may appear again." + }, "app": { "brand": "nanobot", "loading": { diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index d29a3fe2e..d91ebaab1 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -29,6 +29,15 @@ "invalid": "No se puede previsualizar esta dirección.", "frame": "Vista previa web: {{host}}" }, + "starPrompt": { + "footerAction": "Dale una estrella a nanobot", + "title": "Gracias por usar nanobot", + "description": "Danos una estrella en GitHub para ayudarnos a seguir mejorando nanobot.", + "action": "Dar una estrella", + "later": "Ahora no", + "never": "No volver a preguntar", + "saveError": "Puede que haya un problema de conexión. Este recordatorio podría volver a aparecer." + }, "app": { "brand": "nanobot", "loading": { diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index b3ff19ad3..b828a083d 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -29,6 +29,15 @@ "invalid": "Cette adresse ne peut pas être prévisualisée.", "frame": "Aperçu web : {{host}}" }, + "starPrompt": { + "footerAction": "Ajouter une étoile à nanobot", + "title": "Merci d’utiliser nanobot", + "description": "Ajoutez une étoile sur GitHub pour nous aider à continuer à améliorer nanobot.", + "action": "Mettre une étoile", + "later": "Pas maintenant", + "never": "Ne plus demander", + "saveError": "Il y a peut-être un problème de connexion. Ce rappel pourrait réapparaître." + }, "app": { "brand": "nanobot", "loading": { diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index fb461a8a7..9ce811c60 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -29,6 +29,15 @@ "invalid": "Alamat ini tidak dapat dipratinjau.", "frame": "Pratinjau situs: {{host}}" }, + "starPrompt": { + "footerAction": "Beri bintang untuk nanobot", + "title": "Terima kasih telah menggunakan nanobot", + "description": "Beri bintang di GitHub untuk membantu kami terus menyempurnakan nanobot.", + "action": "Beri bintang", + "later": "Tidak sekarang", + "never": "Jangan tanyakan lagi", + "saveError": "Mungkin ada masalah jaringan. Pengingat ini mungkin muncul lagi." + }, "app": { "brand": "nanobot", "loading": { diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index 6d292739a..b226f2377 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -29,6 +29,15 @@ "invalid": "このアドレスはプレビューできません。", "frame": "ウェブプレビュー:{{host}}" }, + "starPrompt": { + "footerAction": "nanobot にスターを付ける", + "title": "nanobot のご利用ありがとうございます", + "description": "GitHub でスターを付けて、nanobot をより良くしていく取り組みを応援してください。", + "action": "スターを付ける", + "later": "今はしない", + "never": "今後表示しない", + "saveError": "ネットワークに問題が発生した可能性があります。この案内が再び表示されることがあります。" + }, "app": { "brand": "nanobot", "loading": { diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index cbb33f92e..de7e535c7 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -29,6 +29,15 @@ "invalid": "이 주소를 미리 볼 수 없습니다.", "frame": "웹 미리보기: {{host}}" }, + "starPrompt": { + "footerAction": "nanobot에 스타 남기기", + "title": "nanobot을 사용해 주셔서 감사합니다", + "description": "GitHub에서 스타를 눌러 nanobot을 계속 개선할 수 있도록 응원해 주세요.", + "action": "스타 남기기", + "later": "나중에", + "never": "다시 표시하지 않기", + "saveError": "네트워크에 문제가 있는 것 같습니다. 이 알림이 다시 표시될 수 있습니다." + }, "app": { "brand": "nanobot", "loading": { diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 5c2e4a408..601ae8da5 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -29,6 +29,15 @@ "invalid": "Não é possível pré-visualizar este endereço.", "frame": "Prévia do site: {{host}}" }, + "starPrompt": { + "footerAction": "Dê uma estrela ao nanobot", + "title": "Obrigado por usar o nanobot", + "description": "Dê uma estrela no GitHub para nos ajudar a continuar melhorando o nanobot.", + "action": "Dar uma estrela", + "later": "Agora não", + "never": "Não perguntar novamente", + "saveError": "Pode haver um problema de conexão. Este lembrete pode aparecer novamente." + }, "app": { "brand": "nanobot", "loading": { diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index 0143c7371..25f2bdbe8 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -29,6 +29,15 @@ "invalid": "Không thể xem trước địa chỉ này.", "frame": "Xem trước trang web: {{host}}" }, + "starPrompt": { + "footerAction": "Tặng nanobot một sao", + "title": "Cảm ơn bạn đã dùng nanobot", + "description": "Hãy tặng một sao trên GitHub để ủng hộ chúng tôi tiếp tục cải thiện nanobot.", + "action": "Tặng sao", + "later": "Để sau", + "never": "Không nhắc lại", + "saveError": "Có thể đã xảy ra sự cố mạng. Lời nhắc này có thể xuất hiện lại." + }, "app": { "brand": "nanobot", "loading": { diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index 9297b3a1a..0b575bbce 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -29,6 +29,15 @@ "invalid": "无法预览此地址。", "frame": "网页预览:{{host}}" }, + "starPrompt": { + "footerAction": "给 nanobot 点个 Star", + "title": "感谢使用 nanobot", + "description": "欢迎来 GitHub 点个 Star,支持我们继续改进。", + "action": "点个 Star", + "later": "暂时不了", + "never": "不再提醒", + "saveError": "网络可能出了点问题,之后可能还会弹出此提醒。" + }, "app": { "brand": "nanobot", "loading": { diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index c6a9d4f62..a22506d8c 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -29,6 +29,15 @@ "invalid": "無法預覽此位址。", "frame": "網頁預覽:{{host}}" }, + "starPrompt": { + "footerAction": "給 nanobot 一顆 Star", + "title": "感謝使用 nanobot", + "description": "歡迎到 GitHub 給顆 Star,支持我們持續改進。", + "action": "給個 Star", + "later": "暫時不用", + "never": "不再提醒", + "saveError": "網路可能出了點問題,之後可能還會跳出此提醒。" + }, "app": { "brand": "nanobot", "loading": { diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts index 44b5273df..b449418ab 100644 --- a/webui/src/lib/api.ts +++ b/webui/src/lib/api.ts @@ -1311,3 +1311,10 @@ export async function updateRuntimeConfigSettings( ): Promise { return mutation(transport, "settings.runtime_config.update", { values }); } + +export function starPromptAction( + transport: WebUIMutationTransport, + action: "claim" | "dismiss", +): Promise<{ show: boolean }> { + return mutation<{ show: boolean }>(transport, `star_prompt.${action}`); +} diff --git a/webui/src/tests/star-prompt.test.tsx b/webui/src/tests/star-prompt.test.tsx new file mode 100644 index 000000000..0b009a946 --- /dev/null +++ b/webui/src/tests/star-prompt.test.tsx @@ -0,0 +1,112 @@ +import { act, cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; + +import { StarLink, StarPrompt } from "@/components/StarPrompt"; +import { starPromptAction } from "@/lib/api"; +import i18n from "@/i18n"; + +vi.mock("@/lib/api", () => ({ starPromptAction: vi.fn() })); +const client = { + onStatus: (handler: (status: string) => void) => { handler("open"); return () => {}; }, +}; +vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client }) })); +const action = vi.mocked(starPromptAction); + +beforeEach(async () => { + vi.clearAllMocks(); + await i18n.changeLanguage("en"); + vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible"); + action.mockResolvedValue({ show: true }); +}); +afterEach(() => { cleanup(); vi.restoreAllMocks(); }); + +async function enter() { + await act(async () => { await Promise.resolve(); }); +} + +it("claims once on entry and lets users skip without permanently dismissing", async () => { + const view = render(); + await enter(); + expect(screen.getByRole("dialog")).toHaveAccessibleName("Thanks for using nanobot"); + fireEvent.click(screen.getByRole("button", { name: "Not now" })); + view.rerender(); + await enter(); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + expect(action).toHaveBeenCalledTimes(1); + expect(action).toHaveBeenCalledWith(client, "claim"); +}); + +it.each(["pointerdown", "keydown", "input", "wheel"])( + "skips this visit when %s occurs before the first screen is ready", async (event) => { + const view = render(); + fireEvent(document, new Event(event, { bubbles: true })); + view.rerender(); + await enter(); + expect(action).not.toHaveBeenCalled(); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + }, +); + +it.each(["pointerdown", "keydown", "input", "wheel"])( + "discards a delayed claim when %s occurs while waiting", async (event) => { + let resolve!: (value: { show: boolean }) => void; + action.mockReturnValueOnce(new Promise((done) => { resolve = done; })); + const view = render(); + fireEvent(document, new Event(event, { bubbles: true })); + await act(async () => resolve({ show: true })); + view.rerender(); + await enter(); + expect(action).toHaveBeenCalledTimes(1); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + }, +); + +it("stays hidden when another page claimed the invitation or storage fails", async () => { + action.mockResolvedValueOnce({ show: false }); + const view = render(); + await enter(); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + view.unmount(); + action.mockRejectedValueOnce(new Error("disk full")); + render(); + await enter(); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); +}); + +it("keeps a failed permanent dismissal retryable", async () => { + render(); + await enter(); + action.mockRejectedValueOnce(new Error("offline")); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Don’t ask again" }))); + expect(screen.getByRole("alert")).toHaveTextContent("There may be a network issue. This reminder may appear again."); + expect(screen.getByRole("dialog")).toBeVisible(); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Don’t ask again" }))); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + expect(action).toHaveBeenLastCalledWith(client, "dismiss"); +}); + +it("the About link opens GitHub and persists permanent dismissal", async () => { + render(); + const link = screen.getByRole("link", { name: "Star nanobot on GitHub" }); + expect(link).toHaveAttribute("href", "https://github.com/HKUDS/nanobot"); + expect(link).toHaveAttribute("target", "_blank"); + await act(async () => fireEvent.click(link)); + expect(action).toHaveBeenCalledWith(client, "dismiss"); +}); + + +it("waits for the initial connection and still attempts only once", async () => { + let statusChanged!: (status: string) => void; + vi.spyOn(client, "onStatus").mockImplementationOnce((handler) => { + statusChanged = handler; + handler("connecting"); + return () => {}; + }); + render(); + expect(action).not.toHaveBeenCalled(); + await act(async () => statusChanged("open")); + expect(screen.getByRole("dialog")).toBeVisible(); + fireEvent.click(screen.getByRole("button", { name: "Not now" })); + await act(async () => statusChanged("open")); + expect(action).toHaveBeenCalledTimes(1); +});