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

+2
View File
@@ -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 (
<ThemeProvider theme={theme}>
<StarPrompt ready={!loading && !sidebarStateLoading} />
<div
className={cn(
"relative h-full w-full overflow-hidden",
+125
View File
@@ -0,0 +1,125 @@
import { useEffect, useRef, useState } from "react";
import { ExternalLink, Star } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
import { starPromptAction } from "@/lib/api";
import { useClient } from "@/providers/ClientProvider";
const REPOSITORY_URL = "https://github.com/HKUDS/nanobot";
export function StarLink({ onSaved, fullWidth = false }: {
onSaved?: () => 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 = (
<a href={REPOSITORY_URL} target="_blank" rel="noopener noreferrer"
className={fullWidth ? undefined : "inline-flex min-h-10 items-center justify-center gap-2 rounded-control px-2 text-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}
onClick={dismiss} onAuxClick={(event) => { if (event.button === 1) dismiss(); }}>
{!fullWidth && <Star className="h-4 w-4 shrink-0" aria-hidden />}
<span className="min-w-0">
{t(fullWidth ? "starPrompt.action" : "starPrompt.footerAction")}
</span>
<ExternalLink className={fullWidth ? "ml-2 h-3.5 w-3.5 shrink-0" : "h-3.5 w-3.5 shrink-0 text-muted-foreground"} aria-hidden />
</a>
);
return (
<>
{fullWidth ? <Button asChild className="h-full min-h-11 w-full !whitespace-normal px-3 py-2.5 text-center text-sm font-medium">{link}</Button> : link}
{error && <p role="alert" className="text-sm text-destructive">{t("starPrompt.saveError")}</p>}
</>
);
}
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<HTMLElement | null>(null);
const titleRef = useRef<HTMLHeadingElement | null>(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 (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="max-w-[440px] gap-0 p-6 text-center outline-none"
onOpenAutoFocus={(event) => {
event.preventDefault();
titleRef.current?.focus({ preventScroll: true });
}} onCloseAutoFocus={(event) => {
event.preventDefault();
previousFocus.current?.focus({ preventScroll: true });
}}>
<img src="/brand/nanobot_mark.svg" alt="" className="mx-auto mb-4 h-10 w-10 select-none" draggable={false} />
<DialogTitle ref={titleRef} tabIndex={-1}
className="text-xl font-semibold leading-tight tracking-normal outline-none">
{t("starPrompt.title")}
</DialogTitle>
<DialogDescription className="mt-3 text-sm leading-6 text-muted-foreground">
{t("starPrompt.description")}
</DialogDescription>
<div className="mt-6 grid grid-cols-2 items-stretch gap-2">
<Button variant="ghost" className="h-full min-h-11 !whitespace-normal bg-muted/70 px-3 py-2.5 text-sm font-medium settings-hover"
onClick={() => setOpen(false)}>{t("starPrompt.later")}</Button>
<div className="flex flex-col gap-2">
<StarLink fullWidth onSaved={() => setOpen(false)} />
</div>
</div>
<Button variant="ghost" className="mx-auto mt-3 h-9 px-3 text-xs font-normal text-muted-foreground" disabled={saving}
onClick={() => void dismissForever()}>{t("starPrompt.never")}</Button>
{error && <p role="alert" className="text-sm text-destructive">{t("starPrompt.saveError")}</p>}
</DialogContent>
</Dialog>
);
}
@@ -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({
<div
className={cn(
"settings-stack",
activeSection === "about" && "flex flex-1 flex-col",
activeSection === "channels" &&
"flex min-h-0 flex-1 flex-col xl:overflow-hidden",
)}
@@ -3,12 +3,12 @@ import {
ArrowUpCircle,
Bot,
BookOpen,
Github,
MessageCircle,
Check,
ChevronRight,
ExternalLink,
Globe2,
Github,
ImageIcon,
Loader2,
Mic,
@@ -16,6 +16,7 @@ import {
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { StarLink } from "@/components/StarPrompt";
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings";
import type { SettingsSectionKey } from "@/components/settings/contracts";
@@ -137,12 +138,12 @@ export function OverviewSettings({
export function AboutSettings({ currentVersion }: { currentVersion?: string }) {
const { t } = useTranslation();
const links = [
{ key: "documentation", icon: BookOpen, href: "https://nanobot.wiki/" },
{ key: "sourceCode", icon: Github, href: "https://github.com/HKUDS/nanobot" },
{ key: "documentation", icon: BookOpen, href: "https://nanobot.wiki/" },
{ key: "reportIssue", icon: MessageCircle, href: "https://github.com/HKUDS/nanobot/issues" },
];
return (
<div className="settings-stack">
<div className="flex flex-1 flex-col gap-5">
<div className="flex flex-col items-center gap-4 py-6 text-center">
<img src="/brand/nanobot_mark.svg" alt="" className="h-16 w-16 select-none" draggable={false} />
<h1><img src="/brand/nanobot_wordmark.svg" alt="nanobot" className="h-auto w-40 select-none dark:brightness-150" draggable={false} /></h1>
@@ -158,6 +159,9 @@ export function AboutSettings({ currentVersion }: { currentVersion?: string }) {
</a>
))}
</SettingsGroup>
<div className="mt-auto pt-8 text-center">
<StarLink />
</div>
</div>
);
}
+9
View File
@@ -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": {
+9
View File
@@ -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": {
+9
View File
@@ -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": {
+9
View File
@@ -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": {
+9
View File
@@ -29,6 +29,15 @@
"invalid": "このアドレスはプレビューできません。",
"frame": "ウェブプレビュー:{{host}}"
},
"starPrompt": {
"footerAction": "nanobot にスターを付ける",
"title": "nanobot のご利用ありがとうございます",
"description": "GitHub でスターを付けて、nanobot をより良くしていく取り組みを応援してください。",
"action": "スターを付ける",
"later": "今はしない",
"never": "今後表示しない",
"saveError": "ネットワークに問題が発生した可能性があります。この案内が再び表示されることがあります。"
},
"app": {
"brand": "nanobot",
"loading": {
+9
View File
@@ -29,6 +29,15 @@
"invalid": "이 주소를 미리 볼 수 없습니다.",
"frame": "웹 미리보기: {{host}}"
},
"starPrompt": {
"footerAction": "nanobot에 스타 남기기",
"title": "nanobot을 사용해 주셔서 감사합니다",
"description": "GitHub에서 스타를 눌러 nanobot을 계속 개선할 수 있도록 응원해 주세요.",
"action": "스타 남기기",
"later": "나중에",
"never": "다시 표시하지 않기",
"saveError": "네트워크에 문제가 있는 것 같습니다. 이 알림이 다시 표시될 수 있습니다."
},
"app": {
"brand": "nanobot",
"loading": {
+9
View File
@@ -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": {
+9
View File
@@ -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": {
+9
View File
@@ -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": {
+9
View File
@@ -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": {
+7
View File
@@ -1311,3 +1311,10 @@ export async function updateRuntimeConfigSettings(
): Promise<SettingsPayload> {
return mutation<SettingsPayload>(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}`);
}
+112
View File
@@ -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(<StarPrompt ready />);
await enter();
expect(screen.getByRole("dialog")).toHaveAccessibleName("Thanks for using nanobot");
fireEvent.click(screen.getByRole("button", { name: "Not now" }));
view.rerender(<StarPrompt ready />);
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(<StarPrompt ready={false} />);
fireEvent(document, new Event(event, { bubbles: true }));
view.rerender(<StarPrompt ready />);
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(<StarPrompt ready />);
fireEvent(document, new Event(event, { bubbles: true }));
await act(async () => resolve({ show: true }));
view.rerender(<StarPrompt ready />);
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(<StarPrompt ready />);
await enter();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
view.unmount();
action.mockRejectedValueOnce(new Error("disk full"));
render(<StarPrompt ready />);
await enter();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
it("keeps a failed permanent dismissal retryable", async () => {
render(<StarPrompt ready />);
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(<StarLink />);
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(<StarPrompt ready />);
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);
});