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
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-24 15:37:18 +08:00
1 parent 09b2ae9a31
commit d898998c47
21 files changed
+567 -3

No files matched your search

@@ -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
+8
View File
@@ -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:
+69
View File
@@ -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
+14
View File
@@ -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":