feat(webui): expand and organize settings with autosave (#5704)

* feat(webui): expand settings with autosave and live configuration

* feat(memory): add long-term memory and idle compaction switches

* refactor(webui): clarify settings hierarchy and align compact controls

* refactor(webui): keep only memory consolidation in memory settings

* refactor(webui): defer runtime changes until explicit restart

* refactor(webui): remove default workspace setting

* fix(webui): align model lists and remove preset counters

* fix(i18n): use natural Chinese labels for chat platforms

* fix(i18n): shorten chat settings navigation label

* fix(webui): match settings navigation icons to text size

* refactor(webui): remove redundant settings sidebar heading

* refactor(webui): use icon-only back navigation in settings

* fix(webui): remove back arrow hover hint

* refactor(webui): remove redundant overview details

* refactor(webui): hide secondary descriptions in settings rows

* style(webui): replace settings dividers with rounded highlights

* refactor(webui): remove redundant model list subtitles and badges

* fix(i18n): restore chat translation namespace boundaries

* fix(i18n): complete settings translations for all locales

* fix(webui): reveal settings only for enabled capabilities

* fix(webui): consolidate capabilities and isolate settings feedback

* fix(webui): clear restart notices when settings are reverted

* fix(webui): anchor restart controls in settings sidebar

* fix(webui): shorten sidebar restart label

* fix(webui): align settings spacing and control sizes

* refactor(webui): unify settings dialogs and interaction feedback

* fix(webui): keep settings option groups on one line without scrolling

* refactor(webui): align settings spacing and sidebar icon proportions

* style(webui): match main sidebar typography to settings

* style(webui): use monospace for sidebar session handles

* refactor(webui): remove heartbeat configuration from automations

* feat(webui): expose configuration actions beside capability toggles

* style(webui): remove ellipsis from configuration actions

* refactor(webui): remove redundant app configuration controls

* feat(webui): add compact sidebar navigation and shortcut hints

* fix(webui): synchronize npm dependency lockfile

* test(webui): align input radius expectation with pill styling

* feat(webui): show daily token usage and cache breakdown

* feat(webui): add model usage details and cache hit rates

* feat(webui): chart daily token usage by model

* refactor(webui): simplify usage details and model labels

* fix(webui): hide usage dialog date range

* refactor(webui): consolidate model usage into chart legends

* fix(webui): enforce restart choices and correct settings test route

* fix(webui): polish settings localization and controls

* fix(webui): avoid repeated usage legend labels

* fix(webui): skip empty usage columns in keyboard navigation

* test(webui): assert settings behavior positively

* feat(webui): refine sidebar navigation and add drag resizing

* style(webui): soften sidebar scroll edges

* style(webui): harmonize sidebar typography and text colors

* feat(webui): move channels to the main sidebar

* style(webui): remove dotted underlines from settings hints

* fix(webui): unify tooltip hover delay

* fix(webui): support Seatbelt sandbox settings

* fix(webui): remove unused appearance density preference

* fix(webui): align settings input values consistently

* style(webui): group compact settings controls before inputs

* feat(webui): edit multiline settings in compact dialogs

* feat(webui): add continuous settings scrolling with gentle snapping

* Revert "feat(webui): add continuous settings scrolling with gentle snapping"

This reverts commit f0978c261a53c844185eeab4d0c3190fbd196fe6.
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-10 11:10:51 +08:00
1 parent 20f115bf46
commit 8ea683679d
244 files changed
+6929 -3900

No files matched your search

+285 -171
View File
@@ -1,4 +1,10 @@
import { ChevronLeft, Loader2 } from "lucide-react";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogLayoutContext, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import type { SettingsExitGuard } from "@/components/settings/contracts";
import { isCapabilitySection, type SettingsSectionKey } from "@/components/settings/contracts";
import { SettingsFeature } from "@/components/settings/shared/SettingsFeature";
import { SkillsCatalogSettings } from "@/components/settings/SkillsCatalogSettings";
import { ImageGenerationSettings } from "@/components/settings/capabilities/ImageGenerationSettings";
@@ -14,12 +20,14 @@ import {
ProvidersSettings,
providerFormFromRow,
} from "@/components/settings/models/ProviderSettings";
import { AppearanceSettings, OverviewSettings } from "@/components/settings/overview/OverviewSettings";
import { AboutSettings, AppearanceSettings, OverviewSettings } from "@/components/settings/overview/OverviewSettings";
import { SettingsSidebar, standaloneSectionTitle } from "@/components/settings/SettingsSidebar";
import {
NanobotFeatureInstallDialog,
SettingsGroup,
SettingsRow,
SettingsSectionTitle,
RestartRequiredNotice,
} from "@/components/settings/shared/SettingsControls";
import { AppsCatalogSettings } from "@/components/settings/system/AppsSettings";
import {
@@ -28,12 +36,15 @@ import {
AutomationsSettings,
} from "@/components/settings/system/AutomationsSettings";
import { ChannelsSettings } from "@/components/settings/system/ChannelsSettings";
import { RUNTIME_CONFIG_FIELDS, type RuntimeConfigPage } from "@/components/settings/system/runtime-config-fields";
import { RuntimeConfigSettings } from "@/components/settings/system/RuntimeConfigSettings";
import { RuntimeSettings } from "@/components/settings/system/RuntimeSettings";
import type { SettingsController } from "@/components/settings/useSettingsController";
import type { SkillSummary } from "@/lib/types";
import { cn } from "@/lib/utils";
interface SettingsPageProps {
registerExitGuard?: (guard: SettingsExitGuard | null) => void;
controller: SettingsController;
theme: "light" | "dark";
showSidebar: boolean;
@@ -46,6 +57,7 @@ interface SettingsPageProps {
}
export function SettingsPage({
registerExitGuard,
controller,
theme,
showSidebar,
@@ -56,6 +68,8 @@ export function SettingsPage({
isRestarting,
hostChromeInset,
}: SettingsPageProps) {
const [dialogLayoutAnchor, setDialogLayoutAnchor] = useState<HTMLDivElement | null>(null);
const [pendingExit, setPendingExit] = useState<(() => void) | null>(null);
const {
activeSection,
apiService,
@@ -76,7 +90,6 @@ export function SettingsPage({
beginModelPresetCreation,
cancelModelPresetCreation,
changeModelCallOrder,
channelsQuery,
cliApps,
cliAppsAction,
cliAppsError,
@@ -109,7 +122,6 @@ export function SettingsPage({
handleSaveCustomMcp,
handleToggleProvider,
handleWebSearchProviderChange,
hasPendingRestart,
hostEngineApplying,
imageGenerationDirty,
imageGenerationForm,
@@ -147,7 +159,7 @@ export function SettingsPage({
networkSafetyDirty,
networkSafetyForm,
networkSafetySaving,
pendingRestartSections,
pendingRestartSections: controllerPendingRestartSections,
providerForms,
providerOAuthCompleting,
providerOAuthDialogError,
@@ -173,7 +185,6 @@ export function SettingsPage({
setAutomationsFilter,
setAutomationsQuery,
setAutomationsSort,
setChannelsQuery,
setCliAppsError,
setCliAppsMessage,
setCustomMcpForm,
@@ -216,18 +227,95 @@ export function SettingsPage({
webSearchSaving,
} = controller;
const renderSection = () => {
const restartInProgress = isRestarting || hostEngineApplying;
const requestExit = useCallback<SettingsExitGuard>((leave) => {
if (settings?.requires_restart && !restartInProgress) setPendingExit(() => leave);
else leave();
}, [settings?.requires_restart, restartInProgress]);
useEffect(() => {
registerExitGuard?.(requestExit);
return () => registerExitGuard?.(null);
}, [registerExitGuard, requestExit]);
const backToChat = () => registerExitGuard ? onBackToChat() : requestExit(onBackToChat);
const pendingRestartSections = showSidebar
? { runtime: false, image: false, browser: false }
: controllerPendingRestartSections;
const runtimeConfiguration = (page: RuntimeConfigPage) => settings && (
<RuntimeConfigSettings page={page} settings={settings} state={controller.runtimeConfigState}
onRestart={showSidebar ? undefined : restartViaSettingsSurface} isRestarting={restartInProgress}
remoteBrowserAccess={remoteBrowserAccess}>
{page === "advanced" ? (
<AdvancedSettings
error={controller.capabilityErrors.safety}
form={networkSafetyForm}
dirty={networkSafetyDirty}
saving={networkSafetySaving}
isNativeHostSurface={(settings.surface ?? settings.runtime_surface) === "native"}
onChangeForm={setNetworkSafetyForm}
onSave={saveNetworkSafetySettings}
onRestart={restartViaSettingsSurface}
isRestarting={restartInProgress}
requiresRestartPending={pendingRestartSections.runtime}
/>
) : null}
</RuntimeConfigSettings>
);
const renderSection = (section: SettingsSectionKey, embedded = false): ReactNode => {
if (!settings) return null;
switch (activeSection) {
switch (section) {
case "capabilities": {
const state = controller.runtimeConfigState;
const toggleRuntime = (path: string, enabled: boolean) => {
const field = RUNTIME_CONFIG_FIELDS.find((item) => item.path === path);
if (field) state.change(field, enabled);
};
return (
<section className="settings-stack">
<div className="settings-section-heading">
<SettingsSectionTitle>{t("settings.nav.capabilities")}</SettingsSectionTitle>
{!showSidebar && settings.requires_restart ? <RestartRequiredNotice message={t("settings.status.savedRestartApply")}
onRestart={restartViaSettingsSurface} isRestarting={restartInProgress} /> : null}
</div>
<SettingsFeature title={t("settings.rows.imageGeneration")} enabled={imageGenerationForm.enabled}
error={imageGenerationForm.enabled && !settings.image_generation.providers.find((provider) => provider.name === imageGenerationForm.provider)?.configured
? t("settings.image.missingCredential") : controller.capabilityErrors.image}
disabled={restartInProgress || imageGenerationSaving} initialOpen={activeSection === "image"}
onChange={(enabled) => setImageGenerationForm((prev) => ({ ...prev, enabled }))}>
{renderSection("image", true)}
</SettingsFeature>
<SettingsFeature title={t("settings.rows.transcription")} enabled={transcriptionForm.enabled}
error={controller.capabilityErrors.voice}
disabled={restartInProgress || transcriptionSaving} initialOpen={activeSection === "voice"}
onChange={(enabled) => setTranscriptionForm((prev) => ({ ...prev, enabled }))}>
{renderSection("voice", true)}
</SettingsFeature>
<SettingsFeature title={t("settings.runtimeConfig.groups.web.title")}
enabled={settings.runtime_config ? state.value("tools.web.enable") === true : settings.web.enable}
disabled={restartInProgress || state.saving === "web" || !settings.runtime_config}
initialOpen={activeSection === "browser"} error={state.errors.web || controller.capabilityErrors.web}
onChange={(enabled) => toggleRuntime("tools.web.enable", enabled)}>
{renderSection("browser", true)}
</SettingsFeature>
<SettingsFeature title={t("settings.runtimeConfig.fields.agents_defaults_dream_enabled.label")}
enabled={state.value("agents.defaults.dream.enabled") === true}
disabled={restartInProgress || state.saving === "memory" || !settings.runtime_config} error={state.errors.memory}
onChange={(enabled) => toggleRuntime("agents.defaults.dream.enabled", enabled)} />
{!settings.runtime_config ? <p className="settings-list-inset text-[13px] text-muted-foreground">{t("settings.runtimeConfig.unavailable")}</p> : null}
</section>
);
}
case "overview":
return (
<OverviewSettings
settings={settings}
requiresRestart={hasPendingRestart}
showBrandLogos={localPrefs.brandLogos}
onSelectSection={selectSection}
/>
);
case "about":
return <AboutSettings currentVersion={settings.version?.current} />;
case "appearance":
return (
<AppearanceSettings
@@ -239,7 +327,7 @@ export function SettingsPage({
);
case "models":
return (
<div className="space-y-8">
<div className="settings-stack">
<ModelsSettings
token={token}
form={form}
@@ -305,32 +393,37 @@ export function SettingsPage({
onCreateCustomProvider={createCustomProvider}
onProviderOAuthLogin={(provider) => runProviderOAuth(provider, "login")}
onProviderOAuthLogout={(provider) => runProviderOAuth(provider, "logout")}
imageProviderRestartPending={pendingRestartSections.image || pendingRestartSections.runtime}
onRestart={restartViaSettingsSurface}
isRestarting={isRestarting || hostEngineApplying}
/>
</div>
);
case "image":
return (
<ImageGenerationSettings
token={token}
settings={settings}
form={imageGenerationForm}
dirty={imageGenerationDirty}
saving={imageGenerationSaving}
onChangeForm={setImageGenerationForm}
onSave={saveImageGenerationSettings}
onOpenProviders={() => selectSection("models")}
showBrandLogos={localPrefs.brandLogos}
onRestart={restartViaSettingsSurface}
isRestarting={isRestarting || hostEngineApplying}
requiresRestartPending={pendingRestartSections.image}
/>
<div className="settings-stack">
<ImageGenerationSettings
error={controller.capabilityErrors.image}
embedded={embedded}
token={token}
settings={settings}
form={imageGenerationForm}
dirty={imageGenerationDirty}
saving={imageGenerationSaving}
onChangeForm={setImageGenerationForm}
onSave={saveImageGenerationSettings}
onOpenProviders={() => selectSection("models")}
showBrandLogos={localPrefs.brandLogos}
onRestart={restartViaSettingsSurface}
isRestarting={restartInProgress}
requiresRestartPending={pendingRestartSections.image}
>
{imageGenerationForm.enabled ? runtimeConfiguration("image") : null}
</ImageGenerationSettings>
</div>
);
case "voice":
return (
<TranscriptionSettings
error={controller.capabilityErrors.voice}
embedded={embedded}
settings={settings}
form={transcriptionForm}
dirty={transcriptionDirty}
@@ -340,36 +433,44 @@ export function SettingsPage({
onOpenProviders={() => selectSection("models")}
showBrandLogos={localPrefs.brandLogos}
onRestart={restartViaSettingsSurface}
isRestarting={isRestarting || hostEngineApplying}
isRestarting={restartInProgress}
requiresRestartPending={pendingRestartSections.browser}
/>
);
case "browser":
return (
<WebSettings
settings={settings}
form={webSearchForm}
keyVisible={webSearchKeyVisible}
keyEditing={webSearchKeyEditing}
saving={webSearchSaving}
onChangeForm={setWebSearchForm}
onChangeProvider={handleWebSearchProviderChange}
onToggleKey={() => setWebSearchKeyVisible((visible) => !visible)}
onToggleKeyEditing={() => {
setWebSearchKeyEditing((editing) => !editing);
setWebSearchKeyVisible(false);
setWebSearchForm((prev) => ({ ...prev, apiKey: "" }));
}}
onReset={resetWebSearchDraft}
onSave={saveWebSearch}
showBrandLogos={localPrefs.brandLogos}
onRestart={restartViaSettingsSurface}
isRestarting={isRestarting || hostEngineApplying}
requiresRestartPending={pendingRestartSections.browser}
olostepFeature={featureCatalog.find((feature) => feature.name === "olostep")}
olostepInstalling={nanobotFeatureAction === "enable:olostep"}
capabilityError={nanobotFeaturesError}
/>
<div className="settings-stack">
{!embedded ? runtimeConfiguration("browser") : null}
<WebSettings
error={controller.capabilityErrors.web || controller.runtimeConfigState.errors.web}
embedded={embedded}
enabled={settings.runtime_config
? controller.runtimeConfigState.value("tools.web.enable") !== false
: settings.web.enable}
settings={settings}
form={webSearchForm}
keyVisible={webSearchKeyVisible}
keyEditing={webSearchKeyEditing}
saving={webSearchSaving}
onChangeForm={setWebSearchForm}
onChangeProvider={handleWebSearchProviderChange}
onToggleKey={() => setWebSearchKeyVisible((visible) => !visible)}
onToggleKeyEditing={() => {
setWebSearchKeyEditing((editing) => !editing);
setWebSearchKeyVisible(false);
setWebSearchForm((prev) => ({ ...prev, apiKey: "" }));
}}
onReset={resetWebSearchDraft}
onSave={saveWebSearch}
showBrandLogos={localPrefs.brandLogos}
onRestart={restartViaSettingsSurface}
isRestarting={restartInProgress}
requiresRestartPending={pendingRestartSections.browser}
olostepFeature={featureCatalog.find((feature) => feature.name === "olostep")}
olostepInstalling={nanobotFeatureAction === "enable:olostep"}
capabilityError={nanobotFeaturesError}
/>
</div>
);
case "channels":
return (
@@ -377,154 +478,166 @@ export function SettingsPage({
token={token}
nanobotFeatures={nanobotFeatures}
loading={nanobotFeaturesLoading}
query={channelsQuery}
actionKey={nanobotFeatureAction}
chatAppsDocsUrl={settings.docs?.chat_apps_url}
showBrandLogos={localPrefs.brandLogos}
error={nanobotFeaturesError}
requiresRestartPending={pendingRestartSections.runtime}
onQueryChange={setChannelsQuery}
onAction={handleNanobotFeatureAction}
onFeaturesUpdate={setNanobotFeatures}
onDismissStatus={() => {
setNanobotFeaturesError(null);
}}
onRestart={restartViaSettingsSurface}
isRestarting={isRestarting || hostEngineApplying}
isRestarting={restartInProgress}
/>
);
case "apps":
return (
<AppsCatalogSettings
cliApps={cliApps}
mcpPresets={mcpPresets}
cliAppsLoading={cliAppsLoading}
mcpPresetsLoading={mcpPresetsLoading}
query={appsQuery}
filter={appsKindFilter}
cliActionKey={cliAppsAction}
mcpActionKey={mcpPresetAction}
mcpOAuthFlow={mcpOAuthFlow}
mcpOAuthPopupBlocked={mcpOAuthPopupBlocked}
mcpOAuthCallbackUrl={mcpOAuthCallbackUrl}
mcpOAuthCompleting={mcpOAuthCompleting}
mcpOAuthCallbackError={mcpOAuthCallbackError}
cliMessage={cliAppsMessage}
cliError={cliAppsError}
cliFocusName={cliAppsFocusName}
mcpMessage={mcpMessage}
mcpError={mcpError}
mcpFieldValues={mcpFieldValues}
customMcpForm={customMcpForm}
mcpConfigImport={mcpConfigImport}
showBrandLogos={localPrefs.brandLogos}
requiresRestartPending={pendingRestartSections.runtime}
onQueryChange={setAppsQuery}
onFilterChange={setAppsKindFilter}
onCliAction={handleCliAppAction}
onMcpAction={handleMcpPresetAction}
onMcpOAuthConnect={handleMcpOAuthConnect}
onMcpOAuthCancel={() => void handleMcpOAuthCancel()}
onMcpOAuthOpen={handleMcpOAuthOpen}
onMcpOAuthCallbackUrlChange={(value) => {
setMcpOAuthCallbackUrl(value);
setMcpOAuthCallbackError(null);
}}
onMcpOAuthComplete={() => void handleMcpOAuthComplete()}
onDismissStatus={() => {
setCliAppsMessage(null);
setCliAppsError(null);
setMcpMessage(null);
setMcpError(null);
}}
onBackToChat={onBackToChat}
onMcpFieldChange={(presetName, fieldName, value) => {
setMcpFieldValues((prev) => ({
...prev,
[presetName]: {
...(prev[presetName] ?? {}),
[fieldName]: value,
},
}));
}}
onCustomMcpFormChange={setCustomMcpForm}
onMcpConfigImportChange={setMcpConfigImport}
onSaveCustomMcp={handleSaveCustomMcp}
onImportMcpConfig={handleImportMcpConfig}
onMcpToolsChange={handleMcpToolsChange}
onRestart={restartViaSettingsSurface}
isRestarting={isRestarting || hostEngineApplying}
/>
<div className="settings-stack">
<AppsCatalogSettings
cliApps={cliApps}
mcpPresets={mcpPresets}
cliAppsLoading={cliAppsLoading}
mcpPresetsLoading={mcpPresetsLoading}
query={appsQuery}
filter={appsKindFilter}
cliActionKey={cliAppsAction}
mcpActionKey={mcpPresetAction}
mcpOAuthFlow={mcpOAuthFlow}
mcpOAuthPopupBlocked={mcpOAuthPopupBlocked}
mcpOAuthCallbackUrl={mcpOAuthCallbackUrl}
mcpOAuthCompleting={mcpOAuthCompleting}
mcpOAuthCallbackError={mcpOAuthCallbackError}
cliMessage={cliAppsMessage}
cliError={cliAppsError}
cliFocusName={cliAppsFocusName}
mcpMessage={mcpMessage}
mcpError={mcpError}
mcpFieldValues={mcpFieldValues}
customMcpForm={customMcpForm}
mcpConfigImport={mcpConfigImport}
showBrandLogos={localPrefs.brandLogos}
requiresRestartPending={pendingRestartSections.runtime}
onQueryChange={setAppsQuery}
onFilterChange={setAppsKindFilter}
onCliAction={handleCliAppAction}
onMcpAction={handleMcpPresetAction}
onMcpOAuthConnect={handleMcpOAuthConnect}
onMcpOAuthCancel={() => void handleMcpOAuthCancel()}
onMcpOAuthOpen={handleMcpOAuthOpen}
onMcpOAuthCallbackUrlChange={(value) => {
setMcpOAuthCallbackUrl(value);
setMcpOAuthCallbackError(null);
}}
onMcpOAuthComplete={() => void handleMcpOAuthComplete()}
onDismissStatus={() => {
setCliAppsMessage(null);
setCliAppsError(null);
setMcpMessage(null);
setMcpError(null);
}}
onBackToChat={onBackToChat}
onMcpFieldChange={(presetName, fieldName, value) => {
setMcpFieldValues((prev) => ({
...prev,
[presetName]: {
...(prev[presetName] ?? {}),
[fieldName]: value,
},
}));
}}
onCustomMcpFormChange={setCustomMcpForm}
onMcpConfigImportChange={setMcpConfigImport}
onSaveCustomMcp={handleSaveCustomMcp}
onImportMcpConfig={handleImportMcpConfig}
onMcpToolsChange={handleMcpToolsChange}
onRestart={restartViaSettingsSurface}
isRestarting={restartInProgress}
/>
</div>
);
case "automations":
return (
<AutomationsSettings
payload={automations}
loading={automationsLoading}
query={automationsQuery}
filter={automationsFilter}
sort={automationsSort}
actionKey={automationAction}
error={automationsError}
onQueryChange={setAutomationsQuery}
onFilterChange={setAutomationsFilter}
onSortChange={setAutomationsSort}
onAction={handleAutomationAction}
onRequestEdit={setAutomationPendingEdit}
onRequestDelete={setAutomationPendingDelete}
onBackToChat={onBackToChat}
/>
<div className="settings-stack">
<AutomationsSettings
payload={automations}
loading={automationsLoading}
query={automationsQuery}
filter={automationsFilter}
sort={automationsSort}
actionKey={automationAction}
error={automationsError}
onQueryChange={setAutomationsQuery}
onFilterChange={setAutomationsFilter}
onSortChange={setAutomationsSort}
onAction={handleAutomationAction}
onRequestEdit={setAutomationPendingEdit}
onRequestDelete={setAutomationPendingDelete}
onBackToChat={onBackToChat}
/>
</div>
);
case "skills":
return <SkillsCatalogSettings skills={skills} />;
case "runtime":
return (
<RuntimeSettings
form={form}
settings={settings}
onRestart={restartViaSettingsSurface}
isRestarting={isRestarting || hostEngineApplying}
requiresRestartPending={pendingRestartSections.runtime}
apiService={apiService}
apiServiceLoading={apiServiceLoading}
apiServiceAction={apiServiceAction}
apiServiceError={apiServiceError}
langfuseFeature={featureCatalog.find((feature) => feature.name === "langfuse")}
capabilitiesLoading={nanobotFeaturesLoading}
capabilityAction={nanobotFeatureAction}
capabilityError={nanobotFeaturesError}
onApiServiceAction={handleApiServiceAction}
onInstallCapability={(name) => void installCapabilities([name])}
/>
<div className="settings-stack">
{runtimeConfiguration("runtime")}
<RuntimeSettings
form={form}
settings={settings}
onRestart={showSidebar ? undefined : restartViaSettingsSurface}
isRestarting={restartInProgress}
requiresRestartPending={pendingRestartSections.runtime}
apiService={apiService}
apiServiceLoading={apiServiceLoading}
apiServiceAction={apiServiceAction}
apiServiceError={apiServiceError}
langfuseFeature={featureCatalog.find((feature) => feature.name === "langfuse")}
capabilitiesLoading={nanobotFeaturesLoading}
capabilityAction={nanobotFeatureAction}
capabilityError={nanobotFeaturesError}
onApiServiceAction={handleApiServiceAction}
onInstallCapability={(name) => void installCapabilities([name])}
/>
</div>
);
case "memory":
return runtimeConfiguration("memory");
case "advanced":
return (
<AdvancedSettings
form={networkSafetyForm}
dirty={networkSafetyDirty}
saving={networkSafetySaving}
isNativeHostSurface={(settings.surface ?? settings.runtime_surface) === "native"}
onChangeForm={setNetworkSafetyForm}
onSave={saveNetworkSafetySettings}
onRestart={restartViaSettingsSurface}
isRestarting={isRestarting || hostEngineApplying}
requiresRestartPending={pendingRestartSections.runtime}
/>
);
return runtimeConfiguration("advanced");
default:
return null;
}
};
return (
<DialogLayoutContext.Provider value={dialogLayoutAnchor}>
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-settings-canvas lg:flex-row">
<Dialog open={pendingExit !== null} onOpenChange={(open) => { if (!open) setPendingExit(null); }}>
<DialogContent showCloseButton={false}>
<DialogHeader>
<DialogTitle>{t("settings.exit.title")}</DialogTitle>
<DialogDescription>{t("settings.exit.description")}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => { const leave = pendingExit; setPendingExit(null); leave?.(); }}>{t("settings.exit.later")}</Button>
<Button onClick={() => { setPendingExit(null); void restartViaSettingsSurface(); }}>{t("app.system.restartAction")}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{showSidebar ? (
<SettingsSidebar
activeSection={activeSection}
onSelectSection={selectSection}
onBackToChat={onBackToChat}
onLogout={onLogout}
onBackToChat={backToChat}
onLogout={onLogout ? () => requestExit(onLogout) : undefined}
hostChromeInset={hostChromeInset}
onRestart={settings ? restartViaSettingsSurface : undefined}
isRestarting={restartInProgress}
restartPending={settings?.requires_restart}
isNativeHost={(settings?.surface ?? settings?.runtime_surface) === "native"}
/>
) : null}
@@ -596,18 +709,18 @@ export function SettingsPage({
<div
className={cn(
"min-w-0 flex-1 bg-settings-canvas [scrollbar-gutter:stable]",
activeSection === "channels" ? "overflow-y-auto xl:overflow-hidden" : "overflow-y-auto",
"overflow-y-auto",
)}
>
<div
key={activeSection}
data-testid="settings-section-transition"
ref={setDialogLayoutAnchor}
data-settings-section={activeSection}
className={cn(
"mx-auto w-full animate-in fade-in-0 slide-in-from-bottom-1 px-4 py-6 duration-200 ease-out",
"motion-reduce:animate-none sm:px-8 sm:py-8 lg:py-12",
activeSection === "channels" ? "max-w-[1240px] xl:px-10" : "max-w-[920px]",
activeSection === "channels" && "flex min-h-full flex-col xl:h-full xl:min-h-0",
"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",
hostChromeInset && "pt-[4.25rem] sm:pt-[4.25rem] lg:pt-[4.75rem]",
)}
>
@@ -615,8 +728,8 @@ export function SettingsPage({
<div className="mb-7">
<button
type="button"
onClick={onBackToChat}
className="touch-target mb-4 inline-flex items-center gap-1.5 rounded-full px-2.5 py-1.5 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground lg:hidden"
onClick={backToChat}
className="touch-target mb-4 inline-flex items-center gap-1.5 rounded-full px-2.5 py-1.5 text-[12px] font-medium text-muted-foreground transition-colors settings-hover hover:text-foreground lg:hidden"
>
<ChevronLeft className="h-3.5 w-3.5" aria-hidden />
{t("settings.backToChat")}
@@ -643,7 +756,7 @@ export function SettingsPage({
) : settings ? (
<div
className={cn(
"space-y-5",
"settings-stack",
activeSection === "channels" &&
"flex min-h-0 flex-1 flex-col xl:overflow-hidden",
)}
@@ -653,11 +766,12 @@ export function SettingsPage({
{error}
</div>
) : null}
{renderSection()}
{renderSection(isCapabilitySection(activeSection) ? "capabilities" : activeSection)}
</div>
) : null}
</div>
</div>
</div>
</DialogLayoutContext.Provider>
);
}
@@ -1,14 +1,14 @@
import { useRef } from "react";
import {
Activity,
Info,
Check,
ChevronDown,
ChevronLeft,
Globe2,
ImageIcon,
LogOut,
MessageCircle,
Mic,
Loader2,
RotateCcw,
Blocks,
Palette,
Server,
ShieldCheck,
@@ -21,7 +21,7 @@ import {
SIDEBAR_SELECTION_ITEM_CLASS,
SidebarSelectionHighlight,
} from "@/components/SidebarSelectionHighlight";
import type { SettingsSectionKey } from "@/components/settings/contracts";
import { isCapabilitySection, type SettingsSectionKey } from "@/components/settings/contracts";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -35,18 +35,17 @@ const SETTINGS_NAV_ITEMS: Array<{ key: SettingsSectionKey; icon: LucideIcon; fal
{ key: "overview", icon: Activity, fallback: "Overview" },
{ key: "appearance", icon: Palette, fallback: "Appearance" },
{ key: "models", icon: SlidersHorizontal, fallback: "Models" },
{ key: "image", icon: ImageIcon, fallback: "Image" },
{ key: "voice", icon: Mic, fallback: "Voice" },
{ key: "browser", icon: Globe2, fallback: "Web" },
{ key: "channels", icon: MessageCircle, fallback: "Channels" },
{ key: "capabilities", icon: Blocks, fallback: "Capabilities" },
{ key: "runtime", icon: Server, fallback: "System" },
{ key: "advanced", icon: ShieldCheck, fallback: "Security" },
{ key: "advanced", icon: ShieldCheck, fallback: "Advanced" },
{ key: "about", icon: Info, fallback: "About" },
];
export function standaloneSectionTitle(section: SettingsSectionKey): string {
if (section === "apps") return "Apps";
if (section === "automations") return "Automations";
if (section === "skills") return "Skills";
if (section === "channels") return "Channels";
return SETTINGS_NAV_ITEMS.find((item) => item.key === section)?.fallback ?? "Settings";
}
@@ -56,16 +55,28 @@ export function SettingsSidebar({
onBackToChat,
onLogout,
hostChromeInset,
onRestart,
isRestarting,
restartPending,
isNativeHost,
}: {
activeSection: SettingsSectionKey;
onSelectSection: (section: SettingsSectionKey) => void;
onBackToChat: () => void;
onLogout?: () => void;
hostChromeInset?: boolean;
onRestart?: () => void;
isRestarting?: boolean;
restartPending?: boolean;
isNativeHost?: boolean;
}) {
const { t } = useTranslation();
const restartLabel = isRestarting
? t(isNativeHost ? "app.system.restartingEngine" : "app.system.restarting")
: t("app.system.restartAction");
const navSection = isCapabilitySection(activeSection) ? "capabilities" : activeSection;
const activeNavItemRef = useRef<HTMLButtonElement>(null);
const activeItem = SETTINGS_NAV_ITEMS.find((item) => item.key === activeSection)
const activeItem = SETTINGS_NAV_ITEMS.find((item) => item.key === navSection)
?? SETTINGS_NAV_ITEMS[0];
const ActiveIcon = activeItem.icon;
const activeLabel = t(`settings.nav.${activeItem.key}`, {
@@ -75,26 +86,21 @@ export function SettingsSidebar({
return (
<aside
className={cn(
"flex w-full shrink-0 flex-col bg-settings-surface px-3 pb-2 lg:w-[17rem] lg:px-3 lg:pb-4",
"flex w-full shrink-0 select-none flex-col bg-settings-surface px-3 pb-2 lg:w-48 lg:px-3 lg:pb-4",
hostChromeInset ? "pt-10 lg:pt-10" : "pt-4 lg:pt-4",
)}
>
<button
type="button"
onClick={onBackToChat}
aria-label={t("settings.backToChat")}
className={cn(
"touch-target mb-2 inline-flex w-fit items-center gap-1.5 rounded-full px-2.5 py-1.5 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground lg:mb-3",
"touch-target mb-2 inline-flex h-9 w-9 items-center justify-center rounded-full text-[13px] leading-5 font-normal text-sidebar-content transition-colors settings-hover hover:text-foreground lg:mb-3",
hostChromeInset && "-ml-1",
)}
>
<ChevronLeft className="h-3.5 w-3.5" aria-hidden />
{t("settings.backToChat")}
<ChevronLeft className="h-4 w-4" aria-hidden />
</button>
<div className="mb-3 px-1 lg:mb-4 lg:px-2">
<h1 className="text-[18px] font-normal tracking-normal text-foreground">
{t("settings.sidebar.title")}
</h1>
</div>
<nav
aria-label={t("settings.sidebar.ariaLabel")}
@@ -105,11 +111,11 @@ export function SettingsSidebar({
<button
type="button"
aria-label={`${t("settings.sidebar.title")}: ${activeLabel}`}
className="touch-target flex h-11 w-full items-center gap-2.5 rounded-control bg-sidebar-accent px-3 text-left text-[13px] font-medium text-foreground transition-colors hover:bg-sidebar-accent/80 lg:hidden"
className="touch-target flex h-11 w-full items-center gap-2.5 rounded-control bg-sidebar-accent px-3 text-left text-[13px] leading-5 font-normal text-foreground transition-colors settings-hover lg:hidden"
>
<ActiveIcon className="h-4 w-4 shrink-0" strokeWidth={2} aria-hidden />
<span className="min-w-0 flex-1 truncate">{activeLabel}</span>
<ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
<ChevronDown className="h-4 w-4 shrink-0 text-sidebar-content" aria-hidden />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent
@@ -118,14 +124,14 @@ export function SettingsSidebar({
className="w-[var(--radix-dropdown-menu-trigger-width)] max-w-[calc(100vw-1.5rem)]"
>
{SETTINGS_NAV_ITEMS.map(({ key, icon: Icon, fallback }) => {
const active = key === activeSection;
const active = key === navSection;
return (
<DropdownMenuItem
key={key}
aria-current={active ? "page" : undefined}
onSelect={() => onSelectSection(key)}
className={cn(
"flex h-10 cursor-default items-center gap-2.5 px-2.5 text-[13px] font-medium",
"flex h-10 cursor-default items-center gap-2.5 px-2.5 text-[13px] leading-5 font-normal",
active && "bg-sidebar-accent text-foreground focus:bg-sidebar-accent",
)}
>
@@ -142,12 +148,12 @@ export function SettingsSidebar({
<SidebarSelectionHighlight
targetRef={activeNavItemRef}
activeId={activeSection}
activeId={navSection}
scope="settings"
className="relative hidden space-y-1 lg:block"
>
{SETTINGS_NAV_ITEMS.map(({ key, icon: Icon, fallback }) => {
const active = key === activeSection;
const active = key === navSection;
return (
<button
ref={active ? activeNavItemRef : undefined}
@@ -156,11 +162,11 @@ export function SettingsSidebar({
aria-current={active ? "page" : undefined}
onClick={() => onSelectSection(key)}
className={cn(
"touch-target flex h-9 w-full items-center gap-2 rounded-xl px-2.5 text-left text-[13px] font-medium",
"touch-target flex h-9 w-full items-center gap-2 rounded-xl px-2.5 text-left text-[13px] leading-5 font-normal",
SIDEBAR_SELECTION_ITEM_CLASS,
active
? "text-sidebar-accent-foreground"
: "text-muted-foreground/78 hover:bg-muted/45 hover:text-foreground",
: "text-sidebar-content settings-hover hover:text-foreground",
)}
>
<Icon className="h-4 w-4 shrink-0" strokeWidth={2} aria-hidden />
@@ -173,16 +179,40 @@ export function SettingsSidebar({
</SidebarSelectionHighlight>
</nav>
<div className="hidden lg:mt-auto lg:block lg:pt-4">
<div className="pt-2 lg:mt-auto lg:pt-4">
{onRestart ? (
<div>
{restartPending ? (
<p id="settings-restart-status" role="status" className="sr-only">
{t("settings.status.savedRestartApply")}
</p>
) : null}
<Button
type="button"
variant="ghost"
onClick={onRestart}
disabled={isRestarting}
aria-describedby={restartPending ? "settings-restart-status" : undefined}
className={cn("h-9 w-full justify-start gap-2 rounded-control px-2.5 text-[13px] leading-5 font-normal settings-hover",
restartPending && !isRestarting
? "settings-restart-pending text-orange-600 hover:text-orange-700 dark:text-orange-400 dark:hover:text-orange-300"
: "text-sidebar-content hover:text-foreground")}
>
{isRestarting ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
: <RotateCcw className="h-4 w-4" aria-hidden />}
<span>{restartLabel}</span>
</Button>
</div>
) : null}
{onLogout && !hostChromeInset ? (
<Button
type="button"
variant="ghost"
onClick={onLogout}
className="h-9 w-full justify-start gap-2 rounded-control px-2.5 text-[13px] font-medium text-muted-foreground hover:bg-destructive/8 hover:text-destructive"
className="hidden h-9 w-full justify-start gap-2 rounded-control px-2.5 text-[13px] leading-5 font-normal text-sidebar-content hover:bg-destructive/8 hover:text-destructive lg:flex"
>
<LogOut className="h-4 w-4" aria-hidden />
{t("app.account.logout")}
<span>{t("app.account.logout")}</span>
</Button>
) : null}
</div>
@@ -1,11 +1,12 @@
import { SettingsPage } from "@/components/settings/SettingsPage";
import type { SettingsSectionKey } from "@/components/settings/contracts";
import type { SettingsExitGuard, SettingsSectionKey } from "@/components/settings/contracts";
import { useSettingsController } from "@/components/settings/useSettingsController";
import type { SettingsPayload, SkillSummary } from "@/lib/types";
export type { SettingsSectionKey } from "@/components/settings/contracts";
interface SettingsViewProps {
registerExitGuard?: (guard: SettingsExitGuard | null) => void;
theme: "light" | "dark";
initialSection?: SettingsSectionKey;
initialSettings?: SettingsPayload | null;
@@ -24,6 +25,7 @@ interface SettingsViewProps {
}
export function SettingsView({
registerExitGuard,
theme,
initialSection = "overview",
initialSettings = null,
@@ -52,6 +54,7 @@ export function SettingsView({
return (
<SettingsPage
registerExitGuard={registerExitGuard}
controller={controller}
theme={theme}
showSidebar={showSidebar}
@@ -77,7 +77,7 @@ export function SkillsCatalogSettings({ skills }: { skills: SkillSummary[] }) {
const disabledCount = skills.filter((skill) => skill.enabled === false).length;
return (
<div className="space-y-7">
<div className="settings-stack">
<SegmentedControl
value={view}
mode="tabs"
@@ -222,7 +222,7 @@ function SkillCatalogRow({
className={cn(
"group flex w-full min-w-0 items-center gap-3 rounded-control px-2 py-3 text-left",
"transition-colors duration-150",
"hover:bg-muted/70",
"settings-hover",
"focus-visible:bg-muted/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
!enabled && "opacity-60",
)}
@@ -368,7 +368,7 @@ function SkillDetailSheet({
side="right"
closeButtonClassName={cn(
"right-2 top-2 inline-flex h-10 w-10 items-center justify-center rounded-full opacity-100",
"text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
"text-muted-foreground transition-colors settings-hover hover:text-foreground",
"sm:right-3 sm:top-3",
)}
className={cn(
@@ -570,7 +570,7 @@ function RawInstructionsBlock({ markdown }: { markdown: string }) {
const content =
markdown ||
t("settings.skills.rawInstructionsEmpty", {
defaultValue: "No raw instructions.",
defaultValue: "No skill file content available.",
});
return (
@@ -661,7 +661,7 @@ function RequirementsSection({
})}
title={option.label}
onClick={() => void copyCommand(option.command)}
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-muted hover:text-foreground sm:h-7 sm:w-7"
className="flex h-9 w-9 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors settings-hover hover:text-foreground sm:h-7 sm:w-7"
>
{copiedCommand === option.command ? (
<Check className="h-3.5 w-3.5 text-emerald-600" aria-hidden />
@@ -675,14 +675,14 @@ function RequirementsSection({
{!installOptions.length && missing_bins.length ? (
<SetupRequirement
icon={<Terminal className="h-3.5 w-3.5" aria-hidden />}
label={t("settings.skills.missingCommands", { defaultValue: "Missing CLI" })}
label={t("settings.skills.missingCommands", { defaultValue: "Missing command-line tools" })}
items={missing_bins}
/>
) : null}
{missing_env.length ? (
<SetupRequirement
icon={<KeyRound className="h-3.5 w-3.5" aria-hidden />}
label={t("settings.skills.missingEnvironment", { defaultValue: "Missing ENV" })}
label={t("settings.skills.missingEnvironment", { defaultValue: "Missing environment variables" })}
items={missing_env}
/>
) : null}
@@ -208,7 +208,7 @@ export function SkillsMarketplace({
aria-label={t("settings.skills.marketplaceSearchLabel", {
defaultValue: "Search skills",
})}
className="h-11 rounded-control bg-settings-surface pl-9"
className="h-11 rounded-full bg-settings-surface pl-9"
/>
{loading ? (
<span
@@ -519,7 +519,7 @@ function MarketplaceSkillRow({
provider: providerLabel(skill.provider),
defaultValue: "Open {{name}} on {{provider}}",
})}
className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors settings-hover hover:text-foreground"
>
<ExternalLink className="h-3.5 w-3.5" aria-hidden />
</a>
@@ -1,3 +1,4 @@
import type { ComponentProps } from "react";
import { cn } from "@/lib/utils";
export function ToggleButton({
@@ -6,15 +7,17 @@ export function ToggleButton({
onChange,
ariaLabel,
label,
...accessibility
}: {
checked: boolean;
disabled?: boolean;
onChange: (checked: boolean) => void;
ariaLabel?: string;
label: string;
}) {
} & Pick<ComponentProps<"button">, "id" | "aria-describedby" | "aria-invalid">) {
return (
<button
{...accessibility}
type="button"
role="switch"
aria-checked={checked}
@@ -0,0 +1,182 @@
import { useTranslation } from "react-i18next";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import type { SettingsPayload } from "@/lib/types";
import { cn } from "@/lib/utils";
import { TokenUsageDetails } from "@/components/settings/TokenUsageDetails";
import { SettingsHint } from "@/components/settings/shared/SettingsHint";
type Usage = NonNullable<SettingsPayload["usage"]>;
const SOURCE_KEYS = ["user", "api", "cron", "dream", "system"] as const;
const SEGMENT_CLASSES = [
"bg-orange-100 text-orange-500 dark:bg-orange-400/15 dark:text-orange-400",
"bg-neutral-300 dark:bg-neutral-500",
"bg-neutral-200 dark:bg-neutral-700",
"bg-orange-500 dark:bg-orange-400",
"bg-neutral-500 dark:bg-neutral-300",
];
const CACHE_PATTERN = { backgroundImage: "repeating-linear-gradient(135deg, transparent, transparent 3px, currentColor 3px, currentColor 4px)" };
function tokenSegments(day?: Usage["days"][number]): number[] {
if (!day) return [0, 0, 0, 0, 0];
const observed = day.cache_read_observed_input_tokens;
return [day.cache_read_tokens, observed - day.cache_read_tokens,
day.input_tokens - observed,
day.output_tokens, Math.max(0, day.total_tokens - day.input_tokens - day.output_tokens)];
}
function todayInTimeZone(timeZone?: string): string {
const now = new Date();
if (timeZone) {
try {
const parts = new Intl.DateTimeFormat("en", {
calendar: "gregory", numberingSystem: "latn", timeZone,
year: "numeric", month: "2-digit", day: "2-digit",
}).formatToParts(now);
const values = Object.fromEntries(parts.map(({ type, value }) => [type, value]));
return `${values.year}-${values.month}-${values.day}`;
} catch {
// Unrecognized configured timezones fall back to UTC.
}
}
return now.toISOString().slice(0, 10);
}
export function TokenUsageCard({ usage, timeZone }: { usage?: Usage; timeZone?: string }) {
const { t, i18n } = useTranslation();
const today = todayInTimeZone(timeZone);
const byDate = new Map(usage?.days.map(day => [day.date, day]));
const days = Array.from({ length: 30 }, (_, index) => {
const date = new Date(`${today}T00:00:00Z`);
date.setUTCDate(date.getUTCDate() - 29 + index);
const key = date.toISOString().slice(0, 10);
return { date: key, usage: byDate.get(key) };
});
const total = days.reduce((sum, day) => sum + (day.usage?.total_tokens ?? 0), 0);
const peak = Math.max(0, ...days.map(day => day.usage?.total_tokens ?? 0));
const compact = new Intl.NumberFormat(i18n.language, { notation: "compact", maximumFractionDigits: 1 });
const exact = new Intl.NumberFormat(i18n.language);
const percent = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 });
const dateFormat = new Intl.DateTimeFormat(i18n.language, { month: "short", day: "numeric", timeZone: "UTC" });
const formatDate = (date: string) => dateFormat.format(new Date(`${date}T00:00:00Z`));
const segmentLabels = [
t("settings.usage.cachedInput", { defaultValue: "Cached input" }),
t("settings.usage.cacheMiss", { defaultValue: "Cache miss" }),
t("settings.usage.cacheUnknown", { defaultValue: "Cache status unknown" }),
t("settings.usage.outputTokens", { defaultValue: "Output" }),
t("settings.usage.otherTokens", { defaultValue: "Other tokens" }),
];
const hasOtherTokens = days.some(day => tokenSegments(day.usage)[4] > 0);
const sourceLabels: Record<string, string> = {
user: t("settings.usage.sources.user", { defaultValue: "Chat" }),
api: t("settings.usage.sources.api", { defaultValue: "API" }),
cron: t("settings.usage.sources.cron", { defaultValue: "Automations" }),
dream: t("settings.usage.sources.dream", { defaultValue: "Memory" }),
system: t("settings.usage.sources.system", { defaultValue: "Auxiliary calls" }),
other: t("settings.usage.unclassified", { defaultValue: "Unclassified" }),
};
const sources = new Map<string, number>();
for (const day of days) {
let classified = 0;
for (const [source, value] of Object.entries(day.usage?.sources ?? {})) {
const key = SOURCE_KEYS.some(known => known === source) ? source : "other";
sources.set(key, (sources.get(key) ?? 0) + value.total_tokens);
classified += value.total_tokens;
}
const remainder = Math.max(0, (day.usage?.total_tokens ?? 0) - classified);
sources.set("other", (sources.get("other") ?? 0) + remainder);
}
const breakdown = [...sources].filter(([, tokens]) => tokens > 0).sort((a, b) => b[1] - a[1]);
return (
<div className="min-w-0 space-y-5">
<div className="flex items-start justify-between gap-4">
<div>
<h3 className="text-sm font-medium">{t("settings.usage.shortTitle", { defaultValue: "Token usage" })}</h3>
<p className="mt-2 text-3xl font-semibold tracking-tight tabular-nums" aria-label={usage ? `${exact.format(total)} tokens` : undefined}>
{usage ? compact.format(total) : "—"}
</p>
</div>
{usage && <TokenUsageDetails days={days} models={usage.providers_30d} modelDays={usage.model_days_30d} />}
</div>
{!usage || total === 0 ? (
<p className="pb-2 text-sm text-muted-foreground" role="status">
{!usage
? t("settings.usage.unavailable", { defaultValue: "Usage data is unavailable." })
: t("settings.usage.noActivity", { defaultValue: "No token usage in the last 30 days." })}
</p>
) : (
<>
<div>
<div className="mb-2 text-right text-[11px] tabular-nums text-muted-foreground" aria-hidden>{compact.format(peak)}</div>
<div className="relative">
<div className="pointer-events-none absolute inset-0 flex flex-col justify-between" aria-hidden>
{[0, 1, 2].map(line => <div key={line} className="border-t border-border/40" />)}
</div>
<div className="relative grid h-28 grid-cols-[repeat(30,minmax(0,1fr))] gap-1" role="group" aria-label={t("settings.usage.dailyTrend", { defaultValue: "Daily token usage" })}>
<TooltipProvider>
{days.map(day => {
const tokens = day.usage?.total_tokens ?? 0;
const segments = tokenSegments(day.usage);
const label = t("settings.usage.cellTitle", {
defaultValue: "{{date}}: {{tokens}} tokens, {{requests}} requests",
date: day.date, tokens: exact.format(tokens), requests: day.usage?.requests ?? 0,
});
if (tokens === 0) return <span key={day.date} role="img" aria-label={label} />;
return (
<Tooltip key={day.date}>
<TooltipTrigger asChild>
<span tabIndex={0} role="img" aria-label={`${label}; ${segments.map((value, index) => `${segmentLabels[index]}: ${exact.format(value)}`).join(", ")}`} className="group flex h-full min-w-0 items-end rounded-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-orange-600 dark:focus-visible:outline-orange-400">
<span className="flex w-full flex-col-reverse overflow-hidden rounded-t-sm group-hover:brightness-95" style={{ height: `${tokens / peak * 100}%` }}>
{segments.map((value, index) => value > 0 && <span key={index} className={cn("w-full shrink-0", SEGMENT_CLASSES[index])} style={{ height: `${value / tokens * 100}%`, ...(index === 0 ? CACHE_PATTERN : {}) }} />)}
</span>
</span>
</TooltipTrigger>
<TooltipContent className="min-w-56 p-3">
<div className="mb-2 flex justify-between gap-6 font-medium tabular-nums"><span>{day.date}</span><span>{exact.format(tokens)}</span></div>
<dl className="space-y-1.5">
{segments.map((value, index) => (index < 4 || value > 0) && <div key={index} className="flex items-center justify-between gap-6">
<dt className="flex items-center text-muted-foreground"><span aria-hidden className={cn("size-2.5 rounded-sm", SEGMENT_CLASSES[index])} style={index === 0 ? CACHE_PATTERN : undefined} /><span className="sr-only">{segmentLabels[index]}</span></dt>
<dd className="tabular-nums">{exact.format(value)}</dd>
</div>)}
<div className="flex justify-between gap-6 border-t border-border/50 pt-2">
<dt className="text-muted-foreground">{t("settings.usage.cacheHitRate", { defaultValue: "Cache hit rate" })}</dt>
<dd className="tabular-nums">{day.usage?.cache_read_observed_input_tokens ? percent.format(day.usage.cache_read_tokens / day.usage.cache_read_observed_input_tokens) : "—"}</dd>
</div>
</dl>
</TooltipContent>
</Tooltip>
);
})}
</TooltipProvider>
</div>
</div>
<div className="mt-2 flex justify-between text-[11px] text-muted-foreground" aria-hidden>
<span>{formatDate(days[0].date)}</span>
<span>{formatDate(days[14].date)}</span>
<span>{formatDate(today)}</span>
</div>
<div className="mt-3 flex flex-wrap gap-x-4 gap-y-2 text-[11px] text-muted-foreground">
{segmentLabels.map((label, index) => (index < 4 || hasOtherTokens) && <span key={label} className="flex items-center gap-1.5"><span aria-hidden className={cn("size-2.5 rounded-sm", SEGMENT_CLASSES[index])} style={index === 0 ? CACHE_PATTERN : undefined} />{label}</span>)}
</div>
</div>
<dl className="grid grid-cols-1 gap-x-6 gap-y-2 text-xs sm:grid-cols-3" aria-label={t("settings.usage.bySource", { defaultValue: "Usage by source" })}>
{breakdown.map(([source, tokens]) => (
<div key={source} className="flex min-w-0 items-center justify-between gap-2">
<dt className="min-w-0 break-words text-muted-foreground">
{source === "system" ? (
<SettingsHint description={t("settings.usage.systemHelp", {
defaultValue: "Auxiliary calls include chat title generation, other internal tasks, and calls without a recorded source.",
})}>{sourceLabels[source]}</SettingsHint>
) : sourceLabels[source]}
</dt>
<dd className="shrink-0 tabular-nums" title={`${exact.format(tokens)} tokens`}>{new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 }).format(tokens / total)}</dd>
</div>
))}
</dl>
</>
)}
</div>
);
}
@@ -0,0 +1,47 @@
import { ChevronRight } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Dialog, DialogContent, DialogLayoutContext, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import type { SettingsPayload } from "@/lib/types";
import { TokenUsageModelTrend } from "@/components/settings/TokenUsageModelTrend";
type Usage = NonNullable<SettingsPayload["usage"]>;
export function TokenUsageDetails({ days, models, modelDays }: {
days: { date: string; usage?: Usage["days"][number] }[];
models?: Usage["providers_30d"];
modelDays?: Usage["model_days_30d"];
}) {
const { t, i18n } = useTranslation();
const number = new Intl.NumberFormat(i18n.language, { maximumFractionDigits: 0 });
const percent = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 });
const sum = (key: "total_tokens" | "requests" | "cache_read_tokens" | "cache_read_observed_input_tokens") =>
days.reduce((total, day) => total + (day.usage?.[key] ?? 0), 0);
const total = sum("total_tokens");
const observed = sum("cache_read_observed_input_tokens");
const metrics = [
[t("settings.usage.totalTokens"), number.format(total)],
[t("settings.usage.requests"), number.format(sum("requests"))],
[t("settings.usage.cacheHitRate"), observed ? percent.format(sum("cache_read_tokens") / observed) : "—"],
];
return (
<DialogLayoutContext.Provider value={null}>
<Dialog>
<DialogTrigger asChild>
<button type="button" className="settings-hover flex shrink-0 items-center gap-1 rounded-full px-2 py-1 text-xs text-muted-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring">
{t("settings.usage.viewDetails")}<ChevronRight className="size-3.5" aria-hidden />
</button>
</DialogTrigger>
<DialogContent className="w-[min(1100px,calc(100vw-32px))] max-w-none gap-5 p-5 pt-10 sm:p-7 sm:pt-10" aria-describedby={undefined}>
<DialogTitle className="sr-only">{t("settings.usage.shortTitle")}</DialogTitle>
<dl className="grid grid-cols-3 gap-3">
{metrics.map(([label, value], index) => <div key={label} title={index === 2 ? t("settings.usage.cacheRateHelp") : undefined}>
<dt className="text-xs text-muted-foreground">{label}</dt>
<dd className="mt-1 text-lg font-medium tabular-nums sm:text-2xl">{value}</dd>
</div>)}
</dl>
{modelDays?.length ? <TokenUsageModelTrend days={days} modelDays={modelDays} models={models} /> : <p className="text-sm text-muted-foreground">{t("settings.usage.modelsUnavailable")}</p>}
</DialogContent>
</Dialog>
</DialogLayoutContext.Provider>
);
}
@@ -1,250 +0,0 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import type { SettingsPayload } from "@/lib/types";
type TokenUsagePayload = NonNullable<SettingsPayload["usage"]>;
type TokenUsageDay = TokenUsagePayload["days"][number];
type TokenUsageCell = {
date: string;
total: number;
estimated: number;
requests: number;
sources: NonNullable<TokenUsageDay["sources"]>;
future: boolean;
};
type TokenUsageMonthLabel = {
label: string;
column: number;
};
const TOKEN_HEATMAP_CELLS = 371;
const TOKEN_HEATMAP_COLUMNS = Math.ceil(TOKEN_HEATMAP_CELLS / 7);
const TOKEN_USAGE_SOURCE_ORDER = ["user", "api", "cron", "dream", "system"] as const;
function addUtcDays(date: Date, days: number): Date {
const next = new Date(date);
next.setUTCDate(next.getUTCDate() + days);
return next;
}
function isoDay(date: Date): string {
return date.toISOString().slice(0, 10);
}
function utcDateFromIsoDay(day: string): Date {
const [year, month, date] = day.split("-").map(Number);
return new Date(Date.UTC(year, month - 1, date));
}
function isoDayInTimeZone(date: Date, timeZone: string | undefined): string {
if (!timeZone) return isoDay(date);
try {
const parts = new Intl.DateTimeFormat("en", {
calendar: "gregory",
numberingSystem: "latn",
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
}).formatToParts(date);
const values = Object.fromEntries(parts.map((part) => [part.type, part.value]));
if (values.year && values.month && values.day) {
return [
values.year.padStart(4, "0"),
values.month.padStart(2, "0"),
values.day.padStart(2, "0"),
].join("-");
}
} catch {
// Fall through to UTC when the browser cannot resolve the configured timezone.
}
return isoDay(date);
}
function buildTokenUsageCalendar(
days: TokenUsageDay[] | undefined,
monthFormatter: Intl.DateTimeFormat,
timeZone: string | undefined,
): { cells: TokenUsageCell[]; monthLabels: TokenUsageMonthLabel[] } {
const byDate = new Map((days ?? []).map((day) => [day.date, day]));
const today = utcDateFromIsoDay(isoDayInTimeZone(new Date(), timeZone));
const end = addUtcDays(today, 6 - today.getUTCDay());
const start = addUtcDays(end, -(TOKEN_HEATMAP_CELLS - 1));
const monthLabels: TokenUsageMonthLabel[] = [];
const cells = Array.from({ length: TOKEN_HEATMAP_CELLS }, (_, index) => {
const date = addUtcDays(start, index);
const key = isoDay(date);
const row = byDate.get(key);
if (date.getUTCDate() === 1) {
monthLabels.push({
label: monthFormatter.format(date),
column: Math.floor(index / 7) + 1,
});
}
return {
date: key,
total: row?.total_tokens ?? 0,
estimated: row?.estimated_tokens ?? 0,
requests: row?.requests ?? 0,
sources: row?.sources ?? {},
future: date > today,
};
});
return { cells, monthLabels };
}
function tokenUsageSourceLabel(
source: string,
tx: (key: string, fallback: string, values?: Record<string, unknown>) => string,
): string {
if (source === "user") return tx("settings.usage.sources.user", "Chat");
if (source === "api") return tx("settings.usage.sources.api", "API");
if (source === "cron") return tx("settings.usage.sources.cron", "Automations");
if (source === "dream") return tx("settings.usage.sources.dream", "Memory");
return tx("settings.usage.sources.system", "System");
}
function tokenUsageSourceBreakdown(
cell: TokenUsageCell,
tx: (key: string, fallback: string, values?: Record<string, unknown>) => string,
): string {
const known = TOKEN_USAGE_SOURCE_ORDER.filter((source) => cell.sources[source]?.total_tokens > 0);
const extra = Object.keys(cell.sources)
.filter((source) => !TOKEN_USAGE_SOURCE_ORDER.includes(source as typeof TOKEN_USAGE_SOURCE_ORDER[number]))
.filter((source) => cell.sources[source]?.total_tokens > 0)
.sort();
return [...known, ...extra]
.map((source) => {
const label = tokenUsageSourceLabel(source, tx);
const tokens = formatCompactTokens(cell.sources[source]?.total_tokens ?? 0);
return `${label} ${tokens}`;
})
.join(" · ");
}
function formatCompactTokens(tokens: number): string {
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(tokens >= 10_000_000 ? 0 : 1)}M`;
if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(tokens >= 10_000 ? 0 : 1)}K`;
return String(tokens);
}
function tokenUsageLevel(tokens: number, max: number): number {
if (tokens <= 0 || max <= 0) return 0;
const ratio = tokens / max;
if (ratio >= 0.75) return 4;
if (ratio >= 0.45) return 3;
if (ratio >= 0.2) return 2;
return 1;
}
function tokenUsageCellClass(level: number, future: boolean): string {
if (future) return "bg-transparent ring-1 ring-neutral-200/70 dark:ring-white/[0.045]";
if (level === 4) return "bg-sky-300 dark:bg-sky-300";
if (level === 3) return "bg-sky-400/85 dark:bg-sky-500/80";
if (level === 2) return "bg-sky-500/60 dark:bg-sky-700/85";
if (level === 1) return "bg-sky-500/30 dark:bg-sky-900/80";
return "bg-neutral-200/70 ring-1 ring-black/[0.025] dark:bg-white/[0.08] dark:ring-white/[0.035]";
}
export function TokenUsageHeatmap({
usage,
timeZone,
}: {
usage?: TokenUsagePayload;
timeZone?: string;
}) {
const { t, i18n } = useTranslation();
const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>
t(key, { defaultValue: fallback, ...(values ?? {}) });
const monthFormatter = useMemo(
() => new Intl.DateTimeFormat(i18n.language, { month: "short", timeZone: "UTC" }),
[i18n.language],
);
const { cells, monthLabels } = useMemo(
() => buildTokenUsageCalendar(usage?.days, monthFormatter, timeZone),
[monthFormatter, timeZone, usage?.days],
);
const maxTokens = Math.max(0, ...cells.map((cell) => cell.total));
return (
<div className="overflow-x-auto pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<div className="mx-auto w-full min-w-0 max-w-[1054px] px-0.5 sm:min-w-[760px]">
<div className="mb-2 flex justify-end">
<span className="text-[11px] font-normal leading-none text-muted-foreground/64">
{tx("settings.usage.shortTitle", "Token Usage")}
</span>
</div>
<div className="relative mb-2 h-4 text-[10px] font-normal leading-4 text-muted-foreground/62" aria-hidden>
{monthLabels.map((month) => (
<span
key={`${month.label}-${month.column}`}
className="absolute top-0 whitespace-nowrap"
style={{ left: `${((month.column - 1) / TOKEN_HEATMAP_COLUMNS) * 100}%` }}
>
{month.label}
</span>
))}
</div>
<div
className="grid grid-flow-col grid-rows-7 gap-[3px] sm:gap-1.5"
style={{ gridTemplateColumns: `repeat(${TOKEN_HEATMAP_COLUMNS}, minmax(0, 1fr))` }}
aria-label={tx("settings.usage.title", "Token activity")}
>
<TooltipProvider delayDuration={120} skipDelayDuration={80}>
{cells.map((cell) => {
const level = tokenUsageLevel(cell.total, maxTokens);
const baseLabel = cell.future
? cell.date
: tx("settings.usage.cellTitle", "{{date}}: {{tokens}} tokens, {{requests}} requests", {
date: cell.date,
tokens: formatCompactTokens(cell.total),
requests: cell.requests,
});
const label = cell.future || cell.estimated <= 0
? baseLabel
: `${baseLabel} · ${
cell.estimated >= cell.total
? tx("settings.usage.estimated", "estimated")
: tx("settings.usage.includesEstimates", "includes estimates")
}`;
const breakdown = cell.future ? "" : tokenUsageSourceBreakdown(cell, tx);
const ariaLabel = breakdown ? `${label} · ${breakdown}` : label;
return (
<Tooltip key={cell.date}>
<TooltipTrigger asChild>
<span
aria-label={ariaLabel}
className={cn(
"aspect-square w-full rounded-mark transition-transform hover:scale-110",
tokenUsageCellClass(level, cell.future),
)}
/>
</TooltipTrigger>
<TooltipContent
side="top"
align="center"
className="px-2.5 py-1.5 text-[11px] font-normal"
>
<span className="block">{label}</span>
{breakdown ? (
<span className="mt-1 block text-muted-foreground">{breakdown}</span>
) : null}
</TooltipContent>
</Tooltip>
);
})}
</TooltipProvider>
</div>
</div>
</div>
);
}
@@ -0,0 +1,106 @@
import { useTranslation } from "react-i18next";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import type { SettingsPayload } from "@/lib/types";
import { cn } from "@/lib/utils";
type Usage = NonNullable<SettingsPayload["usage"]>;
const COLORS = ["bg-orange-500", "bg-amber-500", "bg-stone-500", "bg-orange-300", "bg-zinc-400", "bg-neutral-200 dark:bg-neutral-600"];
export function TokenUsageModelTrend({ days, modelDays, models }: {
days: { date: string; usage?: Usage["days"][number] }[];
modelDays: NonNullable<Usage["model_days_30d"]>;
models?: Usage["providers_30d"];
}) {
const { t, i18n } = useTranslation();
const number = new Intl.NumberFormat(i18n.language);
const percent = new Intl.NumberFormat(i18n.language, { style: "percent", maximumFractionDigits: 1 });
const total = days.reduce((sum, day) => sum + (day.usage?.total_tokens ?? 0), 0);
const modelUsage = new Map((models ?? []).map(model => [JSON.stringify([model.provider, model.model]), model]));
const compact = new Intl.NumberFormat(i18n.language, { notation: "compact", maximumFractionDigits: 1 });
const dates = new Set(days.map(day => day.date));
const totals = new Map<string, { label: string; total: number }>();
const daily = new Map<string, Map<string, number>>();
for (const row of modelDays) {
if (!dates.has(row.date) || row.total_tokens <= 0) continue;
const key = JSON.stringify([row.provider, row.model]);
const item = totals.get(key) ?? { label: row.model, total: 0 };
item.total += row.total_tokens;
totals.set(key, item);
const bucket = daily.get(row.date) ?? new Map<string, number>();
bucket.set(key, (bucket.get(key) ?? 0) + row.total_tokens);
daily.set(row.date, bucket);
}
const series = [...totals].sort((a, b) => b[1].total - a[1].total).slice(0, 5);
const otherLabel = t("settings.usage.otherModels", { defaultValue: "Other / unattributed" });
const columns = days.map(day => {
const bucket = daily.get(day.date);
const values = series.map(([key]) => bucket?.get(key) ?? 0);
const total = day.usage?.total_tokens ?? 0;
return { date: day.date, total, requests: day.usage?.requests ?? 0, values: [...values, Math.max(0, total - values.reduce((a, b) => a + b, 0))] };
});
const peak = Math.max(0, ...columns.map(column => column.total));
if (!peak || !series.length) return null;
const labels = [...series.map(([, item]) => item.label), otherLabel];
const color = (index: number) => index === series.length ? COLORS[5] : COLORS[index];
const hasOther = columns.some(column => column.values[series.length] > 0);
const title = t("settings.usage.modelTrend", { defaultValue: "Model usage over time" });
return <section className="mt-2">
<h3 className="mb-4 text-sm font-medium">{title}</h3>
<div className="relative pl-9">
<div className="pointer-events-none absolute inset-y-0 left-0 right-0 flex flex-col justify-between pb-6" aria-hidden>
{[peak, peak / 2, 0].map((value, index) => <div key={index} className="flex items-center gap-2"><span className="w-7 shrink-0 text-right text-[10px] tabular-nums text-muted-foreground">{compact.format(value)}</span><span className="flex-1 border-t border-border/40" /></div>)}
</div>
<div role="group" aria-label={title} className="relative grid h-[clamp(144px,30vh,280px)] grid-cols-[repeat(30,minmax(0,1fr))] gap-px">
<TooltipProvider>
{columns.map(column => column.total === 0 ? (
<span key={column.date} role="img" aria-label={`${column.date}: ${number.format(0)} tokens`} />
) : <Tooltip key={column.date}>
<TooltipTrigger asChild>
<span role="img" tabIndex={0} aria-label={`${column.date}: ${number.format(column.total)} tokens; ${column.values.map((value, index) => `${labels[index]}: ${number.format(value)}`).join(", ")}`} className="flex min-w-0 items-end focus-visible:outline focus-visible:outline-2 focus-visible:outline-orange-500">
<span className="flex w-full flex-col-reverse" style={{ height: `${column.total / peak * 100}%` }}>
{column.values.map((value, index) => value > 0 && <span key={index} className={cn("w-full shrink-0", color(index))} style={{ height: `${value / column.total * 100}%` }} />)}
</span>
</span>
</TooltipTrigger>
<TooltipContent className="w-72 max-w-[85vw] p-3">
<p className="mb-2 text-xs font-medium">{column.date}</p>
<dl className="space-y-2">
{column.values.map((value, index) => ({ value, index })).filter(item => item.value > 0).sort((a, b) => b.value - a.value).map(({ value, index }) => <div key={index} className="flex items-start justify-between gap-3 text-xs">
<dt className="flex min-w-0 items-start gap-2"><span aria-hidden className={cn("mt-0.5 h-3 w-1 shrink-0 rounded-full", color(index))} /><span className="break-words">{labels[index]}</span></dt><dd className="shrink-0 tabular-nums">{number.format(value)}</dd>
</div>)}
<div className="flex justify-between border-t border-border/50 pt-2 text-xs font-medium"><dt>{t("settings.usage.totalTokens", { defaultValue: "Total tokens" })}</dt><dd className="tabular-nums">{number.format(column.total)}</dd></div>
<div className="flex justify-between text-xs text-muted-foreground"><dt>{t("settings.usage.requests")}</dt><dd className="tabular-nums">{number.format(column.requests)}</dd></div>
</dl>
</TooltipContent>
</Tooltip>)}
</TooltipProvider>
</div>
<div className="relative mt-2 flex justify-between text-[10px] tabular-nums text-muted-foreground"><span>{days[0].date.slice(5)}</span><span>{days[14].date.slice(5)}</span><span>{days[days.length - 1].date.slice(5)}</span></div>
</div>
<TooltipProvider>
<div className="mt-4 grid grid-cols-2 gap-x-4 gap-y-2 text-[11px] text-muted-foreground sm:grid-cols-3">
{labels.map((label, index) => {
if (index === series.length && !hasOther) return null;
const model = index < series.length ? modelUsage.get(series[index][0]) : undefined;
const tokens = columns.reduce((sum, column) => sum + column.values[index], 0);
const rate = model?.cache_read_observed_input_tokens ? percent.format(model.cache_read_tokens / model.cache_read_observed_input_tokens) : "—";
const parts = [
[t("settings.usage.totalTokens"), `${number.format(tokens)} · ${percent.format(tokens / total)}`],
[t("settings.usage.cacheHitRate"), rate],
];
return <Tooltip key={index}>
<TooltipTrigger asChild>
<span tabIndex={0} aria-label={`${label}: ${parts.map(([name, value]) => `${name}: ${value}`).join(", ")}`} className="flex min-w-0 items-center gap-1.5 rounded-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-orange-500">
<span aria-hidden className={cn("size-2 shrink-0 rounded-sm", color(index))} /><span className="truncate">{label}</span>
</span>
</TooltipTrigger>
<TooltipContent className="max-w-[85vw] p-3">
<p className="mb-2 break-all text-xs font-medium">{label}</p>
<dl className="space-y-2">{parts.map(([name, value]) => <div key={name} className="flex justify-between gap-6 text-xs"><dt className="text-muted-foreground">{name}</dt><dd className="tabular-nums">{value}</dd></div>)}</dl>
</TooltipContent>
</Tooltip>;
})}
</div>
</TooltipProvider>
</section>;
}
@@ -1,4 +1,6 @@
import type { Dispatch, SetStateAction } from "react";
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import type { Dispatch, SetStateAction, ReactNode } from "react";
import { SettingsAdvancedOptions } from "@/components/settings/shared/SettingsFeature";
import { useTranslation } from "react-i18next";
import { ModelIdPicker, ProviderPicker, optionRowsWithCurrent } from "@/components/settings/shared/ModelControls";
@@ -39,6 +41,9 @@ export function imageGenerationFormFromPayload(payload: SettingsPayload): ImageG
}
export function ImageGenerationSettings({
embedded = false,
error,
children,
token,
settings,
form,
@@ -52,6 +57,9 @@ export function ImageGenerationSettings({
isRestarting,
requiresRestartPending,
}: {
embedded?: boolean;
error?: string;
children?: ReactNode;
token: string;
settings: SettingsPayload;
form: ImageGenerationSettingsUpdate;
@@ -72,6 +80,7 @@ export function ImageGenerationSettings({
settings.image_generation.providers[0];
const providerConfigured = !!selectedProvider?.configured;
const missingCredential = form.enabled && !providerConfigured;
useAutoSave(form, dirty, saving, onSave, !embedded && !missingCredential);
const aspectOptions = optionRowsWithCurrent(
IMAGE_ASPECT_RATIO_OPTIONS.map((value) => ({ name: value, label: value })),
form.defaultAspectRatio,
@@ -90,10 +99,11 @@ export function ImageGenerationSettings({
};
return (
<div className="space-y-7">
<div className="settings-stack">
<section>
<SettingsSectionTitle>{tx("settings.sections.imageGeneration", "Image generation")}</SettingsSectionTitle>
{!embedded ? <SettingsSectionTitle>{tx("settings.sections.imageGeneration", "Image generation")}</SettingsSectionTitle> : null}
<SettingsGroup>
{!embedded ? (
<SettingsRow title={tx("settings.rows.imageGeneration", "Image generation")}>
<ToggleButton
checked={form.enabled}
@@ -102,6 +112,8 @@ export function ImageGenerationSettings({
label={form.enabled ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
/>
</SettingsRow>
) : null}
{embedded || form.enabled ? <>
<SettingsRow title={tx("settings.rows.imageProvider", "Image provider")}>
<ProviderPicker
providers={settings.image_generation.providers}
@@ -128,17 +140,11 @@ export function ImageGenerationSettings({
) : null}
</div>
</SettingsRow>
<SettingsRow title={tx("settings.rows.imageProviderBase", "Provider base")}>
<SettingsRow title={tx("settings.rows.imageProviderBase", "Provider URL")}>
<span className="max-w-[320px] truncate text-right text-[13px] text-muted-foreground">
{selectedProvider?.api_base || selectedProvider?.default_api_base || selectedProvider?.name || tx("settings.values.notAvailable", "Not available")}
</span>
</SettingsRow>
</SettingsGroup>
</section>
<section>
<SettingsSectionTitle>{tx("settings.sections.imageDefaults", "Defaults")}</SettingsSectionTitle>
<SettingsGroup>
<SettingsRow title={tx("settings.rows.imageModel", "Image model")}>
<ModelIdPicker
token={token}
@@ -159,7 +165,7 @@ export function ImageGenerationSettings({
onChange={(model) => onChangeForm((prev) => ({ ...prev, model }))}
/>
</SettingsRow>
<SettingsRow title={tx("settings.rows.defaultAspectRatio", "Default aspect")}>
<SettingsRow title={tx("settings.rows.defaultAspectRatio", "Default aspect ratio")}>
<ProviderPicker
providers={aspectOptions}
value={form.defaultAspectRatio}
@@ -179,7 +185,8 @@ export function ImageGenerationSettings({
}
/>
</SettingsRow>
<SettingsRow title={tx("settings.rows.maxImagesPerTurn", "Max images per turn")}>
<SettingsAdvancedOptions>
<SettingsRow title={tx("settings.rows.maxImagesPerTurn", "Max images per request")}>
<NumberInput
value={form.maxImagesPerTurn}
min={1}
@@ -189,19 +196,26 @@ export function ImageGenerationSettings({
}
/>
</SettingsRow>
<ReadOnlyRow title={tx("settings.rows.imageSaveDir", "Save directory")} value={settings.image_generation.save_dir} />
{!settings.runtime_config ? (
<ReadOnlyRow title={tx("settings.rows.imageSaveDir", "Save directory")} value={settings.image_generation.save_dir} />
) : null}
{children}
</SettingsAdvancedOptions>
</> : null}
<RestartSettingsFooter
error={missingCredential || Boolean(error)}
autoSave
dirty={dirty}
saving={saving}
pendingRestart={requiresRestartPending}
pendingRestart={!embedded && requiresRestartPending}
disabled={missingCredential}
message={
missingCredential
? tx("settings.image.missingCredential", "Configure this provider before enabling image generation.")
: undefined
: error
}
dirtyMessage={tx("settings.status.restartAfterSaving", "Save changes, then restart when ready.")}
pendingMessage={tx("settings.status.savedRestartApply", "Saved. Restart when ready.")}
dirtyMessage={tx("settings.status.restartAfterSaving", "Save changes, then restart nanobot to apply them.")}
pendingMessage={tx("settings.status.savedRestartApply", "Saved. Restart to apply changes.")}
onSave={onSave}
onRestart={onRestart}
isRestarting={isRestarting}
@@ -1,3 +1,4 @@
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import type { Dispatch, SetStateAction } from "react";
import { useTranslation } from "react-i18next";
@@ -37,6 +38,7 @@ export function visibleWebuiDefaultAccessMode(mode: string | null | undefined):
}
export function AdvancedSettings({
error,
form,
dirty,
saving,
@@ -47,6 +49,7 @@ export function AdvancedSettings({
onRestart,
isRestarting,
}: {
error?: string;
form: NetworkSafetySettingsUpdate;
dirty: boolean;
saving: boolean;
@@ -58,9 +61,10 @@ export function AdvancedSettings({
isRestarting?: boolean;
}) {
const { t } = useTranslation();
useAutoSave(form, dirty, saving, onSave);
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
return (
<div className="space-y-7">
<div className="settings-stack">
<section>
<SettingsSectionTitle>
{isNativeHostSurface
@@ -110,6 +114,9 @@ export function AdvancedSettings({
/>
</SettingsRow>
<RestartSettingsFooter
autoSave
error={Boolean(error)}
message={error}
dirty={dirty}
saving={saving}
pendingRestart={requiresRestartPending}
@@ -120,12 +127,6 @@ export function AdvancedSettings({
</SettingsGroup>
</section>
<p className="max-w-3xl px-1 text-sm leading-6 text-muted-foreground">
{tx(
"settings.help.securityManagedControls",
"Web fetches always protect local, private, and metadata services. Core channel safety stays in config.json.",
)}
</p>
</div>
);
}
@@ -1,3 +1,5 @@
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { SettingsAdvancedOptions } from "@/components/settings/shared/SettingsFeature";
import type { Dispatch, SetStateAction } from "react";
import { useTranslation } from "react-i18next";
@@ -48,6 +50,8 @@ export function transcriptionFormFromPayload(payload: SettingsPayload): Transcri
}
export function TranscriptionSettings({
embedded = false,
error,
settings,
form,
dirty,
@@ -60,6 +64,8 @@ export function TranscriptionSettings({
isRestarting,
requiresRestartPending,
}: {
embedded?: boolean;
error?: string;
settings: SettingsPayload;
form: TranscriptionSettingsUpdate;
dirty: boolean;
@@ -73,6 +79,7 @@ export function TranscriptionSettings({
requiresRestartPending: boolean;
}) {
const { t } = useTranslation();
useAutoSave(form, dirty, saving, onSave, !embedded);
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const transcription = settings.transcription ?? DEFAULT_TRANSCRIPTION_SETTINGS;
const selectedProvider =
@@ -82,8 +89,9 @@ export function TranscriptionSettings({
return (
<section>
<SettingsSectionTitle>{tx("settings.sections.voiceInput", "Voice input")}</SettingsSectionTitle>
{!embedded ? <SettingsSectionTitle>{tx("settings.sections.voiceInput", "Voice input")}</SettingsSectionTitle> : null}
<SettingsGroup>
{!embedded ? (
<SettingsRow
title={tx("settings.rows.transcription", "Transcription")}
description={tx("settings.help.transcription", "Transcribe microphone input before sending it. Chat channel voice messages use the same settings.")}
@@ -95,6 +103,8 @@ export function TranscriptionSettings({
label={form.enabled ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
/>
</SettingsRow>
) : null}
{embedded || form.enabled ? <>
<SettingsRow title={tx("settings.rows.transcriptionProvider", "Provider")}>
<ProviderPicker
providers={transcription.providers}
@@ -123,27 +133,28 @@ export function TranscriptionSettings({
</SettingsRow>
<SettingsRow
title={tx("settings.rows.transcriptionModel", "Model")}
description={tx("settings.help.transcriptionModel", "Leave as the resolved default unless your provider needs a custom model id.")}
description={tx("settings.help.transcriptionModel", "Keep the default model unless your provider requires a specific model ID.")}
>
<Input
value={form.model}
onChange={(event) => onChangeForm((prev) => ({ ...prev, model: event.target.value }))}
className="h-8 w-[min(300px,70vw)] rounded-full text-[13px]"
className="h-9 w-full rounded-full text-end text-[13px]"
/>
</SettingsRow>
<SettingsRow
title={tx("settings.rows.transcriptionLanguage", "Language")}
description={tx("settings.help.transcriptionLanguage", "Optional ISO-639 hint such as en, zh, ja, or ko.")}
description={tx("settings.help.transcriptionLanguage", "Optional language code, such as en for English, zh for Chinese, ja for Japanese, or ko for Korean.")}
>
<Input
value={form.language}
onChange={(event) => onChangeForm((prev) => ({ ...prev, language: event.target.value }))}
placeholder={tx("settings.voice.languageAuto", "Auto")}
className="h-8 w-[min(180px,60vw)] rounded-full text-[13px]"
className="h-9 w-full rounded-full text-end text-[13px]"
/>
</SettingsRow>
<SettingsAdvancedOptions>
<SettingsRow title={tx("settings.rows.voiceLimits", "Limits")}>
<div className="flex flex-wrap justify-end gap-2">
<div className="grid w-full gap-2">
<NumberInput
value={form.maxDurationSec}
min={1}
@@ -160,12 +171,17 @@ export function TranscriptionSettings({
/>
</div>
</SettingsRow>
</SettingsAdvancedOptions>
</> : null}
<RestartSettingsFooter
error={Boolean(error)}
message={error}
autoSave
dirty={dirty}
saving={saving}
pendingRestart={requiresRestartPending}
dirtyMessage={tx("settings.status.restartAfterSaving", "Save changes, then restart when ready.")}
pendingMessage={tx("settings.status.savedRestartApply", "Saved. Restart when ready.")}
pendingRestart={!embedded && requiresRestartPending}
dirtyMessage={tx("settings.status.restartAfterSaving", "Save changes, then restart nanobot to apply them.")}
pendingMessage={tx("settings.status.savedRestartApply", "Saved. Restart to apply changes.")}
onSave={onSave}
onRestart={onRestart}
isRestarting={isRestarting}
@@ -1,3 +1,5 @@
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { SettingsAdvancedOptions } from "@/components/settings/shared/SettingsFeature";
import type { Dispatch, SetStateAction } from "react";
import { Eye, EyeOff, Pencil } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -54,7 +56,28 @@ export function webSearchProviderRequiresApiKey(provider?: WebSearchProviderOpti
return provider?.credential === "api_key";
}
export function webSearchDraftState(settings: SettingsPayload, form: WebSearchSettingsUpdate) {
const provider = settings.web_search.providers.find((row) => row.name === form.provider);
const apiKey = form.apiKey?.trim() ?? "";
const baseUrl = form.baseUrl?.trim() ?? "";
const hasExistingSecret = webSearchProviderAcceptsApiKey(provider) &&
form.provider === settings.web_search.provider && Boolean(settings.web_search.api_key_hint);
const jinaReaderDirty = (form.useJinaReader ?? settings.web.fetch.use_jina_reader) !== settings.web.fetch.use_jina_reader;
return {
hasExistingSecret,
jinaReaderDirty,
dirty: form.provider !== settings.web_search.provider || apiKey.length > 0 ||
baseUrl !== (settings.web_search.base_url ?? "") || form.maxResults !== settings.web_search.max_results ||
form.timeout !== settings.web_search.timeout || jinaReaderDirty,
missingCredential: webSearchProviderRequiresApiKey(provider) ? !apiKey && !hasExistingSecret
: provider?.credential === "base_url" ? !baseUrl : false,
};
}
export function WebSettings({
embedded = false,
error,
enabled = true,
settings,
form,
keyVisible,
@@ -74,6 +97,9 @@ export function WebSettings({
olostepInstalling,
capabilityError,
}: {
embedded?: boolean;
error?: string;
enabled?: boolean;
settings: SettingsPayload;
form: WebSearchSettingsUpdate;
keyVisible: boolean;
@@ -98,40 +124,24 @@ export function WebSettings({
const selectedProvider =
settings.web_search.providers.find((provider) => provider.name === form.provider) ??
settings.web_search.providers[0];
const hasExistingSecret =
webSearchProviderAcceptsApiKey(selectedProvider) &&
form.provider === settings.web_search.provider &&
!!settings.web_search.api_key_hint;
const showKeyInput = webSearchProviderAcceptsApiKey(selectedProvider) && (!hasExistingSecret || keyEditing);
const apiKey = form.apiKey?.trim() ?? "";
const baseUrl = form.baseUrl?.trim() ?? "";
const { hasExistingSecret, dirty, jinaReaderDirty, missingCredential } = webSearchDraftState(settings, form);
const effectiveJinaReader = form.useJinaReader ?? settings.web.fetch.use_jina_reader;
const dirty =
form.provider !== settings.web_search.provider ||
apiKey.length > 0 ||
baseUrl !== (settings.web_search.base_url ?? "") ||
form.maxResults !== settings.web_search.max_results ||
form.timeout !== settings.web_search.timeout ||
effectiveJinaReader !== settings.web.fetch.use_jina_reader;
const jinaReaderDirty = effectiveJinaReader !== settings.web.fetch.use_jina_reader;
const missingCredential =
webSearchProviderRequiresApiKey(selectedProvider)
? !apiKey && !hasExistingSecret
: selectedProvider?.credential === "base_url"
? !baseUrl
: false;
const showKeyInput = webSearchProviderAcceptsApiKey(selectedProvider) && (!hasExistingSecret || keyEditing);
useAutoSave(form, dirty, saving, onSave, !embedded && !missingCredential && (form.provider !== "olostep" || olostepFeature?.installed === true));
return (
<div className="space-y-7">
<div className="settings-stack">
<section>
<SettingsSectionTitle>{tx("settings.sections.webSearch", "Web search")}</SettingsSectionTitle>
{enabled && !embedded ? <SettingsSectionTitle>{tx("settings.sections.webSearch", "Web search")}</SettingsSectionTitle> : null}
<div hidden={!embedded && !enabled}>
{form.provider === "olostep" && olostepFeature && !olostepFeature.installed ? (
<div className="mb-3">
<CapabilityInstallNotice
title={tx("settings.capabilities.searchSupport", "Search provider support")}
title={tx("settings.capabilities.searchSupport", "Search dependencies")}
description={tx(
"settings.capabilities.searchInstallOnSave",
"Olostep support will be installed automatically when you save.",
"Required Olostep packages will be installed automatically when you save.",
)}
installing={olostepInstalling}
/>
@@ -140,7 +150,9 @@ export function WebSettings({
{capabilityError ? (
<p className="mb-3 text-[12px] text-destructive">{capabilityError}</p>
) : null}
</div>
<SettingsGroup>
<div hidden={!embedded && !enabled} className="space-y-1">
<SettingsRow title={t("settings.byok.webSearch.provider")}>
<ProviderPicker
providers={settings.web_search.providers}
@@ -162,7 +174,7 @@ export function WebSettings({
title={t("settings.byok.apiKey")}
description={t("settings.byok.webSearch.apiKeyHelp")}
>
<div className="relative w-[280px] max-w-full">
<div className="relative w-full">
{showKeyInput ? (
<>
<Input
@@ -186,7 +198,7 @@ export function WebSettings({
aria-label={
keyVisible ? t("settings.byok.hideApiKey") : t("settings.byok.showApiKey")
}
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 rounded-full text-muted-foreground settings-hover hover:text-foreground"
>
{keyVisible ? (
<EyeOff className="h-3.5 w-3.5" aria-hidden />
@@ -206,7 +218,7 @@ export function WebSettings({
size="icon"
onClick={onToggleKeyEditing}
aria-label={t("settings.actions.edit")}
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 rounded-full text-muted-foreground settings-hover hover:text-foreground"
>
<Pencil className="h-3.5 w-3.5" aria-hidden />
</Button>
@@ -227,16 +239,11 @@ export function WebSettings({
onChangeForm((prev) => ({ ...prev, baseUrl: event.target.value }))
}
placeholder={t("settings.byok.webSearch.baseUrlPlaceholder")}
className="h-9 w-[280px] rounded-full text-[13px]"
className="h-9 w-full rounded-full text-[13px]"
/>
</SettingsRow>
) : null}
</SettingsGroup>
</section>
<section>
<SettingsSectionTitle>{tx("settings.sections.webBehavior", "Behavior")}</SettingsSectionTitle>
<SettingsGroup>
<SettingsAdvancedOptions>
<SettingsRow title={tx("settings.rows.maxResults", "Max results")}>
<NumberInput
value={form.maxResults ?? settings.web_search.max_results}
@@ -256,7 +263,7 @@ export function WebSettings({
</SettingsRow>
<SettingsRow
title={tx("settings.rows.jinaReader", "Jina reader")}
description={tx("settings.help.jinaReader", "Use Jina Reader for web_fetch when available.")}
description={tx("settings.help.jinaReader", "Use Jina Reader to read web pages when available.")}
>
<ToggleButton
checked={effectiveJinaReader}
@@ -265,21 +272,26 @@ export function WebSettings({
label={effectiveJinaReader ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
/>
</SettingsRow>
</SettingsAdvancedOptions>
</div>
<RestartSettingsFooter
error={missingCredential || Boolean(error)}
autoSave={form.provider !== "olostep" || olostepFeature?.installed === true}
saveLabel={t("settings.nanobotFeatures.installConfirmAction")}
dirty={dirty}
saving={saving}
pendingRestart={requiresRestartPending}
pendingRestart={!embedded && requiresRestartPending}
disabled={missingCredential}
message={
missingCredential
? t("settings.byok.webSearch.missingCredential")
: requiresRestartPending && !dirty
? tx("settings.status.savedRestartApply", "Saved. Restart when ready.")
: error || (!embedded && requiresRestartPending && !dirty
? tx("settings.status.savedRestartApply", "Saved. Restart to apply changes.")
: jinaReaderDirty
? tx("settings.status.restartAfterSaving", "Save changes, then restart when ready.")
? tx("settings.status.restartAfterSaving", "Save changes, then restart nanobot to apply them.")
: dirty
? t("settings.byok.webSearch.saveHint")
: undefined
: undefined)
}
onSave={onSave}
onRestart={onRestart}
@@ -19,6 +19,9 @@ import {
} from "@/lib/api";
import type { NanobotClient } from "@/lib/nanobot-client";
import type { SettingsPayload, WebSearchSettingsUpdate } from "@/lib/types";
import { imageGenerationFormFromPayload } from "@/components/settings/capabilities/ImageGenerationSettings";
import { transcriptionFormFromPayload } from "@/components/settings/capabilities/TranscriptionSettings";
import { networkSafetyFormFromPayload } from "@/components/settings/capabilities/SecuritySettings";
interface CapabilitySettingsActionsOptions {
state: CapabilitySettingsState;
@@ -28,7 +31,6 @@ interface CapabilitySettingsActionsOptions {
applyPayload: ApplySettingsPayload;
maybeRestartHostEngine: MaybeRestartHostEngine;
setPendingRestartSections: Dispatch<SetStateAction<PendingRestartSections>>;
setError: Dispatch<SetStateAction<string | null>>;
installCapabilities: (names: string[]) => Promise<boolean>;
imageGenerationDirty: boolean;
transcriptionDirty: boolean;
@@ -43,7 +45,6 @@ export function useCapabilitySettingsActions({
applyPayload,
maybeRestartHostEngine,
setPendingRestartSections,
setError,
installCapabilities,
imageGenerationDirty,
transcriptionDirty,
@@ -67,20 +68,29 @@ export function useCapabilitySettingsActions({
webSearchKeyEditing,
webSearchSaving,
} = state;
const setError = (section: "image" | "voice" | "web" | "safety", message?: string) =>
state.setCapabilityErrors((prev) => ({ ...prev, [section]: message }));
const saveImageGenerationSettings = async () => {
if (!settings || !imageGenerationDirty || imageGenerationSaving) return;
if (imageGenerationForm.enabled && !settings.image_generation.providers.find(
(provider) => provider.name === imageGenerationForm.provider,
)?.configured) return;
setError("image");
setImageGenerationSaving(true);
try {
const payload = await updateImageGenerationSettings(client, imageGenerationForm);
applyPayload(payload);
if (payload.requires_restart) {
applyPayload(payload, { preserveCapabilityForms: true });
state.setImageGenerationForm(imageGenerationFormFromPayload(payload));
if (!payload.restart_required_sections && payload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, image: true }));
}
await maybeRestartHostEngine(payload);
setError(null);
setError("image");
} catch (err) {
setError((err as Error).message);
const message = (err as Error).message;
setError("image", message === "image generation provider is not configured"
? t("settings.image.missingCredential") : message);
} finally {
setImageGenerationSaving(false);
}
@@ -88,17 +98,19 @@ export function useCapabilitySettingsActions({
const saveTranscriptionSettings = async () => {
if (!settings || !transcriptionDirty || transcriptionSaving) return;
setError("voice");
setTranscriptionSaving(true);
try {
const payload = await updateTranscriptionSettings(client, transcriptionForm);
applyPayload(payload);
if (payload.requires_restart) {
applyPayload(payload, { preserveCapabilityForms: true });
state.setTranscriptionForm(transcriptionFormFromPayload(payload));
if (!payload.restart_required_sections && payload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, browser: true }));
}
await maybeRestartHostEngine(payload);
setError(null);
setError("voice");
} catch (err) {
setError((err as Error).message);
setError("voice", (err as Error).message);
} finally {
setTranscriptionSaving(false);
}
@@ -106,17 +118,19 @@ export function useCapabilitySettingsActions({
const saveNetworkSafetySettings = async () => {
if (!settings || !networkSafetyDirty || networkSafetySaving) return;
setError("safety");
setNetworkSafetySaving(true);
try {
const payload = await updateNetworkSafetySettings(client, networkSafetyForm);
applyPayload(payload);
if (payload.requires_restart) {
applyPayload(payload, { preserveCapabilityForms: true });
state.setNetworkSafetyForm(networkSafetyFormFromPayload(payload));
if (!payload.restart_required_sections && payload.requires_restart) {
setPendingRestartSections((prev) => ({ ...prev, runtime: true }));
}
await maybeRestartHostEngine(payload);
setError(null);
setError("safety");
} catch (err) {
setError((err as Error).message);
setError("safety", (err as Error).message);
} finally {
setNetworkSafetySaving(false);
}
@@ -134,14 +148,13 @@ export function useCapabilitySettingsActions({
!!settings.web_search.api_key_hint;
if (webSearchProviderRequiresApiKey(provider) && !apiKey && !hasExistingSecret) {
setError(t("settings.byok.webSearch.apiKeyRequired"));
return;
}
if (provider.credential === "base_url" && !baseUrl) {
setError(t("settings.byok.webSearch.baseUrlRequired"));
return;
}
setError("web");
setWebSearchSaving(true);
try {
if (provider.name === "olostep" && !(await installCapabilities(["olostep"]))) return;
@@ -162,8 +175,8 @@ export function useCapabilitySettingsActions({
}
if (provider.credential === "base_url") update.baseUrl = baseUrl;
const payload = await updateWebSearchSettings(client, update);
applyPayload(payload);
if (payload.requires_restart || webFetchRestartRequired) {
applyPayload(payload, { preserveCapabilityForms: true });
if (!payload.restart_required_sections && (payload.requires_restart || webFetchRestartRequired)) {
setPendingRestartSections((prev) => ({ ...prev, browser: true }));
}
await maybeRestartHostEngine(payload);
@@ -177,9 +190,9 @@ export function useCapabilitySettingsActions({
}));
setWebSearchKeyVisible(false);
setWebSearchKeyEditing(false);
setError(null);
setError("web");
} catch (err) {
setError((err as Error).message);
setError("web", (err as Error).message);
} finally {
setWebSearchSaving(false);
}
@@ -25,6 +25,7 @@ import type {
} from "@/lib/types";
export function useCapabilitySettingsState(initialSettings: SettingsPayload | null) {
const [capabilityErrors, setCapabilityErrors] = useState<Partial<Record<"image" | "voice" | "web" | "safety", string>>>({});
const [webSearchSaving, setWebSearchSaving] = useState(false);
const [imageGenerationSaving, setImageGenerationSaving] = useState(false);
const [transcriptionSaving, setTranscriptionSaving] = useState(false);
@@ -47,6 +48,8 @@ export function useCapabilitySettingsState(initialSettings: SettingsPayload | nu
const [webSearchKeyEditing, setWebSearchKeyEditing] = useState(false);
return {
capabilityErrors,
setCapabilityErrors,
imageGenerationForm,
imageGenerationSaving,
networkSafetyForm,
@@ -133,6 +133,14 @@ export function ChannelLogo({
const logoUrls = useMemo(() => logoFallbackUrls(presentation?.logoUrl), [presentation?.logoUrl]);
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(logoUrls);
if (feature.name === "websocket") {
return (
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-control bg-background">
<img src="/brand/nanobot_mark.svg" alt="" className="h-6 w-6 object-contain" draggable={false} />
</span>
);
}
if (showBrandLogos && logoUrl) {
return (
<span
@@ -135,7 +135,7 @@ export function ChannelInstancesPanel({
if (payload.nanobot_features) {
onFeaturesUpdate(payload.nanobot_features);
}
setNotice(tx("settings.channels.savedSettings", "Saved settings."));
setNotice(tx("settings.channels.savedSettings", "Settings saved."));
} catch (err) {
setNotice((err as Error).message);
} finally {
@@ -180,7 +180,7 @@ export function ChannelInstancesPanel({
"overflow-hidden rounded-floating transition-colors",
expanded
? "bg-background"
: "bg-background/70 hover:bg-muted",
: "bg-background/70 settings-hover",
)}
>
<div className="flex items-center gap-3 px-3 py-3">
@@ -291,7 +291,7 @@ export function ChannelInstancesPanel({
type="submit"
size="sm"
variant="secondary"
className="h-8 rounded-full bg-muted/70 px-3 text-[12px] font-semibold hover:bg-muted"
className="h-8 rounded-full bg-muted/70 px-3 text-[12px] font-semibold settings-hover"
disabled={savingFields}
>
{savingFields ? (
@@ -316,7 +316,7 @@ export function ChannelQrConnectFlow({
type="button"
size="sm"
variant="outline"
className="h-8 rounded-full border-border/65 bg-background/80 px-3 text-[12px] font-semibold hover:bg-muted/70"
className="h-8 rounded-full border-border/65 bg-background/80 px-3 text-[12px] font-semibold settings-hover"
onClick={() => void start(forceOnRepeat && succeeded)}
disabled={!canStart}
>
@@ -8,7 +8,6 @@ import {
import {
Check,
ChevronDown,
ChevronRight,
Clipboard,
Loader2,
Plus,
@@ -31,7 +30,6 @@ import {
ChannelLogo,
ChannelRuntimeError,
ChannelStatusBadge,
channelDescription,
channelRequirements,
channelSetup,
channelStatusLabel,
@@ -64,31 +62,36 @@ import { useClient } from "@/providers/ClientProvider";
export function ChannelCatalogRow({
feature,
selected,
showBrandLogos,
onSelect,
actionKey,
onAction,
}: {
feature: NanobotFeatureInfo;
selected: boolean;
showBrandLogos: boolean;
onSelect: () => void;
onSelect: (connect?: boolean) => void;
actionKey: string | null;
onAction: (action: "enable" | "disable", name: string) => void;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const displayName = localizedChannelDisplayName(feature, t);
const alwaysEnabled = feature.capabilities?.includes("always_enabled") ?? false;
const checked = alwaysEnabled || channelToggleChecked(feature);
const busy = actionKey === `enable:${feature.name}` || actionKey === `disable:${feature.name}`;
return (
<div className="settings-list-row flex items-center gap-3 py-2.5 transition-colors settings-hover">
<button
type="button"
aria-label={t("settings.channels.selectChannel", {
name: displayName,
defaultValue: "View {{name}} settings",
})}
aria-pressed={selected}
onClick={onSelect}
aria-haspopup="dialog"
onClick={() => onSelect()}
className={cn(
"group flex w-full min-w-0 items-center gap-3 rounded-control px-3 py-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border/80",
selected ? "bg-background" : "hover:bg-muted",
"group flex min-w-0 flex-1 select-none items-center gap-3 rounded-control text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border/80",
)}
>
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
@@ -96,23 +99,24 @@ export function ChannelCatalogRow({
<h3 className="truncate text-[14px] font-semibold leading-5 text-foreground">
{displayName}
</h3>
<p className="mt-0.5 truncate text-[12.5px] leading-5 text-muted-foreground">
{channelDescription(feature, t)}
</p>
</div>
</button>
<div className="flex shrink-0 items-center gap-2">
{feature.runtime_status === "failed" ? (
<ChannelStatusBadge status={feature.runtime_status}>
{channelStatusLabel(feature, tx)}
</ChannelStatusBadge>
<ChevronRight
className={cn(
"h-4 w-4 shrink-0 text-muted-foreground transition-transform",
selected && "translate-x-0.5 text-foreground",
)}
aria-hidden
/>
) : null}
<ToggleButton checked={checked}
label={checked ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
disabled={alwaysEnabled || busy || (!feature.install_supported && !feature.installed && !feature.enabled)}
ariaLabel={t("settings.channels.toggleChannel", { name: displayName, defaultValue: "{{name}} channel" })}
onChange={(enabled) => {
if (enabled && feature.configured === false) onSelect(true);
else onAction(enabled ? "enable" : "disable", feature.name);
}} />
</div>
</button>
</div>
);
}
@@ -124,6 +128,7 @@ export function ChannelSetupPanel({
showBrandLogos,
onAction,
onFeaturesUpdate,
connectRequestId = 0,
}: {
token: string;
feature: NanobotFeatureInfo;
@@ -132,17 +137,18 @@ export function ChannelSetupPanel({
showBrandLogos: boolean;
onAction: (action: "enable" | "disable", name: string) => void;
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
connectRequestId?: number;
}) {
const { t, i18n } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const displayName = localizedChannelDisplayName(feature, t);
const [connectRequestId, setConnectRequestId] = useState(0);
const uiContribution = channelUiContribution(feature.name, feature.webui);
const PluginPanel = uiContribution?.Panel;
if (PluginPanel) {
return (
<Suspense fallback={<ChannelPluginLoading />}>
<PluginPanel
connectRequestId={connectRequestId}
token={token}
feature={feature}
actionKey={actionKey}
@@ -165,39 +171,19 @@ export function ChannelSetupPanel({
);
}
const enableBusy = actionKey === `enable:${feature.name}`;
const disableBusy = actionKey === `disable:${feature.name}`;
const missingSupport = feature.enabled && !feature.installed;
const alwaysEnabled = feature.capabilities?.includes("always_enabled") ?? false;
const channelChecked = alwaysEnabled || channelToggleChecked(feature);
const channelBusy = enableBusy || disableBusy;
const setup = channelSetup(feature, i18n.resolvedLanguage ?? i18n.language);
const needsSetupBeforeEnable =
!channelChecked
&& feature.configured === false
&& !(uiContribution?.canConnectBeforeConfigured && setup.mode === "connect");
const channelToggleDisabled =
alwaysEnabled
|| channelBusy
|| needsSetupBeforeEnable
|| (!feature.install_supported && !feature.installed && !feature.enabled);
const installSupportLabel = tx("settings.nanobotFeatures.installSupport", "Install support");
const toggleAriaLabel = t("settings.channels.toggleChannel", {
name: displayName,
defaultValue: "{{name}} channel",
});
return (
<aside className="min-h-full rounded-panel bg-settings-surface p-5">
<div className="flex items-start justify-between gap-4">
<aside className="settings-editor rounded-panel bg-settings-surface">
<div className="flex items-start justify-between gap-4 pr-8">
<div className="flex min-w-0 items-start gap-3">
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
<div className="min-w-0 flex-1">
<h3 className="truncate text-[18px] font-semibold leading-6 text-foreground">
<h3 className="truncate select-none text-[14px] font-semibold leading-5 text-foreground">
{displayName}
</h3>
<p className="mt-1 text-[13px] leading-5 text-muted-foreground">
{channelDescription(feature, t)}
</p>
{missingSupport && feature.install_supported ? (
<Button
type="button"
@@ -217,32 +203,6 @@ export function ChannelSetupPanel({
) : null}
</div>
</div>
<div className="flex shrink-0 items-center gap-2 pt-1">
<ChannelStatusBadge status={feature.runtime_status}>
{channelStatusLabel(feature, tx)}
</ChannelStatusBadge>
{channelBusy ? (
<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-hidden />
) : null}
<ToggleButton
checked={channelChecked}
disabled={channelToggleDisabled}
ariaLabel={toggleAriaLabel}
label={channelChecked ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
onChange={(checked) => {
if (
uiContribution?.canConnectBeforeConfigured
&& checked
&& !channelChecked
&& feature.configured === false
) {
setConnectRequestId((current) => current + 1);
return;
}
onAction(checked ? "enable" : "disable", feature.name);
}}
/>
</div>
</div>
<ChannelRuntimeError message={feature.runtime_error} className="mt-4" />
@@ -456,12 +416,12 @@ function ChannelSetupSurface({
type="button"
size="sm"
variant="secondary"
className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold hover:bg-background"
className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold settings-hover"
onClick={() =>
setNotice(
tx(
"settings.channels.connectPreview",
"The in-browser connect flow is next. For now, run the command below.",
"Run the command below in your terminal to connect.",
),
)
}
@@ -510,7 +470,7 @@ function ChannelSetupSurface({
type="submit"
size="sm"
variant="secondary"
className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold hover:bg-background"
className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold settings-hover"
disabled={saving}
>
{saving || validating ? (
@@ -57,7 +57,7 @@ export function ChannelGuideLink({
target="_blank"
rel="noreferrer"
className={cn(
"inline-flex max-w-full items-center gap-2 bg-background/80 font-semibold text-foreground transition-colors hover:bg-background",
"inline-flex max-w-full items-center gap-2 bg-background/80 font-semibold text-foreground transition-colors settings-hover",
compact
? "shrink-0 rounded-full py-1 pl-1 pr-2.5 text-[11.5px]"
: "mt-3 rounded-control py-1.5 pl-1.5 pr-3 text-[12px]",
@@ -135,7 +135,7 @@ function ChannelOfficialLink({
href={setup.officialUrl}
target="_blank"
rel="noreferrer"
className="inline-flex max-w-full shrink-0 items-center gap-2 rounded-full bg-background/80 py-1 pl-1 pr-2.5 text-[11.5px] font-semibold text-foreground transition-colors hover:bg-background"
className="inline-flex max-w-full shrink-0 items-center gap-2 rounded-full bg-background/80 py-1 pl-1 pr-2.5 text-[11.5px] font-semibold text-foreground transition-colors settings-hover"
>
<span
className="grid h-5 w-5 shrink-0 place-items-center overflow-hidden rounded-full bg-muted/70"
@@ -183,7 +183,7 @@ export function ChannelSetupActions({
type="button"
size="sm"
variant="secondary"
className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold hover:bg-background"
className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold settings-hover"
onClick={() => {
if (action.copyText) {
void copyTextToClipboard(action.copyText).then((ok) =>
@@ -200,7 +200,7 @@ export function CredentialForm({
value={values[field.key] ?? ""}
onChange={(event) => onChange(field.key, event.target.value)}
className={cn(
"h-9 rounded-control border-border/60 bg-muted/35 text-[13px]",
"h-9 rounded-full border-border/60 bg-muted/35 text-[13px]",
showSecretToggle && "pr-9",
)}
/>
@@ -213,7 +213,7 @@ export function CredentialForm({
: tx("settings.channels.showSecret", "Show secret")
}
onClick={() => onToggleSecret(field.key)}
className="absolute right-2 top-1/2 grid h-6 w-6 -translate-y-1/2 place-items-center rounded-full text-muted-foreground hover:bg-background hover:text-foreground"
className="absolute right-2 top-1/2 grid h-6 w-6 -translate-y-1/2 place-items-center rounded-full text-muted-foreground settings-hover hover:text-foreground"
>
{visible ? (
<EyeOff className="h-3.5 w-3.5" aria-hidden />
+10 -1
View File
@@ -1,19 +1,28 @@
import type { SettingsPayload } from "@/lib/types";
export type SettingsExitGuard = (leave: () => void) => void;
export type SettingsSectionKey =
| "overview"
| "about"
| "appearance"
| "models"
| "capabilities"
| "image"
| "voice"
| "browser"
| "channels"
| "apps"
| "automations"
| "memory"
| "skills"
| "runtime"
| "advanced";
export function isCapabilitySection(section: SettingsSectionKey): boolean {
return ["capabilities", "image", "voice", "browser", "memory"].includes(section);
}
type PendingRestartSection = "runtime" | "browser" | "image";
export type PendingRestartSections = Record<PendingRestartSection, boolean>;
@@ -26,7 +35,7 @@ export type RestartAwarePayload = {
export type ApplySettingsPayload = (
payload: SettingsPayload,
options?: { preserveAgentForm?: boolean },
options?: { preserveAgentForm?: boolean; preserveCapabilityForms?: boolean },
) => void;
export type MaybeRestartHostEngine = (payload: RestartAwarePayload) => Promise<void>;
@@ -1,7 +1,8 @@
import { ProviderIcon } from "@/components/settings/models/ProviderSettings";
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { useEffect, useRef, useState, type Dispatch, type SetStateAction } from "react";
import {
ChevronDown,
ChevronRight,
GripVertical,
ListOrdered,
Loader2,
@@ -142,7 +143,7 @@ export function ModelPresetDeleteDialog({
<DialogDescription className="leading-5">
{tx(
"settings.models.deletePresetHelp",
"This removes the preset “{{name}}”. Provider credentials are not affected.",
"Delete “{{name}}” and remove it from the fallback list. Provider credentials will be kept.",
{ name: preset?.name ?? "" },
)}
</DialogDescription>
@@ -227,15 +228,22 @@ export function ModelsSettings({
onDeleteConfiguration: (preset: SettingsPayload["model_presets"][number]) => void;
}) {
const { t } = useTranslation();
useAutoSave(form, dirty, saving, onSave, !creating && !!form.model.trim());
const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>
t(key, { defaultValue: fallback, ...(values ?? {}) });
const [editorOpen, setEditorOpen] = useState(false);
const editorTriggerRef = useRef<HTMLElement | null>(null);
const presetNameInputRef = useRef<HTMLInputElement>(null);
const suggestedPresetNameRef = useRef<string | null>(null);
const [editorRowKey, setEditorRowKey] = useState<string | null>(null);
const [advancedOpen, setAdvancedOpen] = useState(false);
const [draggedCallOrderIndex, setDraggedCallOrderIndex] = useState<number | null>(null);
const [dragOverCallOrderIndex, setDragOverCallOrderIndex] = useState<number | null>(null);
const [draggedRowHeight, setDraggedRowHeight] = useState(0);
const dragStartY = useRef(0);
const pendingDrag = useRef<number | null>(null);
const suppressDragClick = useRef(false);
const [draggedOffset, setDraggedOffset] = useState(0);
useEffect(() => {
if (presetNameError) presetNameInputRef.current?.focus();
@@ -303,13 +311,14 @@ export function ModelsSettings({
form.temperature < 0 ||
form.temperature > 2;
const selectedPresetReferenced = Boolean(
selectedPreset && callOrder.includes(selectedPreset.name),
selectedPreset && callOrder[0] === selectedPreset.name,
);
const callOrderBusy = orderSaving || saving;
const selectPreset = (
preset: SettingsPayload["model_presets"][number],
rowKey: string,
) => {
editorTriggerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
const toggleCurrentPreset =
!creating && selectedPreset?.name === preset.name && activeEditorRowKey === rowKey;
onSelectConfiguration(preset.name);
@@ -372,18 +381,8 @@ export function ModelsSettings({
<div
id="model-preset-editor"
data-testid="model-preset-editor"
className={cn(
"mx-3 mb-3 divide-y divide-border/45 overflow-hidden rounded-floating border border-border/45 bg-background/80 shadow-sm motion-reduce:animate-none animate-in fade-in-0 slide-in-from-top-1 duration-200 sm:mx-5 lg:mx-auto lg:w-[calc(100%-2.5rem)] lg:max-w-6xl",
creating && "mt-3",
)}
className="space-y-1 pb-4"
>
{creating ? (
<div className="flex min-h-[52px] items-center px-4 py-3 sm:px-5">
<span className="text-[13px] font-semibold text-foreground/85">
{tx("settings.models.newPreset", "New model preset")}
</span>
</div>
) : null}
<SettingsRow
title={tx("settings.models.presetName", "Preset name")}
description={tx(
@@ -393,7 +392,7 @@ export function ModelsSettings({
>
<div
className={cn(
"w-[min(280px,70vw)] motion-reduce:animate-none",
"w-full motion-reduce:animate-none",
presetNameError && "animate-[preset-name-shake_180ms_ease-in-out]",
)}
>
@@ -411,7 +410,7 @@ export function ModelsSettings({
setForm((prev) => ({ ...prev, modelPreset: event.target.value }));
}}
className={cn(
"h-8 rounded-full text-[13px]",
"h-9 rounded-full text-[13px]",
presetNameError &&
"border-destructive/70 focus-visible:border-destructive focus-visible:ring-destructive/25",
)}
@@ -501,7 +500,7 @@ export function ModelsSettings({
type="button"
aria-expanded={advancedOpen}
onClick={() => setAdvancedOpen((value) => !value)}
className="flex min-h-[62px] w-full items-center justify-between gap-4 px-4 py-3.5 text-left transition-colors hover:bg-muted/30 sm:px-5"
className="flex min-h-[62px] w-full items-center justify-between gap-4 px-4 py-3.5 text-left transition-colors settings-hover sm:px-5"
>
<span>
<span className="block text-[14px] font-medium text-foreground">
@@ -573,7 +572,7 @@ export function ModelsSettings({
>
{tx(
"settings.models.removeBeforeDelete",
"Remove this preset from the call order before deleting it.",
"Choose another primary preset before deleting this one.",
)}
</span>
) : null}
@@ -603,7 +602,7 @@ export function ModelsSettings({
);
return (
<div className="space-y-7">
<div className="settings-stack">
<section>
<SettingsSectionTitle>
{tx("settings.models.presets", "Model presets")}
@@ -645,7 +644,7 @@ export function ModelsSettings({
</div>
) : (
<>
<div role="list" className="divide-y divide-border/45">
<div role="list">
{presetRows.map(({ key, name, orderIndex, preset }) => {
const ordered = orderIndex >= 0;
const provider = preset
@@ -658,14 +657,13 @@ export function ModelsSettings({
preset.resolved_provider,
)
: true;
const isDropTarget =
ordered &&
dragOverCallOrderIndex === orderIndex &&
draggedCallOrderIndex !== orderIndex;
const dropAfterTarget =
isDropTarget &&
draggedCallOrderIndex !== null &&
draggedCallOrderIndex < orderIndex;
let dragOffset = 0;
const isDragging = ordered && draggedCallOrderIndex === orderIndex;
if (ordered && draggedCallOrderIndex !== null && dragOverCallOrderIndex !== null) {
if (isDragging) dragOffset = draggedOffset;
if (orderIndex > draggedCallOrderIndex && orderIndex <= dragOverCallOrderIndex) dragOffset = -draggedRowHeight;
if (orderIndex < draggedCallOrderIndex && orderIndex >= dragOverCallOrderIndex) dragOffset = draggedRowHeight;
}
const isSelected =
editorOpen &&
!creating &&
@@ -674,7 +672,7 @@ export function ModelsSettings({
const presetRow = (
<div
tabIndex={ordered ? 0 : -1}
draggable={ordered && !callOrderBusy}
onDragStart={(event) => event.preventDefault()}
aria-label={
ordered
? `${name}. ${tx(
@@ -684,36 +682,43 @@ export function ModelsSettings({
: name
}
data-testid={`model-call-order-row-${name}`}
onDragStart={(event) => {
if (!ordered || callOrderBusy) {
event.preventDefault();
return;
}
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", name);
setDraggedCallOrderIndex(orderIndex);
setDragOverCallOrderIndex(orderIndex);
onPointerDown={(event) => {
if (!ordered || callOrderBusy || event.button !== 0 || (event.target as HTMLElement).closest('[role="switch"]')) return;
pendingDrag.current = orderIndex;
suppressDragClick.current = false;
dragStartY.current = event.clientY;
setDraggedOffset(0);
const wrapper = event.currentTarget.parentElement;
setDraggedRowHeight(wrapper?.getBoundingClientRect().height || 60);
}}
onDragEnd={() => {
onPointerMove={(event) => {
if (!event.buttons) { pendingDrag.current = null; return; }
if (pendingDrag.current !== orderIndex || callOrderBusy) return;
const offset = event.clientY - dragStartY.current;
if (draggedCallOrderIndex === null && Math.abs(offset) < 5) return;
event.currentTarget.setPointerCapture(event.pointerId);
suppressDragClick.current = true;
setDraggedCallOrderIndex(orderIndex);
const target = Math.max(0, Math.min(callOrder.length - 1, orderIndex + Math.round(offset / draggedRowHeight)));
setDragOverCallOrderIndex(target);
setDraggedOffset(Math.max(-orderIndex * draggedRowHeight, Math.min((callOrder.length - orderIndex - 1) * draggedRowHeight, offset)));
}}
onPointerUp={() => {
pendingDrag.current = null;
if (draggedCallOrderIndex !== null) dropCallOrderItem(dragOverCallOrderIndex ?? orderIndex);
}}
onPointerCancel={() => {
pendingDrag.current = null;
setDraggedCallOrderIndex(null);
setDragOverCallOrderIndex(null);
}}
onDragEnter={(event) => {
if (ordered && draggedCallOrderIndex !== null) {
onClickCapture={(event) => {
if (suppressDragClick.current) {
event.preventDefault();
setDragOverCallOrderIndex(orderIndex);
event.stopPropagation();
suppressDragClick.current = false;
}
}}
onDragOver={(event) => {
if (!ordered || draggedCallOrderIndex === null) return;
event.preventDefault();
event.dataTransfer.dropEffect = "move";
}}
onDrop={(event) => {
if (!ordered) return;
event.preventDefault();
dropCallOrderItem(orderIndex);
}}
onKeyDown={(event) => {
if (event.currentTarget !== event.target) return;
if (ordered && event.key === "ArrowUp") {
@@ -728,52 +733,32 @@ export function ModelsSettings({
}
}}
className={cn(
"group relative flex min-h-[76px] select-none items-center gap-3 px-4 py-3 outline-none transition-[background-color,opacity] duration-150 sm:px-5",
"settings-list-row group relative flex select-none items-center gap-3 py-2 outline-none transition-colors duration-150",
ordered &&
(callOrderBusy
? "cursor-wait"
: "cursor-grab active:cursor-grabbing"),
"hover:bg-muted/25",
isDropTarget &&
!dropAfterTarget &&
"before:absolute before:inset-x-4 before:top-0 before:z-10 before:h-0.5 before:rounded-full before:bg-foreground sm:before:inset-x-5",
isDropTarget &&
dropAfterTarget &&
"after:absolute after:inset-x-4 after:bottom-0 after:z-10 after:h-0.5 after:rounded-full after:bg-foreground sm:after:inset-x-5",
ordered && draggedCallOrderIndex === orderIndex && "opacity-35",
isSelected && "bg-muted/45 hover:bg-muted/45",
!isDragging && "settings-hover",
isDragging && "bg-settings-surface shadow-md",
isSelected && "bg-muted/45 settings-hover",
"focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
)}
>
{ordered ? (
<GripVertical
className="pointer-events-none h-4 w-4 shrink-0 text-muted-foreground/40 transition-colors group-hover:text-muted-foreground"
aria-hidden
/>
) : (
<span className="h-4 w-4 shrink-0" aria-hidden />
)}
<button
type="button"
aria-pressed={selectedPreset?.name === name}
aria-expanded={isSelected}
aria-controls={isSelected ? "model-preset-editor" : undefined}
aria-haspopup="dialog"
disabled={!preset}
onClick={() => preset && selectPreset(preset, key)}
className="flex min-w-0 flex-1 items-center gap-3 rounded-control text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{ordered ? (
<span className="grid h-7 w-7 shrink-0 place-items-center rounded-full bg-muted font-mono text-[11px] font-semibold tabular-nums text-muted-foreground">
{orderIndex + 1}
</span>
{presetConfigured ? (
<ProviderIcon provider={provider} showBrandLogos={showBrandLogos} />
) : (
<span className="h-7 w-7 shrink-0" aria-hidden />
<span className="grid h-8 w-8 shrink-0 place-items-center">
<ProviderPickerIcon provider={provider} showBrandLogos={showBrandLogos} unconfigured />
</span>
)}
<ProviderPickerIcon
provider={provider}
showBrandLogos={showBrandLogos}
unconfigured={!presetConfigured}
/>
<span className="min-w-0 flex-1">
<span className="flex min-w-0 flex-wrap items-center gap-2">
<span className="truncate text-[14px] font-medium text-foreground">
@@ -783,10 +768,6 @@ export function ModelsSettings({
<StatusPill tone="success">
{tx("settings.models.primary", "Primary")}
</StatusPill>
) : !ordered ? (
<StatusPill tone="neutral">
{tx("settings.models.disabled", "Disabled")}
</StatusPill>
) : null}
{!presetConfigured ? (
<span className="text-[11px] font-medium text-amber-700 dark:text-amber-300">
@@ -797,18 +778,19 @@ export function ModelsSettings({
</span>
) : null}
</span>
<span className="mt-0.5 block truncate text-[12px] text-muted-foreground">
{preset?.model ?? name}
</span>
</span>
<ChevronRight
className={cn(
"h-4 w-4 shrink-0 text-muted-foreground transition-transform",
isSelected && "rotate-90",
)}
<span className="shrink-0 px-2 py-1 text-[13px] font-normal leading-5 text-muted-foreground">
{t("settings.configure")}
</span>
</button>
{ordered ? (
<GripVertical
className="h-4 w-4 shrink-0 touch-none text-muted-foreground/40 transition-colors group-hover:text-muted-foreground"
aria-hidden
/>
</button>
) : (
<span className="h-4 w-4 shrink-0" aria-hidden />
)}
<button
type="button"
role="switch"
@@ -842,9 +824,11 @@ export function ModelsSettings({
</div>
);
return (
<div key={key} role="listitem">
{presetRow}
{isSelected ? renderPresetEditor() : null}
<div key={key} role="listitem" data-call-order-index={orderIndex}>
<div className={cn("relative", isDragging ? "z-10" : "transition-transform duration-150 ease-out motion-reduce:transition-none")}
style={{ transform: `translateY(${dragOffset}px)` }}>
{presetRow}
</div>
</div>
);
})}
@@ -852,16 +836,17 @@ export function ModelsSettings({
{!creating ? (
<button
type="button"
className="flex min-h-[58px] w-full items-center justify-between gap-3 px-4 py-3 text-left outline-none transition-colors hover:bg-muted/30 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 sm:px-5"
className="flex min-h-[58px] w-full items-center justify-between gap-3 settings-list-inset py-3 text-left outline-none transition-colors settings-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
disabled={callOrderBusy}
onClick={() => {
onClick={(event) => {
editorTriggerRef.current = event.currentTarget;
setEditorRowKey(null);
setEditorOpen(true);
onBeginCreate();
}}
>
<span className="inline-flex items-center text-[13px] font-medium">
<Plus className="mr-1.5 h-3.5 w-3.5" aria-hidden />
<span className="inline-flex items-center gap-3 text-[14px] font-medium">
<span className="grid w-10 shrink-0 place-items-center"><Plus className="h-5 w-5" aria-hidden /></span>
{tx("settings.models.newPreset", "New model preset")}
</span>
{orderSaving ? (
@@ -874,11 +859,26 @@ export function ModelsSettings({
) : null}
</button>
) : null}
{creating && editorOpen ? renderPresetEditor() : null}
</>
)}
</SettingsGroup>
</section>
<Dialog open={editorOpen && (creating || selectedPreset !== null)} onOpenChange={(open) => {
setEditorOpen(open);
if (!open && creating) onCancelCreate();
}}>
<DialogContent aria-describedby={undefined}
className="relative max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none gap-0 overflow-y-auto p-0"
onCloseAutoFocus={(event) => {
event.preventDefault();
editorTriggerRef.current?.focus();
}}>
<DialogHeader className="px-6 pb-2 pt-5 pr-12">
<DialogTitle>{creating ? tx("settings.models.newPreset", "New model preset") : selectedPreset?.name}</DialogTitle>
</DialogHeader>
<div className="settings-grid !px-0">{renderPresetEditor()}</div>
</DialogContent>
</Dialog>
</div>
);
}
@@ -10,7 +10,6 @@ import {
Loader2,
Pencil,
Plus,
RotateCcw,
Zap,
} from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -30,6 +29,7 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
DropdownMenu,
@@ -40,6 +40,7 @@ import {
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { SettingsTextEditor } from "@/components/settings/shared/SettingsTextEditor";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { providerBrand } from "@/lib/provider-brand";
import { cn } from "@/lib/utils";
@@ -381,17 +382,14 @@ function ProviderRequestOptions({
return (
<div className="overflow-hidden rounded-floating border border-border/45 bg-background/75">
{options.map((option, index) => {
{options.map((option) => {
const title = tx(option.titleKey, option.title);
const Icon = option.kind === "priority" ? Zap : Globe2;
const checked = providerRequestOptionEnabled(option, extraBody);
return (
<div
key={option.titleKey}
className={cn(
"flex items-center justify-between gap-4 px-4 py-3",
index > 0 && "border-t border-border/45",
)}
className="flex items-center justify-between gap-4 rounded-xl px-4 py-3 transition-colors settings-hover focus-within:bg-sidebar-accent/60"
>
<div className="flex min-w-0 items-start gap-3">
<span className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted/70 text-muted-foreground">
@@ -444,7 +442,7 @@ function ProviderAdvancedOptions({
];
return (
<div className="border-y border-border/45">
<div className="space-y-1">
<button
type="button"
aria-expanded={open}
@@ -463,7 +461,7 @@ function ProviderAdvancedOptions({
/>
</button>
{open ? (
<div className="border-t border-border/45 py-3">
<div className="py-3">
<div className="grid gap-3 md:grid-cols-2">
{enabled.has("api_type") ? (
<label className="block space-y-1.5">
@@ -504,7 +502,7 @@ function ProviderAdvancedOptions({
{enabled.has("thinking_style") ? (
<label className="block space-y-1.5">
<span className="text-[12px] font-medium text-muted-foreground">
{tx("settings.providers.thinkingStyle", "Thinking style")}
{tx("settings.providers.thinkingStyle", "Reasoning parameter format")}
</span>
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -575,7 +573,7 @@ function ProviderAdvancedOptions({
{enabled.has("profile") ? (
<label className="block space-y-1.5">
<span className="text-[12px] font-medium text-muted-foreground">
{tx("settings.providers.profile", "Profile")}
{tx("settings.providers.profile", "AWS profile")}
</span>
<Input
value={form.profile}
@@ -594,40 +592,31 @@ function ProviderAdvancedOptions({
<span className="text-[12px] font-medium text-muted-foreground">
{tx("settings.providers.extraHeaders", "Extra headers")}
</span>
<Textarea
value={form.extraHeaders}
onChange={(event) => onChange({ extraHeaders: event.target.value })}
<SettingsTextEditor title={tx("settings.providers.extraHeaders", "Extra headers")}
value={form.extraHeaders} onSave={(value) => onChange({ extraHeaders: value })}
placeholder={'{"X-Header":"value"}'}
spellCheck={false}
className="min-h-[88px] resize-y bg-background font-mono text-[12px]"
/>
</label>
) : null}
{enabled.has("extra_query") ? (
<label className="block min-w-0 space-y-1.5">
<span className="text-[12px] font-medium text-muted-foreground">
{tx("settings.providers.extraQuery", "Extra query")}
{tx("settings.providers.extraQuery", "Additional query parameters")}
</span>
<Textarea
value={form.extraQuery}
onChange={(event) => onChange({ extraQuery: event.target.value })}
<SettingsTextEditor title={tx("settings.providers.extraQuery", "Additional query parameters")}
value={form.extraQuery} onSave={(value) => onChange({ extraQuery: value })}
placeholder={'{"api-version":"2024-02-01"}'}
spellCheck={false}
className="min-h-[88px] resize-y bg-background font-mono text-[12px]"
/>
</label>
) : null}
{enabled.has("extra_body") ? (
<label className="block min-w-0 space-y-1.5 md:col-span-2">
<span className="text-[12px] font-medium text-muted-foreground">
{tx("settings.providers.extraBody", "Extra body")}
{tx("settings.providers.extraBody", "Additional body parameters")}
</span>
<Textarea
value={form.extraBody}
onChange={(event) => onChange({ extraBody: event.target.value })}
<SettingsTextEditor title={tx("settings.providers.extraBody", "Additional body parameters")}
value={form.extraBody} onSave={(value) => onChange({ extraBody: value })}
placeholder={'{"service_tier":"priority"}'}
spellCheck={false}
className="min-h-[96px] resize-y bg-background font-mono text-[12px]"
/>
</label>
) : null}
@@ -635,7 +624,7 @@ function ProviderAdvancedOptions({
</div>
) : null}
{footer ? (
<div className="flex items-center justify-end gap-2 border-t border-border/45 py-3">
<div className="flex items-center justify-end gap-2 py-3">
{footer}
</div>
) : null}
@@ -663,9 +652,6 @@ export function ProvidersSettings({
onCreateCustomProvider,
onProviderOAuthLogin,
onProviderOAuthLogout,
imageProviderRestartPending,
onRestart,
isRestarting,
}: {
settings: SettingsPayload;
nanobotFeatures: NanobotFeaturesPayload | null;
@@ -686,9 +672,6 @@ export function ProvidersSettings({
onCreateCustomProvider: (draft: CustomProviderDraft) => Promise<boolean>;
onProviderOAuthLogin: (provider: string) => void;
onProviderOAuthLogout: (provider: string) => void;
imageProviderRestartPending: boolean;
onRestart?: () => void;
isRestarting?: boolean;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
@@ -776,12 +759,14 @@ export function ProvidersSettings({
? (nanobotFeatures?.features ?? []).find((feature) => feature.name === supportName)
: null;
return (
<div key={provider.name} className="divide-y divide-border/45">
<Dialog key={provider.name} open={expanded} onOpenChange={(open) => {
if (open !== expanded) toggleProvider(provider.name);
}}>
<DialogTrigger asChild>
<button
type="button"
aria-expanded={expanded}
onClick={() => toggleProvider(provider.name)}
className="flex min-h-[70px] w-full items-center justify-between gap-4 px-4 py-3 text-left transition-colors hover:bg-muted/35 sm:px-5"
aria-label={provider.label}
className="settings-list-row flex w-full items-center justify-between gap-4 py-2.5 text-left transition-colors settings-hover"
>
<span className="flex min-w-0 items-center gap-3">
<ProviderIcon
@@ -789,33 +774,26 @@ export function ProvidersSettings({
showBrandLogos={showBrandLogos}
/>
<span className="min-w-0">
<span className="block truncate text-[15px] font-semibold leading-5 text-foreground">
<span className="block truncate text-[14px] font-medium leading-5 text-foreground">
{provider.label}
</span>
{provider.api_base ? (
<span className="block truncate text-[12px] text-muted-foreground">
{provider.api_base}
</span>
) : null}
</span>
</span>
<ChevronDown
className={cn(
"h-4 w-4 shrink-0 text-muted-foreground transition-transform",
expanded && "rotate-180",
)}
aria-hidden
/>
<span className="shrink-0 px-2 py-1 text-[13px] font-normal leading-5 text-muted-foreground">
{t("settings.configure")}
</span>
</button>
</DialogTrigger>
{expanded ? (
<div className="space-y-3 bg-muted/18 px-4 py-4 sm:px-5">
<DialogContent aria-describedby={undefined} className="max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none overflow-y-auto">
<DialogHeader><DialogTitle>{provider.label}</DialogTitle></DialogHeader>
{supportFeature && !supportFeature.installed ? (
<CapabilityInstallNotice
title={tx("settings.capabilities.providerSupport", "Provider support")}
title={tx("settings.capabilities.providerSupport", "Provider dependencies")}
description={tx(
"settings.capabilities.providerInstallOnSave",
"Required support will be installed automatically when you save this provider.",
"Required packages will be installed automatically when you save this provider.",
)}
installing={featureAction === `enable:${supportName}`}
/>
@@ -976,7 +954,7 @@ export function ProvidersSettings({
? t("settings.byok.hideApiKey")
: t("settings.byok.showApiKey")
}
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 rounded-full text-muted-foreground settings-hover hover:text-foreground"
>
{keyVisible ? (
<EyeOff className="h-3.5 w-3.5" aria-hidden />
@@ -996,7 +974,7 @@ export function ProvidersSettings({
size="icon"
onClick={() => onToggleProviderKeyEditing(provider.name)}
aria-label={t("settings.actions.edit")}
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 rounded-full text-muted-foreground settings-hover hover:text-foreground"
>
<Pencil className="h-3.5 w-3.5" aria-hidden />
</Button>
@@ -1055,31 +1033,16 @@ export function ProvidersSettings({
</div>
</>
)}
</div>
</DialogContent>
) : null}
</div>
</Dialog>
);
};
const customProviderForm = creatingCustomProvider ? (
<div className="divide-y divide-border/45">
<button
type="button"
aria-expanded
onClick={cancelCustomProviderCreation}
className="flex min-h-[70px] w-full items-center justify-between gap-4 px-4 py-3 text-left transition-colors hover:bg-muted/35 sm:px-5"
>
<span className="flex min-w-0 items-center gap-3">
<ProviderIcon provider="custom" showBrandLogos={showBrandLogos} />
<span className="truncate text-[15px] font-semibold text-foreground">
{tx("settings.providers.customProvider", "Custom provider")}
</span>
</span>
<ChevronDown
className="h-4 w-4 shrink-0 rotate-180 text-muted-foreground"
aria-hidden
/>
</button>
<div className="space-y-3 bg-muted/18 px-4 py-4 sm:px-5">
<Dialog open onOpenChange={(open) => { if (!open) cancelCustomProviderCreation(); }}>
<DialogContent aria-describedby={undefined} className="max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none overflow-y-auto">
<DialogHeader><DialogTitle>{tx("settings.providers.customProvider", "Custom provider")}</DialogTitle></DialogHeader>
<div className="space-y-3">
<label className="block space-y-1.5">
<span className="text-[12px] font-medium text-muted-foreground">
{tx("settings.providers.customProviderName", "Provider name")}
@@ -1151,7 +1114,7 @@ export function ProvidersSettings({
? t("settings.byok.hideApiKey")
: t("settings.byok.showApiKey")
}
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 rounded-full text-muted-foreground settings-hover hover:text-foreground"
>
{customProviderKeyVisible ? (
<EyeOff className="h-3.5 w-3.5" aria-hidden />
@@ -1195,33 +1158,11 @@ export function ProvidersSettings({
</Button>
</div>
</div>
</div>
</DialogContent>
</Dialog>
) : null;
return (
<div className="space-y-6">
{imageProviderRestartPending && onRestart ? (
<div className="flex min-h-[48px] items-center justify-between gap-3 border-y border-border/55 py-3">
<p className="text-[13px] leading-5 text-muted-foreground">
{tx("settings.status.imageProviderRestart", "Provider support changed. Restart when ready.")}
</p>
<div className="shrink-0">
<Button
size="sm"
variant="ghost"
onClick={onRestart}
disabled={isRestarting}
className="rounded-full"
>
{isRestarting ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
) : (
<RotateCcw className="mr-1.5 h-3.5 w-3.5" aria-hidden />
)}
{isRestarting ? t("app.system.restarting") : t("app.system.restart")}
</Button>
</div>
</div>
) : null}
<section>
<SettingsSectionTitle>
{tx("settings.providers.title", "Model providers")}
@@ -1237,13 +1178,13 @@ export function ProvidersSettings({
<DropdownMenuTrigger asChild>
<button
type="button"
className="group flex min-h-[70px] w-full items-center justify-between gap-4 px-4 py-3 text-left transition-colors hover:bg-muted/35 sm:px-5"
className="group settings-list-row flex w-full items-center justify-between gap-4 py-2.5 text-left transition-colors settings-hover"
>
<span className="flex min-w-0 items-center gap-3">
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-control bg-muted text-muted-foreground">
<Plus className="h-5 w-5" aria-hidden />
</span>
<span className="truncate text-[15px] font-semibold text-foreground">
<span className="truncate text-[14px] font-medium text-foreground">
{tx(
"settings.providers.addOwnProvider",
"Add your own model provider",
@@ -1319,7 +1260,7 @@ function providerVisibilityRank(provider: SettingsPayload["providers"][number]):
return 200;
}
function ProviderIcon({
export function ProviderIcon({
provider,
showBrandLogos,
}: {
@@ -1334,7 +1275,7 @@ function ProviderIcon({
return (
<span
data-testid={`provider-logo-${provider}`}
className="grid h-10 w-10 shrink-0 place-items-center overflow-hidden rounded-control border border-border/45 bg-background"
className="grid h-8 w-8 shrink-0 place-items-center overflow-hidden rounded-control border border-border/45 bg-background"
>
<img
src={logoUrl}
@@ -1352,7 +1293,7 @@ function ProviderIcon({
return (
<span
data-testid={`provider-logo-fallback-${provider}`}
className="grid h-10 w-10 shrink-0 place-items-center rounded-control text-[11px] font-semibold text-white"
className="grid h-8 w-8 shrink-0 place-items-center rounded-control text-[11px] font-semibold text-white"
style={{ backgroundColor: brand.color }}
aria-hidden
>
@@ -1361,7 +1302,7 @@ function ProviderIcon({
);
}
return (
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-2xl bg-muted text-foreground/82 dark:bg-muted/70">
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-control bg-muted text-foreground/82 dark:bg-muted/70">
<Icon className="h-5 w-5" strokeWidth={2} aria-hidden />
</span>
);
@@ -2,15 +2,16 @@ import { useState, type Dispatch, type SetStateAction } from "react";
import {
ArrowUpCircle,
Bot,
BookOpen,
Github,
MessageCircle,
Check,
ChevronRight,
ExternalLink,
Globe2,
HardDrive,
ImageIcon,
Loader2,
Mic,
Server,
type LucideIcon,
} from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -24,7 +25,7 @@ import {
SettingsRow,
SettingsSectionTitle,
} from "@/components/settings/shared/SettingsControls";
import { TokenUsageHeatmap } from "@/components/settings/TokenUsageHeatmap";
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";
@@ -33,23 +34,19 @@ import { checkVersion } from "@/lib/api";
import type {
FileEditDisplayMode,
LocalActivityMode,
LocalDensity,
LocalPreferences,
} from "@/lib/local-preferences";
import { providerBrand, providerDisplayLabel } from "@/lib/provider-brand";
import type { SettingsPayload } from "@/lib/types";
import { cn } from "@/lib/utils";
import { shortWorkspacePath } from "@/lib/workspace";
import { useClient } from "@/providers/ClientProvider";
export function OverviewSettings({
settings,
requiresRestart,
onSelectSection,
showBrandLogos,
}: {
settings: SettingsPayload;
requiresRestart: boolean;
onSelectSection: (section: SettingsSectionKey) => void;
showBrandLogos: boolean;
}) {
@@ -75,62 +72,17 @@ export function OverviewSettings({
const webStatus = settings.web.enable
? tx("settings.values.enabled", "Enabled")
: tx("settings.values.disabled", "Disabled");
const webSearchProvider =
settings.web_search.providers.find((provider) => provider.name === settings.web_search.provider) ??
settings.web_search.providers[0];
const webSearchProviderLabel = providerDisplayLabel(
settings.web_search.providers,
settings.web_search.provider,
);
const webSearchCredentialStatus =
webSearchProvider?.credential === "none"
? tx("settings.byok.webSearch.noCredentialRequired", "No key required")
: webSearchProvider?.credential === "optional_api_key"
? settings.web_search.api_key_hint
? tx("settings.values.configured", "Configured")
: tx("settings.byok.webSearch.noCredentialRequired", "No key required")
: webSearchProvider?.credential === "base_url"
? settings.web_search.base_url
? tx("settings.values.configured", "Configured")
: tx("settings.values.notConfigured", "Not configured")
: settings.web_search.api_key_hint
? tx("settings.values.configured", "Configured")
: tx("settings.values.notConfigured", "Not configured");
const webCaption = `${webSearchProviderLabel} · ${webSearchCredentialStatus}`;
const imageStatus = settings.image_generation.enabled
? tx("settings.values.enabled", "Enabled")
: tx("settings.values.disabled", "Disabled");
const imageCaption = `${providerDisplayLabel(settings.image_generation.providers, settings.image_generation.provider)} · ${
settings.image_generation.provider_configured
? tx("settings.values.configured", "Configured")
: tx("settings.values.notConfigured", "Not configured")
}`;
const transcription = settings.transcription ?? DEFAULT_TRANSCRIPTION_SETTINGS;
const voiceStatus = transcription.enabled
? tx("settings.values.enabled", "Enabled")
: tx("settings.values.disabled", "Disabled");
const voiceCaption = `${providerDisplayLabel(transcription.providers, transcription.provider)} · ${
transcription.provider_configured
? tx("settings.values.configured", "Configured")
: tx("settings.values.notConfigured", "Not configured")
}`;
const isNativeHost = (settings.surface ?? settings.runtime_surface) === "native";
const workspaceCaption = shortWorkspacePath(settings.runtime.workspace_path);
const runtimeTitle = isNativeHost
? tx("settings.rows.engine", "Engine")
: tx("settings.rows.gateway", "Gateway");
const runtimeValue = isNativeHost
? tx("settings.values.privateEngine", "Private engine")
: `${settings.runtime.gateway_host}:${settings.runtime.gateway_port}`;
const runtimeCaption = isNativeHost
? tx("settings.values.unixSocket", "Unix socket")
: requiresRestart
? tx("settings.values.restartPending", "Restart pending")
: tx("settings.values.ready", "Ready");
return (
<div className="space-y-7">
<section className="rounded-panel bg-settings-surface px-4 py-4 sm:px-5">
<TokenUsageHeatmap usage={settings.usage} timeZone={settings.agent.timezone} />
<div className="settings-stack">
<section className="rounded-panel bg-settings-surface p-6">
<TokenUsageCard usage={settings.usage} timeZone={settings.agent.timezone} />
</section>
<section>
@@ -156,7 +108,6 @@ export function OverviewSettings({
valueLogoProvider={settings.web_search.provider}
title={tx("settings.overview.webSearch", "Web search")}
value={webStatus}
caption={webCaption}
showBrandLogos={showBrandLogos}
onClick={() => onSelectSection("browser")}
/>
@@ -165,7 +116,6 @@ export function OverviewSettings({
valueLogoProvider={settings.image_generation.provider}
title={tx("settings.overview.imageGeneration", "Image generation")}
value={imageStatus}
caption={imageCaption}
showBrandLogos={showBrandLogos}
onClick={() => onSelectSection("image")}
/>
@@ -174,39 +124,40 @@ export function OverviewSettings({
valueLogoProvider={transcription.provider}
title={tx("settings.overview.voiceInput", "Voice input")}
value={voiceStatus}
caption={voiceCaption}
showBrandLogos={showBrandLogos}
onClick={() => onSelectSection("voice")}
/>
</SettingsGroup>
</section>
<section>
<SettingsSectionTitle>{tx("settings.sections.system", "System")}</SettingsSectionTitle>
<SettingsGroup>
<OverviewListRow
icon={Server}
title={runtimeTitle}
value={runtimeValue}
caption={runtimeCaption}
onClick={() => onSelectSection("runtime")}
/>
<OverviewListRow
icon={HardDrive}
title={tx("settings.overview.workspace", "Workspace")}
value={tx("settings.values.defaultWorkspace", "Default workspace")}
caption={workspaceCaption}
onClick={() => onSelectSection("runtime")}
/>
</SettingsGroup>
</section>
</div>
);
}
<section>
<SettingsSectionTitle>{tx("settings.sections.about", "About")}</SettingsSectionTitle>
<SettingsGroup>
<VersionCheckRow currentVersion={settings.version?.current} />
</SettingsGroup>
</section>
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: "reportIssue", icon: MessageCircle, href: "https://github.com/HKUDS/nanobot/issues" },
];
return (
<div className="settings-stack">
<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} />
</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>
);
}
@@ -245,16 +196,16 @@ function VersionCheckRow({ currentVersion }: { currentVersion?: string }) {
};
return (
<div className="flex min-h-[62px] flex-col gap-3 px-4 py-3.5 sm:flex-row sm:items-center sm:justify-between sm:px-5">
<div className="flex flex-col items-center gap-4">
<div className="min-w-0">
<div className="text-[14px] font-medium leading-5 text-foreground">
<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"}
</div>
</div>
<div className="flex shrink-0 flex-col items-end gap-2">
<div className="flex shrink-0 flex-col items-center gap-2">
<Button
size="sm"
variant="outline"
@@ -319,7 +270,7 @@ export function AppearanceSettings({
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
return (
<div className="space-y-7">
<div className="settings-stack">
<section>
<SettingsSectionTitle>{t("settings.sections.interface")}</SettingsSectionTitle>
<SettingsGroup>
@@ -359,18 +310,6 @@ export function AppearanceSettings({
<section>
<SettingsSectionTitle>{tx("settings.sections.localPreferences", "Local preferences")}</SettingsSectionTitle>
<SettingsGroup>
<SettingsRow title={tx("settings.rows.density", "Density")}>
<SegmentedControl
value={localPrefs.density}
options={[
{ value: "comfortable", label: tx("settings.values.comfortable", "Comfortable") },
{ value: "compact", label: tx("settings.values.compact", "Compact") },
]}
onChange={(density) =>
onChangeLocalPrefs((prev) => ({ ...prev, density: density as LocalDensity }))
}
/>
</SettingsRow>
<SettingsRow title={tx("settings.rows.activityMode", "Activity detail")}>
<SegmentedControl
value={localPrefs.activityMode}
@@ -527,7 +466,7 @@ function OverviewListRow({
valueLogoProvider?: string | null;
title: string;
value: string;
caption: string;
caption?: string;
showBrandLogos?: boolean;
onClick: () => void;
}) {
@@ -535,12 +474,12 @@ function OverviewListRow({
<button
type="button"
onClick={onClick}
className="group flex min-h-[68px] w-full items-center gap-3 px-4 py-3.5 text-left transition-colors hover:bg-muted/30 sm:px-5"
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>
<span className="mt-0.5 block truncate text-[12px] leading-5 text-muted-foreground">{caption}</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} />
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { useEffect, useMemo, useRef, useState, type ComponentProps } from "react";
import {
Bot,
Brain,
@@ -27,12 +27,7 @@ import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { ComboboxOption, useComboboxNavigation } from "@/components/ui/combobox";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useLogoFallback } from "@/hooks/useLogoFallback";
@@ -93,33 +88,35 @@ export function settingsProviderConfigured(
export function ProviderPicker({
providers,
value,
triggerProps,
emptyLabel,
showProviderLogos = false,
onChange,
}: {
providers: Array<{ name: string; label: string }>;
value: string;
triggerProps?: Pick<ComponentProps<typeof Button>, "id" | "aria-label" | "aria-describedby" | "aria-invalid" | "disabled">;
emptyLabel: string;
showProviderLogos?: boolean;
onChange: (provider: string) => void;
}) {
const selectedProvider = providers.find((provider) => provider.name === value) ?? null;
const disabled = providers.length === 0;
const disabled = !!triggerProps?.disabled || providers.length === 0;
return (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild disabled={disabled}>
<Button
<Select value={value} onValueChange={onChange} disabled={disabled}>
<SelectTrigger
{...triggerProps}
aria-label={triggerProps?.["aria-label"] ?? selectedProvider?.label ?? emptyLabel}
type="button"
variant="outline"
disabled={disabled}
className={cn(
"h-8 w-[210px] justify-between rounded-full border-input bg-background px-3 text-[13px] font-normal shadow-none",
"hover:bg-accent/55 focus-visible:ring-2 focus-visible:ring-ring",
"h-9 w-full justify-between rounded-full border-input bg-background px-3 text-[13px] font-normal shadow-none",
"settings-hover focus-visible:ring-2 focus-visible:ring-ring",
disabled && "text-muted-foreground",
)}
>
<span className="flex min-w-0 items-center gap-2">
<SelectValue placeholder={emptyLabel}><span className="flex min-w-0 items-center gap-2">
{selectedProvider && showProviderLogos ? (
<ProviderPickerIcon
provider={selectedProvider.name}
@@ -127,24 +124,14 @@ export function ProviderPicker({
/>
) : null}
<span className="truncate">{selectedProvider?.label ?? emptyLabel}</span>
</span>
<ChevronDown className="ml-2 h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
className="max-h-[18rem] w-[240px] overflow-y-auto scrollbar-thin scrollbar-track-transparent"
>
</span></SelectValue>
</SelectTrigger>
<SelectContent>
{providers.map((provider) => {
const selected = provider.name === value;
return (
<DropdownMenuItem
<SelectItem
key={provider.name}
onSelect={() => onChange(provider.name)}
className={cn(
"flex cursor-default items-center justify-between gap-2 text-[13px]",
selected && "bg-muted/80 text-foreground focus:bg-muted",
)}
value={provider.name}
>
<span className="flex min-w-0 items-center gap-2">
{showProviderLogos ? (
@@ -155,12 +142,11 @@ export function ProviderPicker({
) : null}
<span className="truncate">{provider.label}</span>
</span>
{selected ? <Check className="h-3.5 w-3.5 shrink-0" aria-hidden /> : null}
</DropdownMenuItem>
</SelectItem>
);
})}
</DropdownMenuContent>
</DropdownMenu>
</SelectContent>
</Select>
);
}
@@ -349,8 +335,8 @@ export function ModelIdPicker({
type="button"
variant="outline"
className={cn(
"h-9 w-[min(360px,70vw)] justify-between rounded-full border-input bg-background px-3 text-[12px] font-normal shadow-none",
"hover:bg-accent/55 focus-visible:ring-2 focus-visible:ring-ring",
"h-9 w-full justify-between rounded-full border-input bg-background px-3 text-[13px] font-normal shadow-none",
"settings-hover focus-visible:ring-2 focus-visible:ring-ring",
)}
>
<span className="flex min-w-0 items-center gap-2">
@@ -373,7 +359,7 @@ export function ModelIdPicker({
</PopoverTrigger>
<PopoverContent
align="end"
className="w-[360px] max-w-[calc(100vw-2rem)] p-1.5"
className="w-[var(--radix-popover-trigger-width)] max-w-[calc(100vw-2rem)] p-1.5"
>
<div className="p-1 pb-1.5">
<div className="relative">
@@ -410,11 +396,11 @@ export function ModelIdPicker({
</div>
) : !canFetchModels ? (
<div className="px-2 py-1.5 text-[11px] leading-4 text-muted-foreground">
{tx("settings.models.autoProviderCustomOnly", "Auto provider mode uses custom model IDs.")}
{tx("settings.models.autoProviderCustomOnly", "Enter a model ID manually when using automatic provider selection.")}
</div>
) : waitingForModelSearch ? (
<div className="px-2 py-1.5 text-[11px] leading-4 text-muted-foreground">
{tx("settings.models.searchCatalog", "Search provider catalog to choose a model.")}
{tx("settings.models.searchCatalog", "Search this provider’s model catalog.")}
</div>
) : loading ? (
<div className="flex items-center gap-2 px-2 py-1.5 text-[11px] text-muted-foreground">
@@ -435,8 +421,11 @@ export function ModelIdPicker({
</div>
) : isCatalog && !normalizedQuery ? (
<div className="px-2 py-1.5 text-[11px] leading-4 text-muted-foreground">
{tx("settings.models.searchCatalog", "Search provider catalog to choose a model.")}
{providerModelCount ? ` ${providerModelCount} ${tx("settings.models.modelsAvailable", "available")}.` : ""}
{tx("settings.models.searchCatalog", "Search this provider’s model catalog.")}
{providerModelCount ? <> {t("settings.models.availableCount", {
defaultValue: "Models available: {{count}}",
count: providerModelCount,
})}</> : null}
</div>
) : null}
@@ -12,6 +12,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { SettingsHint } from "@/components/settings/shared/SettingsHint";
import { isNativeRuntime } from "@/lib/runtime";
import type { NanobotFeatureInfo } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -84,7 +85,7 @@ export function NanobotFeatureInstallDialog({
variant="ghost"
onClick={() => onOpenChange(false)}
disabled={installing}
className="h-11 w-full min-w-0 bg-muted/70 px-5 text-[15px] font-semibold text-foreground shadow-none hover:bg-muted"
className="h-11 w-full min-w-0 bg-muted/70 px-5 text-[15px] font-semibold text-foreground shadow-none settings-hover"
>
{tx("settings.automations.cancel", "Cancel")}
</Button>
@@ -133,7 +134,7 @@ export function DismissibleStatusMessage({
"flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-colors",
isError
? "text-destructive/70 hover:bg-destructive/10 hover:text-destructive"
: "text-muted-foreground/70 hover:bg-muted hover:text-foreground",
: "text-muted-foreground/70 settings-hover hover:text-foreground",
)}
>
<X className="h-3.5 w-3.5" aria-hidden />
@@ -153,16 +154,16 @@ export function RestartRequiredNotice({
}) {
const { t } = useTranslation();
return (
<div className="flex flex-col gap-3 rounded-control border border-amber-500/20 bg-amber-500/8 px-4 py-3 text-[12.5px] text-amber-800 dark:text-amber-200 sm:flex-row sm:items-center sm:justify-between">
<span>{message}</span>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-muted-foreground">
<span role="status">{message}</span>
{onRestart ? (
<Button
type="button"
size="sm"
variant="outline"
variant="ghost"
onClick={onRestart}
disabled={isRestarting}
className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold"
className="h-8 rounded-full px-2 text-[12px] font-medium text-muted-foreground hover:text-foreground"
>
{isRestarting ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
@@ -178,7 +179,7 @@ export function RestartRequiredNotice({
export function SettingsSectionTitle({ children }: { children: ReactNode }) {
return (
<h2 className="mb-2 px-1 text-[13px] font-semibold tracking-[-0.01em] text-foreground/85">
<h2 className="settings-section-title select-none text-[13px] font-semibold tracking-[-0.01em] text-foreground/85">
{children}
</h2>
);
@@ -187,7 +188,7 @@ export function SettingsSectionTitle({ children }: { children: ReactNode }) {
export function SettingsGroup({ children }: { children: ReactNode }) {
return (
<div className="overflow-hidden rounded-panel bg-settings-surface">
<div className="divide-y divide-border/45">{children}</div>
{children}
</div>
);
}
@@ -197,21 +198,18 @@ export function SettingsRow({
description,
children,
}: {
title: string;
title: ReactNode;
description?: string;
children?: ReactNode;
}) {
return (
<div className="flex min-h-[62px] flex-col gap-3 px-4 py-3.5 sm:flex-row sm:items-center sm:justify-between sm:px-5">
<div className="settings-row rounded-xl transition-colors settings-hover focus-within:bg-sidebar-accent/60">
<div className="min-w-0">
<div className="text-[14px] font-medium leading-5 text-foreground">{title}</div>
{description ? (
<div className="mt-0.5 max-w-[28rem] text-[12px] leading-5 text-muted-foreground">
{description}
</div>
) : null}
<div className="select-none text-[14px] font-medium leading-5 text-foreground">
{description ? <SettingsHint description={description}>{title}</SettingsHint> : title}
</div>
</div>
{children ? <div className="min-w-0 sm:ml-6 sm:shrink-0">{children}</div> : null}
{children ? <div className="settings-control">{children}</div> : null}
</div>
);
}
@@ -235,6 +233,9 @@ export function ReadOnlyRow({
}
export function RestartSettingsFooter({
saveLabel,
error = false,
autoSave = false,
dirty,
saving,
pendingRestart,
@@ -247,6 +248,9 @@ export function RestartSettingsFooter({
onReset,
isRestarting,
}: {
saveLabel?: string;
error?: boolean;
autoSave?: boolean;
dirty: boolean;
saving: boolean;
pendingRestart: boolean;
@@ -269,22 +273,27 @@ export function RestartSettingsFooter({
? tx("app.system.restartingEngine", "Restarting engine...")
: t("app.system.restarting");
const statusMessage =
message ??
(saving ? t("settings.actions.saving") : undefined) ?? message ??
(pendingRestart && !dirty
? pendingMessage ?? tx("settings.status.savedRestartApply", "Saved. Restart when ready.")
? pendingMessage ?? tx("settings.status.savedRestartApply", "Saved. Restart to apply changes.")
: dirty
? dirtyMessage ?? t("settings.status.unsaved")
? autoSave
? error ? undefined : t("settings.actions.saving")
: dirtyMessage ?? t("settings.status.unsaved")
: undefined);
const statusTone = disabled ? "danger" : dirty || pendingRestart ? "accent" : undefined;
const statusTone = error || disabled ? "danger" : dirty || pendingRestart ? "accent" : undefined;
if (autoSave && !statusMessage && !pendingRestart) return null;
return (
<div className="flex min-h-[58px] flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:px-5">
<div className="min-w-0 text-[13px] leading-5 text-muted-foreground">
<div className={cn("settings-footer", autoSave && "settings-footer-auto")}>
<div role={error ? "alert" : "status"} className="min-w-0 text-[13px] leading-5 text-muted-foreground">
<SettingsStatusMessage tone={statusTone}>{statusMessage}</SettingsStatusMessage>
</div>
<div className="flex w-full shrink-0 flex-wrap justify-end gap-2 sm:w-auto">
{pendingRestart && !dirty && onRestart ? (
<Button
type="button"
size="sm"
variant="ghost"
onClick={onRestart}
@@ -299,8 +308,9 @@ export function RestartSettingsFooter({
{isRestarting ? restartingLabel : restartLabel}
</Button>
) : null}
{onReset ? (
{onReset && !autoSave ? (
<Button
type="button"
size="sm"
variant="ghost"
onClick={onReset}
@@ -310,15 +320,16 @@ export function RestartSettingsFooter({
{t("settings.actions.cancel")}
</Button>
) : null}
<Button
{!autoSave ? <Button
type="button"
size="sm"
variant="outline"
onClick={onSave}
disabled={!dirty || disabled || saving}
className="rounded-full"
>
{saving ? t("settings.actions.saving") : t("settings.actions.save")}
</Button>
{saving ? t("settings.actions.saving") : saveLabel ?? t("settings.actions.save")}
</Button> : null}
</div>
</div>
);
@@ -366,7 +377,7 @@ export function StatusPill({
return (
<span
className={cn(
"inline-flex max-w-[260px] items-center rounded-full px-2.5 py-1 text-[12px] font-medium",
"inline-flex max-w-[260px] select-none items-center rounded-full px-2.5 py-1 text-[12px] font-medium",
tone === "success" && "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
tone === "warning" && "bg-amber-500/10 text-amber-700 dark:text-amber-300",
tone === "neutral" && "bg-muted text-muted-foreground",
@@ -391,7 +402,7 @@ export function NumberInput({
suffix?: string;
}) {
return (
<div className="flex items-center gap-2">
<div className="relative w-full">
<Input
type="number"
min={min}
@@ -401,9 +412,9 @@ export function NumberInput({
const parsed = Number(event.target.value);
if (Number.isFinite(parsed)) onChange(parsed);
}}
className="h-8 w-24 max-w-full rounded-full text-[13px]"
className={cn("h-9 w-full rounded-full text-[13px]", suffix && "pr-12")}
/>
{suffix ? <span className="text-[12px] text-muted-foreground">{suffix}</span> : null}
{suffix ? <span className="pointer-events-none absolute inset-y-0 right-3 flex select-none items-center text-[12px] text-muted-foreground">{suffix}</span> : null}
</div>
);
}
@@ -0,0 +1,71 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { ChevronDown } from "lucide-react";
import { useTranslation } from "react-i18next";
import { ToggleButton } from "@/components/settings/ToggleButton";
import { SettingsGroup, SettingsRow } from "@/components/settings/shared/SettingsControls";
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
export function SettingsAdvancedOptions({ children }: { children: ReactNode }) {
const { t } = useTranslation();
return (
<details className="group/advanced [&>summary]:select-none">
<summary className="settings-list-inset flex min-h-12 cursor-pointer list-none items-center justify-between gap-4 rounded-xl text-[13px] leading-5 text-muted-foreground settings-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&::-webkit-details-marker]:hidden">
{t("settings.runtimeConfig.advancedOptions")}
<ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 group-open/advanced:rotate-180" />
</summary>
<div className="space-y-1">{children}</div>
</details>
);
}
export function SettingsFeature({
title, enabled, onChange, disabled, initialOpen = false, error, children,
}: {
title: string;
enabled: boolean;
onChange: (enabled: boolean) => void;
disabled?: boolean;
initialOpen?: boolean;
error?: string;
children?: ReactNode;
}) {
const { t } = useTranslation();
const [open, setOpen] = useState(initialOpen && enabled);
const section = useRef<HTMLElement>(null);
useEffect(() => {
if (initialOpen && enabled) {
setOpen(true);
section.current?.scrollIntoView?.({ block: "nearest" });
}
}, [initialOpen, enabled]);
return (
<section ref={section} aria-label={title}>
<Dialog open={Boolean(children) && open} onOpenChange={setOpen}>
<SettingsGroup>
<SettingsRow title={children ? (
<DialogTrigger asChild>
<button type="button"
className="flex min-h-9 w-full items-center rounded-lg text-start focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
{title}
</button>
</DialogTrigger>
) : title}>
{children ? <DialogTrigger asChild>
<button type="button"
className="mr-3 shrink-0 rounded-lg px-2 py-1 text-[13px] leading-5 text-muted-foreground settings-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
{t("settings.configure")}
</button>
</DialogTrigger> : null}
<ToggleButton checked={enabled} disabled={disabled} ariaLabel={title} label={title}
onChange={(next) => { setOpen(next); onChange(next); }} />
</SettingsRow>
</SettingsGroup>
{children ? <DialogContent aria-describedby={undefined} className="settings-grid max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none overflow-y-auto p-0 [--settings-surface:var(--background)]">
<DialogTitle className="sr-only">{title}</DialogTitle>
<div className="pb-4 pt-8">{children}</div>
</DialogContent> : null}
</Dialog>
{error && !open ? <p role="alert" className="settings-list-inset pt-2 text-[13px] leading-5 text-destructive">{error}</p> : null}
</section>
);
}
@@ -0,0 +1,25 @@
import { useState, type ReactNode } from "react";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
export function SettingsHint({ children, description }: { children: ReactNode; description: string }) {
const [open, setOpen] = useState(false);
return (
<TooltipProvider>
<Tooltip open={open} onOpenChange={setOpen}>
<TooltipTrigger asChild>
<button
type="button"
onClick={(event) => { event.preventDefault(); setOpen(true); }}
className="max-w-full cursor-help rounded-sm text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{children}
</button>
</TooltipTrigger>
<TooltipContent side="top" className="max-w-[min(22rem,calc(100vw-2rem))] whitespace-normal text-pretty leading-5">
{description}
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
@@ -0,0 +1,70 @@
import { useRef, useState } from "react";
import { SquarePen } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
export function SettingsTextEditor({ id, title, description, value, placeholder, disabled, onSave }: {
id?: string;
title: string;
description?: string;
value: string;
placeholder?: string;
disabled?: boolean;
onSave: (value: string) => void | Promise<void>;
}) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const [draft, setDraft] = useState(value);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
const editor = useRef<HTMLTextAreaElement>(null);
const save = async () => {
setSaving(true);
setError("");
try {
await onSave(draft);
setOpen(false);
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
editor.current?.focus();
} finally {
setSaving(false);
}
};
return <Dialog open={open} onOpenChange={(next) => {
if (saving) return;
if (next) { setDraft(value); setError(""); }
setOpen(next);
}}>
<TooltipProvider><Tooltip>
<TooltipTrigger asChild><DialogTrigger asChild>
<Button id={id} type="button" variant="ghost" disabled={disabled} aria-label={title}
className="ml-auto flex h-9 w-9 shrink-0 rounded-full p-0 text-muted-foreground">
<SquarePen className="h-4 w-4" aria-hidden />
</Button>
</DialogTrigger></TooltipTrigger>
<TooltipContent>{t("settings.actions.edit")}</TooltipContent>
</Tooltip></TooltipProvider>
<DialogContent className="max-w-xl" showCloseButton={!saving}
onOpenAutoFocus={(event) => { event.preventDefault(); editor.current?.focus(); }}
onEscapeKeyDown={(event) => { if (saving) event.preventDefault(); }}
onPointerDownOutside={(event) => { if (saving) event.preventDefault(); }}>
<DialogHeader>
<DialogTitle className="pr-6 text-base">{title}</DialogTitle>
<DialogDescription>{description || title}</DialogDescription>
</DialogHeader>
<Textarea ref={editor} aria-label={title} value={draft} placeholder={placeholder} disabled={saving}
aria-invalid={Boolean(error)} spellCheck={false}
onChange={(event) => { setDraft(event.target.value); setError(""); }}
className="h-[min(40vh,280px)] min-h-24 resize-none rounded-xl font-mono text-[13px] leading-6" />
{error && <p role="alert" className="break-words text-[13px] text-destructive">{error}</p>}
<DialogFooter>
<Button type="button" variant="outline" disabled={saving} onClick={() => setOpen(false)}>{t("settings.actions.cancel")}</Button>
<Button type="button" disabled={saving} onClick={() => void save()}>{t(saving ? "settings.actions.saving" : "settings.actions.save")}</Button>
</DialogFooter>
</DialogContent>
</Dialog>;
}
@@ -0,0 +1,66 @@
import { useMemo, useState, type ComponentProps } from "react";
import { ChevronDown } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { ComboboxOption, useComboboxNavigation } from "@/components/ui/combobox";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
export function TimezonePicker({ value, onChange, ...triggerProps }: {
value: string;
onChange: (value: string) => void;
} & Pick<ComponentProps<typeof Button>, "id" | "aria-label" | "aria-describedby" | "aria-invalid" | "disabled">) {
const { t, i18n } = useTranslation();
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const options = useMemo(() => {
const now = new Date();
return [...new Set(["UTC", ...Intl.supportedValuesOf("timeZone"), value].filter(Boolean))]
.sort().map((zone) => {
try {
const name = new Intl.DateTimeFormat(i18n.language, { timeZone: zone, timeZoneName: "longGeneric" })
.formatToParts(now).find((part) => part.type === "timeZoneName")?.value ?? zone;
const offset = new Intl.DateTimeFormat("en", { timeZone: zone, timeZoneName: "longOffset" })
.formatToParts(now).find((part) => part.type === "timeZoneName")?.value ?? "";
return { zone, detail: `${name} · ${offset.replace("GMT", "UTC")}` };
} catch {
// Keep a server-supported timezone visible even if this browser cannot format it.
return { zone, detail: zone };
}
});
}, [i18n.language, value]);
const filtered = options.filter(({ zone, detail }) =>
`${zone.replaceAll("_", " ")} ${zone} ${detail}`.toLocaleLowerCase(i18n.language)
.includes(query.trim().toLocaleLowerCase(i18n.language)));
const select = (zone: string) => { onChange(zone); setOpen(false); };
const navigation = useComboboxNavigation({
open, values: filtered.map(({ zone }) => zone), selectedValue: value,
onSelect: select, onClose: () => setOpen(false),
});
return (
<Popover open={open} onOpenChange={(next) => { setOpen(next); setQuery(""); }}>
<PopoverTrigger asChild>
<Button {...triggerProps} type="button" variant="outline"
className="h-9 w-full justify-between rounded-full border-input bg-background px-3 text-[13px] font-normal shadow-none">
<span className="truncate">{value}</span>
<ChevronDown className="ml-2 h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-80 max-w-[calc(100vw-2rem)] p-1.5">
<Input {...navigation.inputProps} value={query} onChange={(event) => setQuery(event.target.value)}
aria-label={t("sidebar.searchAria")} placeholder={t("sidebar.searchPlaceholder")}
className="mb-1.5 h-9 rounded-full" />
<div {...navigation.listProps} aria-label={triggerProps["aria-label"]} className="max-h-64 overflow-y-auto">
{filtered.map(({ zone, detail }) => (
<ComboboxOption key={zone} {...navigation.getOptionProps(zone)} className="block">
<span className="block">{zone}</span>
<span className="block text-xs text-muted-foreground">{detail}</span>
</ComboboxOption>
))}
</div>
{!filtered.length ? <p role="status" className="p-2 text-xs text-muted-foreground">{t("settings.timezoneNoMatches")}</p> : null}
</PopoverContent>
</Popover>
);
}
@@ -0,0 +1,18 @@
import { useEffect, useRef } from "react";
/** Save a valid draft once per edit; failures wait for another edit or explicit retry. */
export function useAutoSave(value: unknown, dirty: boolean, saving: boolean, onSave: () => void, enabled = true) {
const latest = useRef(onSave);
latest.current = onSave;
const attempted = useRef<string | null>(null);
const signature = JSON.stringify(value);
useEffect(() => {
if (!dirty) { attempted.current = null; return; }
if (!enabled || saving || attempted.current === signature) return;
const timer = window.setTimeout(() => {
attempted.current = signature;
latest.current();
}, 600);
return () => window.clearTimeout(timer);
}, [signature, dirty, saving, enabled]);
}
@@ -48,6 +48,7 @@ import {
import { Input } from "@/components/ui/input";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { Textarea } from "@/components/ui/textarea";
import { SettingsTextEditor } from "@/components/settings/shared/SettingsTextEditor";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { isGenericRepositoryLogoUrl, logoFallbackUrls } from "@/lib/provider-brand";
import type {
@@ -245,7 +246,7 @@ export function AppsCatalogSettings({
)
: "";
return (
<div className="space-y-7">
<div className="settings-stack">
<div role="status" className="sr-only">{oauthStatusAnnouncement}</div>
<section className="space-y-4">
<div className="flex flex-col gap-3 lg:flex-row lg:items-center">
@@ -303,7 +304,7 @@ export function AppsCatalogSettings({
{loading ? (
<div className="flex h-36 items-center justify-center text-sm text-muted-foreground">
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />
{tx("settings.apps.loading", "Loading Apps...")}
{tx("settings.apps.loading", "Loading apps…")}
</div>
) : items.length ? (
<div className="grid grid-cols-1 gap-x-10 gap-y-1 py-3 xl:grid-cols-2">
@@ -412,7 +413,7 @@ function CliAppsCatalogRow({
const description = app.description || app.requires || app.entry_point || app.name;
return (
<article className="apps-catalog-row group flex min-w-0 items-center gap-3 rounded-control px-3 py-3 transition-colors hover:bg-muted/45">
<article className="apps-catalog-row group flex min-w-0 items-center gap-3 rounded-control px-3 py-3 transition-colors settings-hover">
<CliAppLogo app={app} showBrandLogos={showBrandLogos} />
<div className="min-w-0 flex-1">
<div className="flex min-w-0 items-baseline gap-2">
@@ -583,7 +584,7 @@ function McpAppsCatalogRow({
};
return (
<article className="min-w-0 rounded-control transition-colors hover:bg-muted/45">
<article className="min-w-0 rounded-control transition-colors settings-hover">
<div className="group flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 px-3 py-3">
<McpPresetLogo preset={preset} showBrandLogos={showBrandLogos} />
<div className="min-w-[8rem] flex-[1_1_8rem]">
@@ -918,9 +919,9 @@ export const AppsActionButton = forwardRef<HTMLButtonElement, AppsActionButtonPr
visibleLabel
? "h-8 w-auto gap-1.5 px-3 text-[12px] font-semibold"
: "h-9 w-9",
tone === "installed" && "bg-transparent hover:bg-muted/70 hover:text-foreground",
tone === "installed" && "bg-transparent settings-hover hover:text-foreground",
tone === "danger" && "bg-transparent hover:bg-destructive/10 hover:text-destructive",
tone === "default" && "bg-muted/70 hover:bg-muted hover:text-foreground",
tone === "default" && "bg-muted/70 settings-hover hover:text-foreground",
className,
)}
>
@@ -1146,16 +1147,12 @@ function McpCustomServerPanel({
htmlFor={headersInputId}
className="mb-1 block text-[11.5px] font-medium text-muted-foreground"
>
{tx("settings.mcp.headers", "Headers JSON")}
{tx("settings.mcp.headers", "Headers (JSON)")}
</label>
<Textarea
id={headersInputId}
aria-describedby={headersHelpId}
value={form.headers}
onChange={(event) => update("headers", event.target.value)}
placeholder={'{"Authorization":"Bearer ..."}'}
className="min-h-[68px] resize-y bg-background/80 font-mono text-[12px]"
/>
<SettingsTextEditor id={headersInputId} title={tx("settings.mcp.headers", "Headers (JSON)")}
value={form.headers} onSave={(value) => update("headers", value)}
placeholder={'{"Authorization":"Bearer ..."}'}
/>
<p
id={headersHelpId}
className="mt-1 text-[11.5px] leading-5 text-muted-foreground"
@@ -1180,7 +1177,7 @@ function McpCustomServerPanel({
aria-hidden
/>
{advancedOpen
? tx("settings.mcp.hideAdvanced", "Hide advanced")
? tx("settings.mcp.hideAdvanced", "Hide advanced options")
: tx("settings.mcp.advancedOptions", "Advanced options")}
</Button>
@@ -1196,30 +1193,26 @@ function McpCustomServerPanel({
{!remote ? (
<label className="min-w-0">
<span className="mb-1 block text-[11.5px] font-medium text-muted-foreground">
{tx("settings.mcp.args", "Args JSON")}
{tx("settings.mcp.args", "Arguments (JSON)")}
</span>
<Textarea
value={form.args}
onChange={(event) => update("args", event.target.value)}
placeholder={'["-y", "docs-mcp"]'}
className="min-h-[68px] resize-y bg-background/80 font-mono text-[12px]"
/>
<SettingsTextEditor title={tx("settings.mcp.args", "Arguments (JSON)")}
value={form.args} onSave={(value) => update("args", value)}
placeholder={'["-y", "docs-mcp"]'}
/>
</label>
) : null}
<label className="min-w-0">
<span className="mb-1 block text-[11.5px] font-medium text-muted-foreground">
{tx("settings.mcp.env", "Env JSON")}
{tx("settings.mcp.env", "Environment variables (JSON)")}
</span>
<Textarea
value={form.env}
onChange={(event) => update("env", event.target.value)}
<SettingsTextEditor title={tx("settings.mcp.env", "Environment variables (JSON)")}
value={form.env} onSave={(value) => update("env", value)}
placeholder={'{"API_KEY":"..."}'}
className="min-h-[68px] resize-y bg-background/80 font-mono text-[12px]"
/>
</label>
<label className="min-w-0">
<span className="mb-1 block text-[11.5px] font-medium text-muted-foreground">
{tx("settings.mcp.timeout", "Tool timeout")}
{tx("settings.mcp.timeout", "Tool timeout (seconds)")}
</span>
<Input
value={form.toolTimeout}
@@ -1240,7 +1233,7 @@ function McpCustomServerPanel({
className="h-9 w-full rounded-full px-4 text-[12.5px] font-semibold sm:w-auto"
>
{customBusy ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden /> : <Check className="mr-1.5 h-3.5 w-3.5" aria-hidden />}
{tx("settings.mcp.saveCustom", "Save MCP")}
{tx("settings.mcp.saveCustom", "Save MCP server")}
</Button>
</div>
</div>
@@ -1253,11 +1246,9 @@ function McpCustomServerPanel({
<span className="mb-1.5 block text-[11.5px] font-medium text-muted-foreground">
{tx("settings.mcp.configImport", "Import mcp.json")}
</span>
<Textarea
value={configImport}
onChange={(event) => onConfigImportChange(event.target.value)}
<SettingsTextEditor title={tx("settings.mcp.configImport", "Import mcp.json")}
value={configImport} onSave={onConfigImportChange}
placeholder={'{"mcpServers":{"docs":{"command":"npx","args":["-y","docs-mcp"]}}}'}
className="min-h-[84px] resize-y bg-background/80 font-mono text-[12px]"
/>
</label>
<Button
@@ -1295,7 +1286,7 @@ function mcpOAuthStatusText(
}
return popupBlocked
? tx("settings.mcp.openSignInToContinue", "Open the sign-in page to continue.")
: tx("settings.mcp.finishSignInInBrowser", "Finish signing in in the browser window.");
: tx("settings.mcp.finishSignInInBrowser", "Complete sign-in in the browser window.");
case "connecting":
return tx("settings.mcp.finishingConnection", "Finishing connection...");
case "authorized":
@@ -1433,7 +1424,7 @@ function CliAppReadyPanel({
size="sm"
variant="ghost"
onClick={copyPrompt}
className="h-8 rounded-full px-3 text-[12px] font-medium text-muted-foreground hover:bg-muted/65 hover:text-foreground"
className="h-8 rounded-full px-3 text-[12px] font-medium text-muted-foreground settings-hover hover:text-foreground"
>
{copied ? <Check className="mr-1.5 h-3.5 w-3.5" aria-hidden /> : null}
{copied
@@ -166,7 +166,7 @@ export function AutomationsSettings({
"Search task, message, linked chat, or schedule",
)}
className={cn(
"h-9 w-full rounded-control pl-9 text-[13px]",
"h-9 w-full rounded-full pl-9 text-[13px]",
SETTINGS_SEARCH_INPUT_CLASS,
)}
/>
@@ -175,7 +175,7 @@ export function AutomationsSettings({
<DropdownMenuTrigger asChild>
<button
type="button"
className="inline-flex h-9 min-w-[8.5rem] items-center justify-center gap-1.5 whitespace-nowrap rounded-control border border-border/45 bg-settings-surface px-3 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground sm:w-auto"
className="inline-flex h-9 min-w-[8.5rem] items-center justify-center gap-1.5 whitespace-nowrap rounded-control border border-border/45 bg-settings-surface px-3 text-[12px] font-medium text-muted-foreground transition-colors settings-hover hover:text-foreground sm:w-auto"
>
<ArrowUpDown className="h-3.5 w-3.5" aria-hidden />
<span>{sortLabel[sort]}</span>
@@ -316,7 +316,7 @@ function AutomationListItem({
"group grid w-full grid-cols-[minmax(0,1fr)_auto] gap-3 rounded-floating px-3 py-3.5 text-left transition-colors",
selected
? "bg-background/80 text-foreground"
: "text-muted-foreground hover:bg-background/55 hover:text-foreground",
: "text-muted-foreground settings-hover hover:text-foreground",
)}
>
<span className="min-w-0">
@@ -1070,27 +1070,27 @@ function automationEditDraftError(
job: SessionAutomationJob | null,
tx: (key: string, fallback: string, values?: Record<string, unknown>) => string,
): string | null {
if (!draft.name.trim()) return tx("settings.automations.validation.nameRequired", "Name is required.");
if (!draft.name.trim()) return tx("settings.automations.validation.nameRequired", "Enter a task name.");
if (isLocalTriggerAutomation(job)) return null;
if (!draft.message.trim()) {
return tx("settings.automations.validation.messageRequired", "Message is required.");
return tx("settings.automations.validation.messageRequired", "Enter a task message.");
}
if (draft.scheduleKind === "every") {
const value = Number(draft.everyValue);
if (!Number.isInteger(value) || value <= 0) {
return tx("settings.automations.validation.intervalRequired", "Interval must be a positive number.");
return tx("settings.automations.validation.intervalRequired", "Enter a positive whole number for the interval.");
}
}
if (draft.scheduleKind === "cron" && !draft.cronExpr.trim()) {
return tx("settings.automations.validation.cronRequired", "Cron expression is required.");
return tx("settings.automations.validation.cronRequired", "Enter a Cron expression.");
}
if (draft.scheduleKind === "at") {
const atMs = new Date(draft.atLocal).getTime();
if (!Number.isFinite(atMs)) {
return tx("settings.automations.validation.timeRequired", "Run time is required.");
return tx("settings.automations.validation.timeRequired", "Choose a run time.");
}
if (atMs <= Date.now() && automationScheduleChanged(draft, job)) {
return tx("settings.automations.validation.futureRequired", "Run time must be in the future.");
return tx("settings.automations.validation.futureRequired", "Choose a time in the future.");
}
}
return null;
@@ -1,52 +1,26 @@
import { useEffect, useRef, useState } from "react";
import { ChevronLeft, Loader2, Search } from "lucide-react";
import { useRef, useState } from "react";
import { Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import {
channelIsRunning,
channelMatchesFilter,
channelSearchText,
localizedChannelDisplayName,
type ChannelFilter,
} from "@/components/settings/channels/ChannelIdentity";
import { localizedChannelDisplayName } from "@/components/settings/channels/ChannelIdentity";
import { ChannelCatalogRow, ChannelSetupPanel } from "@/components/settings/channels/ChannelSetupPanel";
import {
DismissibleStatusMessage,
RestartRequiredNotice,
SETTINGS_SEARCH_INPUT_CLASS,
} from "@/components/settings/shared/SettingsControls";
import { Input } from "@/components/ui/input";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import { DismissibleStatusMessage, RestartRequiredNotice, SettingsGroup } from "@/components/settings/shared/SettingsControls";
import type { NanobotFeaturesPayload } from "@/lib/types";
import { cn } from "@/lib/utils";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
export function ChannelsSettings({
token,
nanobotFeatures,
loading,
query,
actionKey,
chatAppsDocsUrl,
showBrandLogos,
error,
requiresRestartPending,
onQueryChange,
onAction,
onFeaturesUpdate,
onDismissStatus,
onRestart,
isRestarting,
token, nanobotFeatures, loading, actionKey, chatAppsDocsUrl, showBrandLogos,
error, requiresRestartPending, onAction, onFeaturesUpdate, onDismissStatus,
onRestart, isRestarting,
}: {
token: string;
nanobotFeatures: NanobotFeaturesPayload | null;
loading: boolean;
query: string;
actionKey: string | null;
chatAppsDocsUrl?: string;
showBrandLogos: boolean;
error: string | null;
requiresRestartPending: boolean;
onQueryChange: (value: string) => void;
onAction: (action: "enable" | "disable", name: string) => void;
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
onDismissStatus: () => void;
@@ -54,204 +28,58 @@ export function ChannelsSettings({
isRestarting?: boolean;
}) {
const { t } = useTranslation();
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
const normalizedQuery = query.trim().toLowerCase();
const [filter, setFilter] = useState<ChannelFilter>("all");
const splitLayout = useMediaQuery("(min-width: 1280px)");
const containerRef = useRef<HTMLDivElement>(null);
const compactDetailTopRef = useRef<HTMLButtonElement>(null);
const [compactDetailOpen, setCompactDetailOpen] = useState(false);
const allChannels = (nanobotFeatures?.features ?? [])
.filter((feature) => feature.type === "channel")
.filter((feature) => feature.settings_visible !== false)
.filter((feature) => !normalizedQuery || channelSearchText(feature, t).includes(normalizedQuery))
.sort((left, right) => {
const rank = Number(!left.ready) - Number(!right.ready);
return rank || localizedChannelDisplayName(left, t).localeCompare(
localizedChannelDisplayName(right, t),
);
});
const channels = allChannels.filter((feature) => channelMatchesFilter(feature, filter));
const [selectedChannelName, setSelectedChannelName] = useState<string | null>(null);
const selectedChannel =
channels.find((feature) => feature.name === selectedChannelName) ?? channels[0] ?? null;
const enabledCount = allChannels.filter(channelIsRunning).length;
const offCount = Math.max(0, allChannels.length - enabledCount);
const filterOptions: Array<{ value: ChannelFilter; label: string; count: number }> = [
{ value: "all", label: tx("settings.channels.filterAll", "All"), count: allChannels.length },
{ value: "on", label: tx("settings.channels.filterOn", "On"), count: enabledCount },
{ value: "off", label: tx("settings.channels.filterOff", "Off"), count: offCount },
];
const statusMessage = error;
const statusIsError = true;
useEffect(() => {
if (!channels.length) {
if (selectedChannelName !== null) setSelectedChannelName(null);
setCompactDetailOpen(false);
return;
}
if (!selectedChannelName || !channels.some((feature) => feature.name === selectedChannelName)) {
setSelectedChannelName(channels[0].name);
setCompactDetailOpen(false);
}
}, [channels, selectedChannelName]);
useEffect(() => {
if (splitLayout) return;
const resetScroll = () => {
let node = containerRef.current?.parentElement ?? null;
while (node) {
node.scrollTop = 0;
node = node.parentElement;
}
if (compactDetailOpen) {
compactDetailTopRef.current?.scrollIntoView?.({ block: "start" });
}
};
resetScroll();
const frame = window.requestAnimationFrame(resetScroll);
return () => window.cancelAnimationFrame(frame);
}, [compactDetailOpen, selectedChannelName, splitLayout]);
const openChannel = (name: string) => {
setSelectedChannelName(name);
if (!splitLayout) setCompactDetailOpen(true);
};
const setupPanel = selectedChannel ? (
<ChannelSetupPanel
token={token}
feature={selectedChannel}
actionKey={actionKey}
chatAppsDocsUrl={chatAppsDocsUrl}
showBrandLogos={showBrandLogos}
onAction={onAction}
onFeaturesUpdate={onFeaturesUpdate}
/>
) : null;
const showingCompactDetail = !splitLayout && compactDetailOpen && selectedChannel !== null;
const [connectRequestId, setConnectRequestId] = useState(0);
const triggerRef = useRef<HTMLElement | null>(null);
const dialogRef = useRef<HTMLDivElement | null>(null);
const channels = (nanobotFeatures?.features ?? [])
.filter((feature) => feature.type === "channel" && feature.settings_visible !== false)
.sort((left, right) => Number(!left.ready) - Number(!right.ready)
|| localizedChannelDisplayName(left, t).localeCompare(localizedChannelDisplayName(right, t)));
const selectedChannel = channels.find((feature) => feature.name === selectedChannelName);
return (
<div
ref={containerRef}
className="flex min-h-full flex-1 flex-col xl:min-h-0 xl:overflow-hidden"
>
{!showingCompactDetail ? (
<section className="shrink-0 space-y-4">
<div className="flex flex-col gap-3 lg:flex-row lg:items-center">
<div className="relative min-w-0 flex-1">
<Search className="pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden />
<Input
value={query}
onChange={(event) => onQueryChange(event.target.value)}
placeholder={tx("settings.channels.searchPlaceholder", "Search channels")}
className={cn(
"h-12 rounded-control pl-11 text-[15px]",
SETTINGS_SEARCH_INPUT_CLASS,
)}
/>
</div>
<div className="flex shrink-0 flex-wrap gap-1.5 rounded-control bg-muted/55 p-1">
{filterOptions.map((option) => (
<button
key={option.value}
type="button"
onClick={() => setFilter(option.value)}
className={cn(
"rounded-control px-3 py-1.5 text-[12px] font-medium transition-colors",
filter === option.value
? "bg-background text-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
{option.label}
<span className="ml-1 text-[11px] text-muted-foreground">{option.count}</span>
</button>
))}
</div>
</div>
</section>
) : null}
{statusMessage ? (
<div className="mt-3 shrink-0">
<DismissibleStatusMessage
message={statusMessage}
isError={statusIsError}
onDismiss={onDismissStatus}
/>
</div>
) : null}
<div className="settings-stack">
{error ? <DismissibleStatusMessage message={error} isError onDismiss={onDismissStatus} /> : null}
{requiresRestartPending ? (
<div className="mt-3 shrink-0">
<RestartRequiredNotice
message={tx("settings.channels.restartRequired", "Restart nanobot to apply updated channel support.")}
onRestart={onRestart}
isRestarting={isRestarting}
/>
</div>
<RestartRequiredNotice message={t("settings.channels.restartRequired")}
onRestart={onRestart} isRestarting={isRestarting} />
) : null}
<section
className={cn(
"flex flex-1 flex-col",
showingCompactDetail ? "mt-1" : "mt-5",
splitLayout && "min-h-0 overflow-hidden",
)}
>
{loading && !nanobotFeatures ? (
<div className="flex h-36 items-center justify-center text-sm text-muted-foreground">
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />
{tx("settings.channels.loading", "Loading Channels...")}
</div>
) : channels.length ? splitLayout ? (
<div className="grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)_minmax(400px,460px)] gap-6 overflow-hidden">
<div className="min-h-0 space-y-1 overflow-y-auto overscroll-contain pr-1">
{channels.map((feature) => (
<ChannelCatalogRow
key={feature.name}
feature={feature}
selected={selectedChannel?.name === feature.name}
showBrandLogos={showBrandLogos}
onSelect={() => openChannel(feature.name)}
/>
))}
</div>
<div className="min-h-0 overflow-y-auto overscroll-contain pr-1">{setupPanel}</div>
</div>
) : showingCompactDetail ? (
<div className="pb-6">
<button
ref={compactDetailTopRef}
type="button"
onClick={() => setCompactDetailOpen(false)}
className="mb-4 inline-flex h-9 items-center gap-1.5 rounded-full px-2.5 text-[13px] font-medium text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground"
>
<ChevronLeft className="h-4 w-4" aria-hidden />
{tx("settings.channels.backToChannels", "All channels")}
</button>
{setupPanel}
</div>
) : (
<div className="space-y-1 pb-6">
{channels.map((feature) => (
<ChannelCatalogRow
key={feature.name}
feature={feature}
selected={false}
showBrandLogos={showBrandLogos}
onSelect={() => openChannel(feature.name)}
/>
))}
</div>
) : (
<div className="min-h-0 flex-1 px-3 py-12 text-center text-sm text-muted-foreground">
{tx("settings.channels.empty", "No channels match this filter.")}
</div>
)}
</section>
{loading && !nanobotFeatures ? (
<div className="flex h-36 items-center justify-center text-sm text-muted-foreground">
<Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden />
{t("settings.channels.loading")}
</div>
) : channels.length ? (
<SettingsGroup>
{channels.map((feature) => (
<ChannelCatalogRow key={feature.name} feature={feature} showBrandLogos={showBrandLogos}
actionKey={actionKey} onAction={onAction}
onSelect={(connect = false) => {
triggerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
setConnectRequestId(connect ? 1 : 0);
setSelectedChannelName(feature.name);
}} />
))}
</SettingsGroup>
) : (
<div className="px-3 py-12 text-center text-sm text-muted-foreground">
{t("settings.channels.empty")}
</div>
)}
<Dialog open={Boolean(selectedChannel)} onOpenChange={(open) => { if (!open) setSelectedChannelName(null); }}>
<DialogContent ref={dialogRef} aria-describedby={undefined} className="max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none overflow-y-auto p-0 outline-none"
onOpenAutoFocus={(event) => {
event.preventDefault();
dialogRef.current?.focus({ preventScroll: true });
}}
onCloseAutoFocus={(event) => { event.preventDefault(); triggerRef.current?.focus(); }}>
<DialogTitle className="sr-only">{t("settings.nav.channels")}</DialogTitle>
{selectedChannel ? <ChannelSetupPanel token={token} feature={selectedChannel} actionKey={actionKey}
chatAppsDocsUrl={chatAppsDocsUrl} showBrandLogos={showBrandLogos}
onAction={onAction} onFeaturesUpdate={onFeaturesUpdate} connectRequestId={connectRequestId} /> : null}
</DialogContent>
</Dialog>
</div>
);
}
@@ -449,7 +449,7 @@ function ToolsPanel({
return (
<label
key={toolName}
className="flex min-h-11 cursor-pointer items-center gap-3 border-b border-border/45 px-3.5 py-2.5 transition-colors last:border-b-0 hover:bg-muted/35 has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-inset has-[:focus-visible]:ring-ring"
className="flex min-h-11 cursor-pointer items-center gap-3 border-b border-border/45 px-3.5 py-2.5 transition-colors last:border-b-0 settings-hover has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-inset has-[:focus-visible]:ring-ring"
>
<span className="relative h-5 w-5 shrink-0">
<input
@@ -598,7 +598,7 @@ function ConnectionPanel({
{field.label}
{field.configured ? (
<span className="font-normal text-emerald-600 dark:text-emerald-300">
· {tx("settings.mcp.configured", "configured")}
· {tx("settings.mcp.configured", "Configured")}
</span>
) : null}
</span>
@@ -607,7 +607,7 @@ function ConnectionPanel({
type={field.secret ? "password" : "text"}
value={values[field.name] ?? ""}
onChange={(event) => onFieldChange(preset.name, field.name, event.target.value)}
placeholder={field.configured ? tx("settings.mcp.keepExisting", "Leave blank to keep existing") : field.placeholder}
placeholder={field.configured ? tx("settings.mcp.keepExisting", "Leave blank to keep the current value") : field.placeholder}
className="h-10 rounded-full bg-muted/35 text-[12.5px]"
/>
</label>
@@ -0,0 +1,238 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { ToggleButton } from "@/components/settings/ToggleButton";
import { SettingsGroup, SettingsRow, SettingsSectionTitle, RestartRequiredNotice, RestartSettingsFooter } from "@/components/settings/shared/SettingsControls";
import { ProviderPicker } from "@/components/settings/shared/ModelControls";
import { TimezonePicker } from "@/components/settings/shared/TimezonePicker";
import { SettingsTextEditor } from "@/components/settings/shared/SettingsTextEditor";
import { Input } from "@/components/ui/input";
import { RUNTIME_CONFIG_FIELDS, RUNTIME_CONFIG_GROUPS, type RuntimeConfigField, type RuntimeConfigPage } from "@/components/settings/system/runtime-config-fields";
import { updateRuntimeConfigSettings } from "@/lib/api";
import type { NanobotClient } from "@/lib/nanobot-client";
import type { RuntimeConfigValue, SettingsPayload } from "@/lib/types";
import type { ApplySettingsPayload } from "@/components/settings/contracts";
type Draft = string | boolean;
function displayValue(value: RuntimeConfigValue | undefined): Draft {
if (typeof value === "boolean") return value;
if (Array.isArray(value)) return value.join("\n");
return value == null ? "" : String(value);
}
export function useRuntimeConfigSettings(
settings: SettingsPayload | null,
client: NanobotClient,
applyPayload: ApplySettingsPayload,
) {
const { t } = useTranslation();
const [drafts, setDrafts] = useState<Record<string, Draft>>({});
const [saving, setSaving] = useState<string | null>(null);
const [errors, setErrors] = useState<Record<string, string>>({});
const [invalidField, setInvalidField] = useState<string | null>(null);
const delay = useRef(600);
const saveLatest = useRef<(group: string) => Promise<void>>(async () => {});
const pendingGroups = useRef<string[]>([]);
const queuedSaves = useRef<string[]>([]);
const [saved, setSaved] = useState<Record<string, boolean>>({});
useEffect(() => {
if (invalidField && saving === null) document.getElementById(`runtime-${invalidField}`)?.focus();
}, [invalidField, saving]);
const value = (path: string): Draft => drafts[path] ?? displayValue(settings?.runtime_config?.[path]);
const visible = (field: RuntimeConfigField) => !field.when || (Array.isArray(field.when.value)
? field.when.value.includes(String(value(field.when.path)))
: value(field.when.path) === field.when.value);
const dirty = (field: RuntimeConfigField) =>
drafts[field.path] !== undefined && drafts[field.path] !== displayValue(settings?.runtime_config?.[field.path]);
const discard = (group: string) => {
setDrafts((prev) => Object.fromEntries(Object.entries(prev).filter(([path]) =>
!RUNTIME_CONFIG_FIELDS.some((field) => field.group === group && field.path === path),
)));
setErrors((prev) => ({ ...prev, [group]: "" }));
setInvalidField(null);
};
const change = (field: RuntimeConfigField, next: Draft) => {
delay.current = ["boolean", "toggle", "select", "preset"].includes(field.kind) ? 0 : 600;
setDrafts((prev) => ({ ...prev, [field.path]: next }));
setSaved((prev) => ({ ...prev, [field.group]: false }));
setErrors((prev) => ({ ...prev, [field.group]: "" }));
setInvalidField(null);
};
const save = async (group: string) => {
if (!settings?.runtime_config) return;
if (saving) {
if (!queuedSaves.current.includes(group)) queuedSaves.current.push(group);
return;
}
const changed = RUNTIME_CONFIG_FIELDS.filter((field) => field.group === group && visible(field) && dirty(field));
if (!changed.length) return;
const values: Record<string, RuntimeConfigValue> = {};
for (const field of changed) {
const raw = value(field.path);
if (field.kind === "number") {
const parsed = Number(raw);
if (String(raw).trim() === "" || !Number.isFinite(parsed)
|| (field.path !== "api.timeout" && !Number.isInteger(parsed))
|| (field.min !== undefined && parsed < field.min)
|| (field.max !== undefined && parsed > field.max)) {
setErrors((prev) => ({ ...prev, [group]: t("settings.runtimeConfig.numberError") }));
setInvalidField(field.path);
return;
}
values[field.path] = parsed;
} else if (field.kind === "list") {
values[field.path] = String(raw).split("\n").map((line) => line.trim()).filter(Boolean);
} else if (field.kind === "nullable" || field.kind === "preset") {
values[field.path] = String(raw).trim() || null;
} else {
values[field.path] = raw;
}
}
setSaving(group);
setErrors((prev) => ({ ...prev, [group]: "" }));
try {
const payload = await updateRuntimeConfigSettings(client, values);
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
discard(group);
setSaved((prev) => ({ ...prev, [group]: true }));
} catch (error) {
const message = (error as Error).message;
setErrors((prev) => ({ ...prev, [group]: message }));
setInvalidField(changed.find((field) => message.startsWith(field.path))?.path ?? null);
} finally {
setSaving(null);
}
};
saveLatest.current = save;
pendingGroups.current = [...new Set(RUNTIME_CONFIG_FIELDS.filter((field) =>
visible(field) && dirty(field) && !errors[field.group]
&& !RUNTIME_CONFIG_FIELDS.some((other) => other.group === field.group && other.manual && dirty(other)),
).map((field) => field.group))];
useEffect(() => {
if (saving) return;
const timer = window.setTimeout(() => {
const group = queuedSaves.current.shift() ?? pendingGroups.current[0];
if (group) void saveLatest.current(group);
}, delay.current);
return () => window.clearTimeout(timer);
}, [drafts, saving]);
const saveList = async (field: RuntimeConfigField, next: string) => {
const payload = await updateRuntimeConfigSettings(client, {
[field.path]: next.split("\n").map((line) => line.trim()).filter(Boolean),
});
applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true });
setSaved((prev) => ({ ...prev, [field.group]: true }));
};
return { value, visible, dirty, discard, change, save, saveList, saving, errors, invalidField, saved };
}
export type RuntimeConfigController = ReturnType<typeof useRuntimeConfigSettings>;
export function RuntimeConfigSettings({
page, settings, state, onRestart, isRestarting, remoteBrowserAccess, children,
}: {
page: RuntimeConfigPage;
settings: SettingsPayload;
state: RuntimeConfigController;
onRestart?: () => void;
isRestarting: boolean;
remoteBrowserAccess: boolean;
children?: ReactNode;
}) {
const { t } = useTranslation();
const tr = (key: string) => t(`settings.runtimeConfig.${key}`);
if (!settings.runtime_config) return <div className="settings-stack">
<p className="settings-editor text-[13px] leading-5 text-muted-foreground">{tr("unavailable")}</p>
{children}
</div>;
const groups = RUNTIME_CONFIG_GROUPS.filter((group) => group.page === page);
const restartPending = settings.restart_required_sections?.includes("runtime")
|| (settings.requires_restart && Object.values(state.saved).some(Boolean));
return (
<div className="settings-stack">
{restartPending && onRestart ? <RestartRequiredNotice message={t("settings.status.savedRestartApply")}
onRestart={onRestart} isRestarting={isRestarting} /> : null}
{groups.map((group) => {
if (group.enabledBy && state.value(group.enabledBy) === false) return null;
if (group.id === "chat") return <div key={group.id}>{children}</div>;
const fields = RUNTIME_CONFIG_FIELDS.filter((field) => field.group === group.id);
const dirty = fields.filter(state.visible).some(state.dirty);
const title = tr(`groups.${group.id}.title`);
const errorId = `runtime-error-${group.id}`;
const section = (
<section key={group.id} aria-label={title}>
<SettingsSectionTitle>{title}</SettingsSectionTitle>
<form noValidate onSubmit={(event) => { event.preventDefault(); void state.save(group.id); }}>
<fieldset disabled={state.saving === group.id || isRestarting} className="min-w-0">
<legend className="sr-only">{title}</legend>
<button type="submit" hidden />
<SettingsGroup>
{fields.filter(state.visible).map((field) => {
const id = `runtime-${field.path}`;
const key = field.path.replaceAll(".", "_");
const text = tr(`fields.${key}.label`);
const help = tr(`fields.${key}.help`);
const current = state.value(field.path);
const disabled = (field.path === "agents.defaults.timezone" && state.value("agents.defaults.timezone_mode") === "auto")
|| (field.path === "tools.webui_allow_remote_package_install" && remoteBrowserAccess);
const common = {
id, disabled, "aria-label": text, "aria-describedby": `${id}-help${state.invalidField === field.path ? ` ${errorId}` : ""}`,
"aria-invalid": state.invalidField === field.path || undefined,
};
const options = field.kind === "preset"
? ["", ...new Set(["default", ...settings.model_presets.map((preset) => preset.name)])]
: [...field.options ?? []];
// Keep a configured preset visible if it is no longer available.
if (field.kind === "preset" && current && !options.includes(String(current))) options.push(String(current));
return (
<SettingsRow key={field.path} title={text} description={help}>
<span id={`${id}-help`} className="sr-only">{help}</span>
{field.kind === "boolean" || field.kind === "toggle" ? (
<ToggleButton {...common} checked={field.kind === "toggle" ? current === field.options?.[1] : current === true} label={text}
onChange={(next) => state.change(field, field.kind === "toggle" ? field.options![next ? 1 : 0] : next)} />
) : (
<div className="w-full">
{field.path === "agents.defaults.timezone" ? (
<TimezonePicker {...common} value={String(current)} onChange={(next) => state.change(field, next)} />
) : field.kind === "list" ? (
<SettingsTextEditor id={id} title={text} description={help} value={String(current)}
disabled={disabled || state.saving !== null || isRestarting}
onSave={(next) => state.saveList(field, next)} />
) : field.kind === "select" || field.kind === "preset" ? (
<ProviderPicker triggerProps={{ ...common, disabled: disabled || state.saving === group.id || isRestarting }}
value={String(current) || "__none__"} emptyLabel={tr("none")}
providers={options.map((option) => ({ name: option || "__none__", label:
!option ? tr(field.kind === "preset" ? "activeModel" : "none")
: ["auto", "manual", "standard", "persistent"].includes(option) ? tr(option) : option,
}))}
onChange={(next) => state.change(field, next === "__none__" ? "" : next)} />
) : (
<Input {...common} type={field.kind === "number" ? "number" : "text"}
min={field.min} max={field.max} step={field.path === "api.timeout" ? "any" : 1}
value={String(current)} className="h-9 rounded-full text-[13px]" autoComplete="off"
onChange={(event) => state.change(field, event.target.value)} />
)}
</div>
)}
</SettingsRow>
);
})}
<RestartSettingsFooter autoSave={!fields.some((field) => field.manual && state.dirty(field))} dirty={dirty} saving={state.saving === group.id}
error={Boolean(state.errors[group.id])}
disabled={state.saving === group.id || isRestarting}
pendingRestart={false}
message={state.saved[group.id] && !dirty ? tr("saved") : undefined}
onSave={() => void state.save(group.id)} onReset={() => state.discard(group.id)}
onRestart={onRestart} isRestarting={isRestarting} />
</SettingsGroup>
</fieldset>
{state.errors[group.id] ? <p id={errorId} role="alert" className="mt-2 break-words px-1 text-[12px] text-destructive">{state.errors[group.id]}</p> : null}
</form>
</section>
);
return section;
})}
</div>
);
}
@@ -91,11 +91,11 @@ export function RuntimeSettings({
const [apiKeyVisible, setApiKeyVisible] = useState(false);
useEffect(() => {
if (!apiService) return;
setApiHost(apiService.host);
setApiPort(apiService.port);
setApiHost(settings.api?.host ?? apiService.host);
setApiPort(settings.api?.port ?? apiService.port);
setApiKey("");
setApiKeyVisible(false);
}, [apiService]);
}, [apiService, settings.api?.host, settings.api?.port]);
const apiNetworkAccess = !isLoopbackHost(apiHost);
const apiMissingNetworkKey = apiNetworkAccess && !apiKey.trim() && !apiDefaults.api_key_hint;
const engineState = isRestarting
@@ -114,7 +114,7 @@ export function RuntimeSettings({
target,
message: tx(
"settings.status.hostApiUnavailable",
"Host actions are only available inside the native app.",
"These actions are only available in the desktop app.",
),
});
return;
@@ -131,7 +131,7 @@ export function RuntimeSettings({
}
};
return (
<div className="space-y-7">
<div className="settings-stack">
{isNativeHost ? (
<section>
<SettingsSectionTitle>{tx("settings.sections.nativeHost", "Native host")}</SettingsSectionTitle>
@@ -238,7 +238,7 @@ export function RuntimeSettings({
: {
host: apiHost,
port: apiPort,
timeout: apiDefaults.timeout,
timeout: settings.api?.timeout ?? apiDefaults.timeout,
apiKey: apiKey.trim() || undefined,
},
)
@@ -284,8 +284,7 @@ export function RuntimeSettings({
<SettingsRow title={tx("settings.api.port", "Port")}>
<NumberInput value={apiPort} min={1} max={65535} onChange={setApiPort} />
</SettingsRow>
{apiNetworkAccess ? (
<SettingsRow
<SettingsRow
title={tx("settings.api.apiKey", "API key")}
description={
apiMissingNetworkKey
@@ -293,7 +292,7 @@ export function RuntimeSettings({
: tx("settings.api.apiKeyHelp", "Clients send this as a Bearer token.")
}
>
<div className="relative w-[280px] max-w-full">
<div className="relative w-full">
<Input
type={apiKeyVisible ? "text" : "password"}
value={apiKey}
@@ -312,8 +311,7 @@ export function RuntimeSettings({
{apiKeyVisible ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
</Button>
</div>
</SettingsRow>
) : null}
</SettingsRow>
</>
) : null}
</SettingsGroup>
@@ -353,7 +351,7 @@ export function RuntimeSettings({
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
) : null}
{capabilityAction === "enable:langfuse"
? tx("settings.capabilities.installing", "Installing support...")
? tx("settings.capabilities.installing", "Installing required packages…")
: tx("settings.observability.enable", "Enable tracing support")}
</Button>
)}
@@ -372,14 +370,18 @@ export function RuntimeSettings({
/>
) : null}
<ReadOnlyRow title={t("settings.rows.configPath")} value={settings.runtime.config_path} />
<ReadOnlyRow title={tx("settings.rows.workspacePath", "Default workspace")} value={settings.runtime.workspace_path} />
<ReadOnlyRow title={tx("settings.rows.timezone", "Timezone")} value={form.timezone} />
{!settings.runtime_config ? (
<ReadOnlyRow title={tx("settings.rows.workspacePath", "Default workspace")} value={settings.runtime.workspace_path} />
) : null}
{!settings.runtime_config ? (
<ReadOnlyRow title={tx("settings.rows.timezone", "Timezone")} value={form.timezone} />
) : null}
{onRestart ? (
<SettingsRow
title={t("settings.rows.restart")}
description={
requiresRestartPending
? tx("settings.status.savedRestartApply", "Saved. Restart when ready.")
? tx("settings.status.savedRestartApply", "Saved. Restart to apply changes.")
: undefined
}
>
@@ -0,0 +1,70 @@
export interface RuntimeConfigField {
group: string;
path: string;
kind: "toggle" | "text" | "nullable" | "number" | "boolean" | "select" | "list" | "preset";
options?: string[];
when?: { path: string; value: string | boolean | string[] };
manual?: boolean;
min?: number;
max?: number;
}
export type RuntimeConfigPage = "memory" | "runtime" | "advanced" | "browser" | "image";
export const RUNTIME_CONFIG_GROUPS: { id: string; page: RuntimeConfigPage; enabledBy?: string }[] = [
{ id: "identity", page: "runtime" },
{ id: "memory", page: "memory" },
{ id: "chat", page: "advanced" },
{ id: "execution", page: "advanced" },
{ id: "sessions", page: "runtime" },
{ id: "tools", page: "runtime" },
{ id: "web", page: "browser" },
{ id: "shell", page: "advanced", enabledBy: "tools.exec.enable" },
{ id: "network", page: "advanced", enabledBy: "tools.web.enable" },
{ id: "safety", page: "advanced" },
{ id: "cli", page: "advanced", enabledBy: "tools.cli_apps.enable" },
{ id: "gateway", page: "advanced" },
{ id: "api", page: "advanced" },
{ id: "storage", page: "image" },
];
export const RUNTIME_CONFIG_FIELDS: RuntimeConfigField[] = [
{ group: "identity", path: "agents.defaults.timezone_mode", kind: "toggle", options: ["manual", "auto"] },
{ group: "identity", path: "agents.defaults.timezone", kind: "text", when: { path: "agents.defaults.timezone_mode", value: "manual" } },
{ group: "memory", path: "agents.defaults.dream.enabled", kind: "boolean" },
{ group: "execution", path: "agents.defaults.provider_retry_mode", kind: "toggle", options: ["standard", "persistent"] },
{ group: "execution", path: "agents.defaults.max_tool_iterations", kind: "number", min: 1 },
{ group: "execution", path: "agents.defaults.max_concurrent_subagents", kind: "number", min: 1 },
{ group: "execution", path: "agents.defaults.max_tool_result_chars", kind: "number", min: 1 },
{ group: "execution", path: "agents.defaults.tool_hint_max_length", kind: "number", min: 20, max: 500 },
{ group: "execution", path: "tools.max_session_messages_per_minute", kind: "number", min: 1 },
{ group: "sessions", path: "agents.defaults.unified_session", kind: "boolean" },
{ group: "tools", path: "tools.exec.enable", kind: "boolean" },
{ group: "tools", path: "tools.file.enable", kind: "boolean" },
{ group: "web", path: "tools.web.enable", kind: "boolean" },
{ group: "tools", path: "tools.my.enable", kind: "boolean" },
{ group: "tools", path: "tools.my.allow_set", kind: "boolean", when: { path: "tools.my.enable", value: true } },
{ group: "shell", path: "tools.exec.timeout", kind: "number", min: 0 },
{ group: "shell", path: "tools.exec.path_prepend", kind: "text" },
{ group: "shell", path: "tools.exec.path_append", kind: "text" },
{ group: "shell", path: "tools.exec.sandbox", kind: "select", options: ["", "bwrap", "seatbelt"] },
{ group: "shell", path: "tools.exec.sandbox_ro_binds", kind: "list", when: { path: "tools.exec.sandbox", value: ["bwrap", "seatbelt"] } },
{ group: "shell", path: "tools.exec.sandbox_rw_binds", kind: "list", when: { path: "tools.exec.sandbox", value: ["bwrap", "seatbelt"] } },
{ group: "shell", path: "tools.exec.allowed_env_keys", kind: "list" },
{ group: "shell", path: "tools.exec.allow_patterns", kind: "list" },
{ group: "shell", path: "tools.exec.deny_patterns", kind: "list" },
{ group: "network", path: "tools.web.proxy", kind: "nullable" },
{ group: "network", path: "tools.web.user_agent", kind: "nullable" },
{ group: "safety", path: "tools.restrict_to_workspace", kind: "boolean" },
{ group: "safety", path: "tools.webui_allow_remote_package_install", kind: "boolean" },
{ group: "safety", path: "tools.ssrf_whitelist", kind: "list" },
{ group: "cli", path: "tools.cli_apps.install_timeout", kind: "number", min: 1, max: 3600 },
{ group: "cli", path: "tools.cli_apps.run_timeout", kind: "number", min: 1, max: 600 },
{ group: "cli", path: "tools.cli_apps.catalog_ttl_seconds", kind: "number", min: 60, max: 86400 },
{ group: "gateway", path: "gateway.host", kind: "text", manual: true },
{ group: "gateway", path: "gateway.port", kind: "number", min: 1, max: 65535, manual: true },
{ group: "gateway", path: "gateway.restart_mode", kind: "select", options: ["auto", "exec", "spawn", "exit"] },
{ group: "api", path: "api.host", kind: "text", manual: true },
{ group: "api", path: "api.timeout", kind: "number", min: 1, max: 3600 },
{ group: "storage", path: "tools.image_generation.save_dir", kind: "text" },
];
@@ -85,7 +85,7 @@ export function useSystemSettingsEffects({
useEffect(() => {
if (
!pageVisible
|| !["channels", "models", "browser", "runtime"].includes(activeSection)
|| !["channels", "models", "browser", "image", "voice", "memory", "capabilities", "runtime"].includes(activeSection)
) {
return;
}
@@ -46,7 +46,6 @@ export function useSystemSettingsState() {
const [apiServiceAction, setApiServiceAction] = useState<"start" | "stop" | null>(null);
const [apiServiceError, setApiServiceError] = useState<string | null>(null);
const [appsQuery, setAppsQuery] = useState("");
const [channelsQuery, setChannelsQuery] = useState("");
const [automationsQuery, setAutomationsQuery] = useState("");
const [automationsFilter, setAutomationsFilter] = useState<AutomationFilter>("all");
const [automationsSort, setAutomationsSort] = useState<AutomationSort>("next");
@@ -83,7 +82,6 @@ export function useSystemSettingsState() {
automationsLoading,
automationsQuery,
automationsSort,
channelsQuery,
cliApps,
cliAppsAction,
cliAppsError,
@@ -126,7 +124,6 @@ export function useSystemSettingsState() {
setAutomationsLoading,
setAutomationsQuery,
setAutomationsSort,
setChannelsQuery,
setCliApps,
setCliAppsAction,
setCliAppsError,
@@ -12,7 +12,7 @@ import {
} from "@/components/settings/capabilities/TranscriptionSettings";
import { useCapabilitySettingsActions } from "@/components/settings/capabilities/useCapabilitySettingsActions";
import { useCapabilitySettingsState } from "@/components/settings/capabilities/useCapabilitySettingsState";
import { webSearchFormFromPayload } from "@/components/settings/capabilities/WebSettings";
import { webSearchDraftState, webSearchFormFromPayload } from "@/components/settings/capabilities/WebSettings";
import type {
ApplySettingsPayload,
PendingRestartSections,
@@ -27,10 +27,12 @@ import {
} from "@/components/settings/models/useModelSettingsEffects";
import { useModelSettingsState } from "@/components/settings/models/useModelSettingsState";
import { normalizeContextWindowTokens } from "@/components/settings/shared/ModelControls";
import { useRuntimeConfigSettings } from "@/components/settings/system/RuntimeConfigSettings";
import { createSystemSettingsActions } from "@/components/settings/system/createSystemSettingsActions";
import { useSystemSettingsEffects } from "@/components/settings/system/useSystemSettingsEffects";
import { useSystemSettingsState } from "@/components/settings/system/useSystemSettingsState";
import { usePageVisibility } from "@/hooks/usePageVisibility";
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
import { fetchSettings, fetchSettingsUsage } from "@/lib/api";
import {
readLocalPreferences,
@@ -115,14 +117,14 @@ export function useSettingsController({
apiService, apiServiceAction, apiServiceError, apiServiceLoading, appsKindFilter, appsQuery,
automationAction, automationPendingDelete, automationPendingEdit, automations,
automationsError, automationsFilter, automationsLoading, automationsQuery, automationsSort,
channelsQuery, cliApps, cliAppsAction, cliAppsError, cliAppsFocusName, cliAppsLoading,
cliApps, cliAppsAction, cliAppsError, cliAppsFocusName, cliAppsLoading,
cliAppsMessage, customMcpForm, mcpConfigImport, mcpError, mcpFieldValues, mcpMessage,
mcpOAuthCallbackError, mcpOAuthCallbackUrl, mcpOAuthCompleting, mcpOAuthFlow,
mcpOAuthPopupBlocked, mcpPresetAction, mcpPresets, mcpPresetsLoading, nanobotFeatureAction,
nanobotFeatureConfirm, nanobotFeatures, nanobotFeaturesError, nanobotFeaturesLoading,
setAppsKindFilter, setAppsQuery, setAutomationPendingDelete,
setAutomationPendingEdit, setAutomationsFilter,
setAutomationsQuery, setAutomationsSort, setChannelsQuery,
setAutomationsQuery, setAutomationsSort,
setCliAppsError,
setCliAppsMessage, setCustomMcpForm, setMcpConfigImport, setMcpError, setMcpFieldValues,
setMcpMessage, setMcpOAuthCallbackError, setMcpOAuthCallbackUrl,
@@ -145,7 +147,7 @@ export function useSettingsController({
const applyPayload: ApplySettingsPayload = useCallback(
(
payload: SettingsPayload,
options: { preserveAgentForm?: boolean } = {},
options: { preserveAgentForm?: boolean; preserveCapabilityForms?: boolean } = {},
) => {
setSettings(payload);
if (!options.preserveAgentForm) {
@@ -153,12 +155,16 @@ export function useSettingsController({
setForm(nextForm);
setModelPresetEditingName(nextForm.modelPreset);
setModelPresetCreating(false);
} else {
setForm((current) => ({ ...current, timezone: payload.agent.timezone }));
}
setModelCallOrder(payload.model_call_order ?? []);
setWebSearchForm((prev) => webSearchFormFromPayload(payload, prev));
setImageGenerationForm(imageGenerationFormFromPayload(payload));
setTranscriptionForm(transcriptionFormFromPayload(payload));
setNetworkSafetyForm(networkSafetyFormFromPayload(payload));
if (!options.preserveCapabilityForms) {
setWebSearchForm((prev) => webSearchFormFromPayload(payload, prev));
setImageGenerationForm(imageGenerationFormFromPayload(payload));
setTranscriptionForm(transcriptionFormFromPayload(payload));
setNetworkSafetyForm(networkSafetyFormFromPayload(payload));
}
if (payload.restart_required_sections) {
setPendingRestartSections(pendingRestartSectionsFromPayload(payload));
}
@@ -167,6 +173,8 @@ export function useSettingsController({
[onSettingsChange],
);
const runtimeConfigState = useRuntimeConfigSettings(settings, client, applyPayload);
const closeProviderOAuthFlow = useCallback(() => {
providerOAuthFlowRef.current = null;
setProviderOAuthFlow(null);
@@ -314,15 +322,6 @@ export function useSettingsController({
[settings],
);
const hasPendingRestart = useMemo(
() =>
!!settings?.requires_restart ||
pendingRestartSections.runtime ||
pendingRestartSections.browser ||
pendingRestartSections.image,
[pendingRestartSections, settings?.requires_restart],
);
const restartViaSettingsSurface = useCallback(async () => {
const isNativeHost = (settings?.surface ?? settings?.runtime_surface) === "native";
if (
@@ -412,7 +411,6 @@ export function useSettingsController({
applyPayload,
maybeRestartHostEngine,
setPendingRestartSections,
setError,
installCapabilities,
imageGenerationDirty,
transcriptionDirty,
@@ -441,6 +439,15 @@ export function useSettingsController({
saveTranscriptionSettings,
saveWebSearch,
} = capabilityActions;
useAutoSave(imageGenerationForm, imageGenerationDirty, imageGenerationSaving, saveImageGenerationSettings,
!imageGenerationForm.enabled || Boolean(settings?.image_generation.providers.find(
(provider) => provider.name === imageGenerationForm.provider,
)?.configured));
useAutoSave(transcriptionForm, transcriptionDirty, transcriptionSaving, saveTranscriptionSettings);
const webDraft = settings ? webSearchDraftState(settings, webSearchForm) : null;
useAutoSave(webSearchForm, webDraft?.dirty ?? false, webSearchSaving, saveWebSearch,
!webDraft?.missingCredential && (webSearchForm.provider !== "olostep" ||
featureCatalog.some((feature) => feature.name === "olostep" && feature.installed)));
const {
handleApiServiceAction,
handleAutomationAction,
@@ -459,6 +466,8 @@ export function useSettingsController({
return {
activeSection,
capabilityErrors: capabilityState.capabilityErrors,
runtimeConfigState,
apiService,
apiServiceAction,
apiServiceError,
@@ -477,7 +486,6 @@ export function useSettingsController({
beginModelPresetCreation,
cancelModelPresetCreation,
changeModelCallOrder,
channelsQuery,
cliApps,
cliAppsAction,
cliAppsError,
@@ -510,7 +518,6 @@ export function useSettingsController({
handleSaveCustomMcp,
handleToggleProvider,
handleWebSearchProviderChange,
hasPendingRestart,
hostEngineApplying,
imageGenerationDirty,
imageGenerationForm,
@@ -574,7 +581,6 @@ export function useSettingsController({
setAutomationsFilter,
setAutomationsQuery,
setAutomationsSort,
setChannelsQuery,
setCliAppsError,
setCliAppsMessage,
setCustomMcpForm,