Files
nanobot/webui/src/components/settings/overview/OverviewSettings.tsx
T
chengyongru b0d28af321 feat(webui): show commit and prefill bug report diagnostics (#6080)
* feat(webui): show gateway commit in About settings

* feat(webui): prefill revision in bug reports

* fix(webui): use parentheses for commit details

* feat(webui): prefill gateway diagnostics in bug reports

* docs: remove About settings explanation

* fix(webui): prefill dedicated issue diagnostic fields

* fix(docker): include revision helper in dependency build layer
2026-10-06 18:53:50 +08:00

565 lines
22 KiB
TypeScript

import {
ModelsIcon,
WebSearchIcon,
ImageGenerationIcon,
VoiceIcon,
} from "@/components/icons/product-icons";
import { useContext, useState, type Dispatch, type SetStateAction } from "react";
import {
ArrowUpCircle,
BookOpen,
MessageCircle,
Check,
ChevronRight,
ExternalLink,
Github,
Loader2,
type LucideIcon,
} from "lucide-react";
import { useTranslation } from "react-i18next";
import { HostNavigationContext } from "@/components/remote/HostSwitcher";
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";
import { settingsProviderConfigured } from "@/components/settings/shared/ModelControls";
import {
SettingsGroup,
SettingsRow,
SettingsSectionTitle,
} from "@/components/settings/shared/SettingsControls";
import { TokenUsageCard } from "@/components/settings/TokenUsageCard";
import { ToggleButton } from "@/components/settings/ToggleButton";
import { Button } from "@/components/ui/button";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { checkVersion } from "@/lib/api";
import type {
FileEditDisplayMode,
LocalActivityMode,
LocalPreferences,
} from "@/lib/local-preferences";
import { providerBrand, providerDisplayLabel } from "@/lib/provider-brand";
import type { SettingsPayload } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider";
export function OverviewSettings({
settings,
onSelectSection,
showBrandLogos,
}: {
settings: SettingsPayload;
onSelectSection: (section: SettingsSectionKey) => void;
showBrandLogos: boolean;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const activePresetName = settings.agent.model_preset;
const activePreset =
activePresetName && activePresetName !== "default"
? settings.model_presets.find((preset) => preset.name === activePresetName)?.name ??
activePresetName
: null;
const activeProvider = settings.agent.resolved_provider ?? settings.agent.provider;
const activeProviderConfigured = settingsProviderConfigured(settings, activeProvider);
const activeProviderLabel = providerDisplayLabel(settings.providers, activeProvider);
const activeModelValue = activeProviderConfigured
? settings.agent.model
: tx("settings.values.notConfigured", "Not configured");
const activeModelCaption = activeProviderConfigured
? [activeProvider, activePreset].filter(Boolean).join(" ")
: activeProviderLabel || settings.agent.model
? [activeProviderLabel, settings.agent.model].filter(Boolean).join(" ")
: tx("settings.byok.noConfiguredProviders", "No configured providers");
const webStatus = settings.web.enable
? tx("settings.values.enabled", "Enabled")
: tx("settings.values.disabled", "Disabled");
const imageStatus = settings.image_generation.enabled
? tx("settings.values.enabled", "Enabled")
: tx("settings.values.disabled", "Disabled");
const transcription = settings.transcription ?? DEFAULT_TRANSCRIPTION_SETTINGS;
const voiceStatus = transcription.enabled
? tx("settings.values.enabled", "Enabled")
: tx("settings.values.disabled", "Disabled");
return (
<div className="settings-stack">
<section className="rounded-panel bg-settings-surface p-6">
<TokenUsageCard usage={settings.usage} timeZone={settings.agent.timezone} />
</section>
<section>
<SettingsSectionTitle>{tx("settings.sections.ai", "AI")}</SettingsSectionTitle>
<SettingsGroup>
<OverviewListRow
icon={ModelsIcon}
valueLogoProvider={activeProvider}
title={tx("settings.overview.model", "Current model")}
value={activeModelValue}
caption={activeModelCaption}
showBrandLogos={showBrandLogos}
onClick={() => onSelectSection("models")}
/>
</SettingsGroup>
</section>
<section>
<SettingsSectionTitle>{tx("settings.sections.capabilities", "Capabilities")}</SettingsSectionTitle>
<SettingsGroup>
<OverviewListRow
icon={WebSearchIcon}
valueLogoProvider={settings.web_search.provider}
title={tx("settings.overview.webSearch", "Web search")}
value={webStatus}
showBrandLogos={showBrandLogos}
onClick={() => onSelectSection("browser")}
/>
<OverviewListRow
icon={ImageGenerationIcon}
valueLogoProvider={settings.image_generation.provider}
title={tx("settings.overview.imageGeneration", "Image generation")}
value={imageStatus}
showBrandLogos={showBrandLogos}
onClick={() => onSelectSection("image")}
/>
<OverviewListRow
icon={VoiceIcon}
valueLogoProvider={transcription.provider}
title={tx("settings.overview.voiceInput", "Voice input")}
value={voiceStatus}
showBrandLogos={showBrandLogos}
onClick={() => onSelectSection("voice")}
/>
</SettingsGroup>
</section>
</div>
);
}
type VersionInfoProps = { currentVersion?: string; currentCommit?: string | null };
export function AboutSettings({ settings }: { settings: SettingsPayload }) {
const { t } = useTranslation();
const hostPicker = useContext(HostNavigationContext);
const currentVersion = settings.version?.current;
const currentCommit = settings.version?.commit;
const environment = settings.environment;
const reportIssueUrl = new URL("https://github.com/HKUDS/nanobot/issues/new");
reportIssueUrl.searchParams.set("template", "bug_report.yml");
const reportedVersion = [currentVersion, currentCommit && `(commit ${currentCommit})`]
.filter(Boolean).join(" ");
if (reportedVersion) reportIssueUrl.searchParams.set("version", reportedVersion);
reportIssueUrl.searchParams.set("channel", "WebSocket");
if (environment) {
reportIssueUrl.searchParams.set("python_version", environment.python_version);
const osName = environment.os === "Darwin" ? "macOS" : environment.os;
const osVersion = [osName, environment.os_version].filter(Boolean).join(" ");
reportIssueUrl.searchParams.set("os", environment.architecture
? `${osVersion} (${environment.architecture})` : osVersion);
}
if (settings.agent.model) reportIssueUrl.searchParams.set("model", settings.agent.model);
const provider = settings.agent.resolved_provider || settings.agent.provider;
if (provider) reportIssueUrl.searchParams.set("llm_provider", provider);
reportIssueUrl.searchParams.set("browser", navigator.userAgent);
reportIssueUrl.searchParams.set("connection", hostPicker?.kind === "embedded"
? "Remote host" : hostPicker ? "Local host" : "Direct WebUI");
const links = [
{ key: "sourceCode", icon: Github, href: "https://github.com/HKUDS/nanobot" },
{ key: "documentation", icon: BookOpen, href: "https://nanobot.wiki/" },
{ key: "reportIssue", icon: MessageCircle, href: reportIssueUrl.href },
];
return (
<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>
<VersionCheckRow currentVersion={currentVersion} currentCommit={currentCommit} />
</div>
<SettingsGroup>
{links.map(({ key, icon: Icon, href }) => (
<a key={key} href={href} target="_blank" rel="noopener noreferrer"
className="settings-list-row flex select-none items-center gap-3 text-[14px] settings-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<Icon className="h-4 w-4 text-muted-foreground" aria-hidden />
<span className="flex-1">{t(`settings.about.${key}`)}</span>
<ExternalLink className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />
</a>
))}
</SettingsGroup>
<div className="mt-auto pt-8 text-center">
<StarLink />
</div>
</div>
);
}
function VersionCheckRow({ currentVersion, currentCommit }: VersionInfoProps) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const { token } = useClient();
const [checking, setChecking] = useState(false);
const [result, setResult] = useState<
| { type: "up-to-date" }
| { type: "update"; latestVersion: string; pypiUrl?: string }
| { type: "error"; message: string }
| null
>(null);
const handleCheck = async () => {
setChecking(true);
setResult(null);
try {
const res = await checkVersion(token);
if (res.updateAvailable) {
setResult({
type: "update",
latestVersion: res.updateAvailable.latestVersion,
pypiUrl: res.updateAvailable.pypiUrl,
});
} else {
setResult({ type: "up-to-date" });
}
} catch (err) {
setResult({ type: "error", message: (err as Error).message });
} finally {
setChecking(false);
}
};
return (
<div className="flex flex-col items-center gap-4">
<div className="min-w-0">
<div className="sr-only">
{tx("settings.about.version", "Version")}
</div>
<div className="mt-0.5 text-[12px] leading-5 text-muted-foreground">
{currentVersion ? `v${currentVersion}` : "nanobot"}
{currentCommit && (
<>
<span aria-hidden> (</span>
<a href={`https://github.com/HKUDS/nanobot/commit/${currentCommit}`}
target="_blank" rel="noopener noreferrer" title={currentCommit}
className="font-mono hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
{currentCommit.slice(0, 7)}
</a>
<span aria-hidden>)</span>
</>
)}
</div>
</div>
<div className="flex shrink-0 flex-col items-center gap-2">
<Button
size="sm"
variant="outline"
onClick={() => void handleCheck()}
disabled={checking}
className="rounded-full"
>
{checking ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
) : (
<ArrowUpCircle className="mr-1.5 h-3.5 w-3.5" aria-hidden />
)}
{checking
? tx("settings.about.checking", "Checking...")
: tx("settings.about.checkForUpdates", "Check for updates")}
</Button>
{result?.type === "up-to-date" ? (
<span className="inline-flex items-center gap-1.5 text-[12px] text-emerald-600 dark:text-emerald-300">
<Check className="h-3 w-3" aria-hidden />
{tx("settings.about.upToDate", "You're up to date")}
</span>
) : null}
{result?.type === "update" ? (
<span className="inline-flex items-center gap-1.5 text-[12px] text-blue-600 dark:text-blue-300">
<ArrowUpCircle className="h-3 w-3" aria-hidden />
{t("settings.about.updateAvailable", {
defaultValue: "Update available v{{version}}",
version: result.latestVersion,
})}
{result.pypiUrl ? (
<a
href={result.pypiUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-0.5 underline-offset-2 hover:underline"
>
PyPI
<ExternalLink className="h-2.5 w-2.5" aria-hidden />
</a>
) : null}
</span>
) : null}
{result?.type === "error" ? (
<span className="text-[12px] text-destructive">{result.message}</span>
) : null}
</div>
</div>
);
}
export function AppearanceSettings({
theme,
onToggleTheme,
localPrefs,
onChangeLocalPrefs,
}: {
theme: "light" | "dark";
onToggleTheme: () => void;
localPrefs: LocalPreferences;
onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
return (
<div className="settings-stack">
<section>
<SettingsSectionTitle>{t("settings.sections.interface")}</SettingsSectionTitle>
<SettingsGroup>
<SettingsRow title={t("settings.rows.theme")}>
<SegmentedControl
value={theme}
ariaLabel={t("settings.rows.theme")}
className="bg-muted p-0.5"
itemClassName="px-3"
options={[
{ value: "light", label: t("settings.values.light") },
{ value: "dark", label: t("settings.values.dark") },
]}
onChange={(nextTheme) => {
if (nextTheme !== theme) onToggleTheme();
}}
/>
</SettingsRow>
<SettingsRow title={t("settings.rows.language")}>
<LanguageSwitcher />
</SettingsRow>
</SettingsGroup>
</section>
<section>
<SettingsSectionTitle>{tx("settings.sections.localPreferences", "Local preferences")}</SettingsSectionTitle>
<SettingsGroup>
<SettingsRow title={tx("settings.rows.activityMode", "Activity detail")}>
<SegmentedControl
value={localPrefs.activityMode}
options={[
{ value: "auto", label: tx("settings.values.auto", "Auto") },
{ value: "expanded", label: tx("settings.values.expanded", "Expanded") },
]}
onChange={(activityMode) =>
onChangeLocalPrefs((prev) => ({ ...prev, activityMode: activityMode as LocalActivityMode }))
}
/>
</SettingsRow>
<SettingsRow title={tx("settings.rows.fileEditDisplay", "File edit display")}>
<SegmentedControl
value={localPrefs.fileEditDisplayMode}
options={[
{ value: "summary", label: tx("settings.values.summary", "Summary") },
{ value: "diff", label: tx("settings.values.diff", "Diff") },
{ value: "collapsed_diff", label: tx("settings.values.collapsedDiff", "Collapsed diff") },
]}
onChange={(fileEditDisplayMode) =>
onChangeLocalPrefs((prev) => ({
...prev,
fileEditDisplayMode: fileEditDisplayMode as FileEditDisplayMode,
}))
}
/>
</SettingsRow>
<SettingsRow title={tx("settings.rows.codeWrap", "Code wrapping")}>
<ToggleButton
checked={localPrefs.codeWrap}
onChange={(codeWrap) => onChangeLocalPrefs((prev) => ({ ...prev, codeWrap }))}
ariaLabel={tx("settings.rows.codeWrap", "Code wrapping")}
label={localPrefs.codeWrap ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
/>
</SettingsRow>
<SettingsRow
title={tx("settings.rows.brandLogos", "Brand logos")}
description={tx(
"settings.legal.thirdPartyBrands",
"Product names, logos, and brands are property of their respective owners. Use is for identification only and does not imply endorsement.",
)}
>
<ToggleButton
checked={localPrefs.brandLogos}
onChange={(brandLogos) => onChangeLocalPrefs((prev) => ({ ...prev, brandLogos }))}
ariaLabel={tx("settings.rows.brandLogos", "Brand logos")}
label={localPrefs.brandLogos ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
/>
</SettingsRow>
<SettingsRow
title={tx("settings.rows.browserNotifications", "Task notifications")}
description={tx(
"settings.help.browserNotifications",
"Notify only when this page is in the background. Off by default.",
)}
>
<ToggleButton
checked={localPrefs.browserNotifications}
onChange={(enabled) => {
if (!enabled) {
onChangeLocalPrefs((prev) => ({ ...prev, browserNotifications: false }));
return;
}
if (typeof Notification === "undefined") return;
if (Notification.permission === "granted") {
onChangeLocalPrefs((prev) => ({ ...prev, browserNotifications: true }));
return;
}
void Notification.requestPermission().then((permission) => {
if (permission === "granted") {
onChangeLocalPrefs((prev) => ({ ...prev, browserNotifications: true }));
}
});
}}
ariaLabel={tx("settings.rows.browserNotifications", "Task notifications")}
label={localPrefs.browserNotifications
? tx("settings.values.on", "On")
: tx("settings.values.off", "Off")}
/>
</SettingsRow>
<SettingsRow
title={tx("settings.rows.notificationSound", "Completion sound")}
description={tx(
"settings.help.notificationSound",
"Play a short chime when a turn finishes, even when this page is in the background. Off by default.",
)}
>
<ToggleButton
checked={localPrefs.notificationSound}
onChange={(notificationSound) =>
onChangeLocalPrefs((prev) => ({ ...prev, notificationSound }))}
ariaLabel={tx("settings.rows.notificationSound", "Completion sound")}
label={localPrefs.notificationSound
? tx("settings.values.on", "On")
: tx("settings.values.off", "Off")}
/>
</SettingsRow>
</SettingsGroup>
</section>
</div>
);
}
function OverviewRowIcon({
icon: Icon,
}: {
icon: LucideIcon;
}) {
return (
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-control bg-muted text-foreground/82 transition-colors dark:bg-muted/70">
<Icon className="h-4 w-4" aria-hidden />
</span>
);
}
function OverviewValueLogo({
provider,
showBrandLogos,
}: {
provider: string | null | undefined;
showBrandLogos: boolean;
}) {
const brand = provider ? providerBrand(provider) : null;
const { logoUrl, logoLoaded, onLogoError, onLogoLoad } = useLogoFallback(brand?.logoUrls);
const isLogoTile = brand?.logoLayout === "tile" && logoUrl === brand.logoUrl;
if (!provider || !showBrandLogos || !brand) return null;
if (logoUrl) {
return (
<span
data-testid={`overview-logo-${provider}`}
className={cn(
"grid h-5 w-5 shrink-0 place-items-center overflow-hidden rounded-md",
logoLoaded ? (isLogoTile ? "bg-transparent" : "bg-white") : "bg-muted",
)}
aria-hidden
>
<span
className={cn(
"col-start-1 row-start-1 grid h-full w-full place-items-center rounded-md text-[7.5px] font-semibold text-white",
logoLoaded ? "opacity-0" : "opacity-100",
)}
style={{ backgroundColor: brand.color }}
>
{brand.initials}
</span>
<img
src={logoUrl}
alt=""
decoding="async"
loading="lazy"
referrerPolicy="no-referrer"
draggable={false}
className={cn(
"col-start-1 row-start-1 object-contain",
isLogoTile ? "h-5 w-5" : "h-3.5 w-3.5",
logoLoaded ? "opacity-100" : "opacity-0",
)}
onLoad={onLogoLoad}
onError={onLogoError}
/>
</span>
);
}
return (
<span
data-testid={`overview-logo-fallback-${provider}`}
className="grid h-5 w-5 shrink-0 place-items-center rounded-md text-[7.5px] font-semibold text-white"
style={{ backgroundColor: brand.color }}
aria-hidden
>
{brand.initials}
</span>
);
}
function OverviewListRow({
icon: Icon,
valueLogoProvider,
title,
value,
caption,
showBrandLogos = false,
onClick,
}: {
icon: LucideIcon;
valueLogoProvider?: string | null;
title: string;
value: string;
caption?: string;
showBrandLogos?: boolean;
onClick: () => void;
}) {
return (
<button
type="button"
onClick={onClick}
className="group flex min-h-[68px] w-full select-none items-center gap-3 px-4 py-3.5 text-left transition-colors settings-hover sm:px-5"
>
<OverviewRowIcon icon={Icon} />
<span className="min-w-0 flex-1">
<span className="block text-[14px] font-medium leading-5 text-foreground">{title}</span>
{caption ? <span className="sr-only">{caption}</span> : null}
</span>
<span className="ml-auto flex min-w-0 max-w-[48%] items-center gap-2">
<OverviewValueLogo provider={valueLogoProvider} showBrandLogos={showBrandLogos} />
<span className="truncate text-right text-[13px] leading-5 text-muted-foreground">
{value}
</span>
<ChevronRight
className="h-4 w-4 shrink-0 text-muted-foreground/60 transition-transform group-hover:translate-x-0.5"
aria-hidden
/>
</span>
</button>
);
}