refactor(webui): separate presentation views and expand component gallery (#6179)
* refactor(webui): organize shared components with an internal gallery * refactor(webui): decouple views and expand component gallery * fix(docker): include channel sources in WebUI build * refactor(webui): cover all channel interfaces in gallery * docs(webui): remove manual paragraph wrapping
This commit is contained in:
1 parent
db804ef94a
commit
30e43aec82
109 files changed
+7874
-3459
No files matched your search
@@ -32,7 +32,7 @@ import { SegmentedControl } from "@/components/ui/segmented-control";
|
||||
import { Sheet, SheetContent, SheetDescription, SheetTitle } from "@/components/ui/sheet";
|
||||
import { SkillsMarketplace } from "@/components/settings/SkillsMarketplace";
|
||||
import { CatalogSkeleton } from "@/components/settings/shared/CatalogSkeleton";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { deleteSkill, fetchSkillDetail, updateSkillEnabled } from "@/lib/api";
|
||||
import { notifySkillsChanged, requestSkillsRefresh } from "@/lib/skill-events";
|
||||
import type { SkillDetail, SkillSummary } from "@/lib/types";
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import type { ComponentProps } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function ToggleButton({
|
||||
checked,
|
||||
disabled,
|
||||
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}
|
||||
aria-label={ariaLabel ?? label}
|
||||
disabled={disabled}
|
||||
onClick={() => {
|
||||
if (!disabled) onChange(!checked);
|
||||
}}
|
||||
className={cn(
|
||||
"relative inline-flex h-5 w-9 shrink-0 items-center rounded-full p-0.5",
|
||||
"after:absolute after:left-1/2 after:top-1/2 after:h-11 after:w-11 after:-translate-x-1/2 after:-translate-y-1/2 after:content-['']",
|
||||
"transition-colors duration-200 ease-out motion-reduce:transition-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||
checked
|
||||
? "bg-foreground"
|
||||
: "bg-muted-foreground/25 hover:bg-muted-foreground/30",
|
||||
disabled && "cursor-default opacity-60",
|
||||
disabled && !checked && "hover:bg-muted-foreground/25",
|
||||
)}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
"h-4 w-4 rounded-full bg-background shadow-sm",
|
||||
"transition-transform duration-200 ease-out motion-reduce:transition-none",
|
||||
checked ? "translate-x-[16px]" : "translate-x-0",
|
||||
)}
|
||||
/>
|
||||
<span className="sr-only">{label}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
SettingsSectionTitle,
|
||||
StatusPill,
|
||||
} from "@/components/settings/shared/SettingsControls";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { ImageGenerationSettingsUpdate, SettingsPayload } from "@/lib/types";
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
SettingsRow,
|
||||
SettingsSectionTitle,
|
||||
} from "@/components/settings/shared/SettingsControls";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { SegmentedControl } from "@/components/ui/segmented-control";
|
||||
import type {
|
||||
NetworkSafetySettingsUpdate,
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
SettingsSectionTitle,
|
||||
StatusPill,
|
||||
} from "@/components/settings/shared/SettingsControls";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type { SettingsPayload, TranscriptionSettingsUpdate } from "@/lib/types";
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
SettingsSectionTitle,
|
||||
StatusPill,
|
||||
} from "@/components/settings/shared/SettingsControls";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import type {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Download, Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import type { ChannelFeatureAction } from "@/channel-plugins/types";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import {
|
||||
ChannelLogo,
|
||||
ChannelStatusBadge,
|
||||
|
||||
@@ -1,421 +1,54 @@
|
||||
import { useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import { ChevronDown, Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { channelUiPresentation } from "@/channel-plugins/registry";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import type { ChannelConfigField } from "@/channel-plugins/catalog";
|
||||
import {
|
||||
CredentialForm,
|
||||
channelValuesForSave,
|
||||
defaultChannelFieldValues,
|
||||
} from "@/components/settings/channels/CredentialForm";
|
||||
import {
|
||||
channelValidationStatusClass,
|
||||
channelValidationStatusIcon,
|
||||
} from "@/components/settings/channels/ChannelValidationProgress";
|
||||
import {
|
||||
CHANNEL_SETUP_PANEL_CLASS_NAME,
|
||||
ChannelLogo,
|
||||
ChannelRuntimeError,
|
||||
channelSetup,
|
||||
localizedChannelDisplayName,
|
||||
} from "@/components/settings/channels/ChannelIdentity";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||
import {
|
||||
configureChannel,
|
||||
disableNanobotFeature,
|
||||
enableNanobotFeature,
|
||||
} from "@/lib/api";
|
||||
import { logoFallbackUrls } from "@/lib/provider-brand";
|
||||
import type {
|
||||
NanobotChannelInstanceInfo,
|
||||
NanobotFeatureInfo,
|
||||
NanobotFeaturesPayload,
|
||||
} from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { NanobotChannelInstanceInfo, NanobotFeatureInfo, NanobotFeaturesPayload } from "@/lib/types";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
import {
|
||||
ChannelInstancesPanelView,
|
||||
type ChannelInstancesPanelCustomization,
|
||||
type ChannelInstancesPanelViewProps,
|
||||
} from "./ChannelInstancesPanelView";
|
||||
|
||||
export type ChannelInstancesPanelCustomization = {
|
||||
toggleAriaLabel?: (instance: NanobotChannelInstanceInfo) => string;
|
||||
configuredLabel?: string;
|
||||
needsSetupLabel?: string;
|
||||
renderInstanceSummary?: (instance: NanobotChannelInstanceInfo) => ReactNode;
|
||||
renderInstanceAction?: (instance: NanobotChannelInstanceInfo) => ReactNode;
|
||||
footer?: ReactNode;
|
||||
};
|
||||
export type { ChannelInstancesPanelCustomization } from "./ChannelInstancesPanelView";
|
||||
|
||||
export function ChannelInstancesPanel({
|
||||
feature,
|
||||
showBrandLogos,
|
||||
instances: providedInstances,
|
||||
instances,
|
||||
onFeaturesUpdate,
|
||||
customization = {},
|
||||
customization,
|
||||
renderView,
|
||||
}: {
|
||||
feature: NanobotFeatureInfo;
|
||||
showBrandLogos: boolean;
|
||||
instances?: NanobotChannelInstanceInfo[];
|
||||
onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;
|
||||
customization?: ChannelInstancesPanelCustomization;
|
||||
renderView?: (props: ChannelInstancesPanelViewProps) => ReactNode;
|
||||
}) {
|
||||
const { client } = useClient();
|
||||
const { t, i18n } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const displayName = localizedChannelDisplayName(feature, t);
|
||||
const instances = providedInstances ?? feature.instances ?? [];
|
||||
const [editor, setEditor] = useState<{ id: string; expanded: boolean } | null>(null);
|
||||
const selectedId = editor?.id;
|
||||
const [pendingToggle, setPendingToggle] = useState<{ id: string; checked: boolean } | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const selected = selectedId ? instances.find((instance) => instance.id === selectedId) : undefined;
|
||||
const setup = useMemo(
|
||||
() => channelSetup(feature, i18n.resolvedLanguage ?? i18n.language),
|
||||
[feature.name, feature.setup, i18n.language, i18n.resolvedLanguage],
|
||||
);
|
||||
const instanceFields = useMemo(
|
||||
() => channelInstanceFields(feature, setup.fields, setup.manualFields),
|
||||
[feature, setup.fields, setup.manualFields],
|
||||
);
|
||||
const [fieldValues, setFieldValues] = useState<Record<string, string>>(() =>
|
||||
defaultChannelFieldValues(instanceFields, selected?.config_values),
|
||||
);
|
||||
const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});
|
||||
const [savingFields, setSavingFields] = useState(false);
|
||||
const selectedValuesKey = JSON.stringify(
|
||||
defaultChannelFieldValues(instanceFields, selected?.config_values),
|
||||
);
|
||||
const selectedConfiguredFields = useMemo(
|
||||
() => new Set(selected?.configured_fields ?? []),
|
||||
[selected?.configured_fields],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedId && !instances.some((instance) => instance.id === selectedId)) {
|
||||
setEditor(null);
|
||||
}
|
||||
}, [instances, selectedId]);
|
||||
|
||||
useEffect(() => {
|
||||
setFieldValues(defaultChannelFieldValues(instanceFields, selected?.config_values));
|
||||
setVisibleSecrets({});
|
||||
}, [selected?.id, selectedValuesKey]);
|
||||
|
||||
const toggleInstance = async (instance: NanobotChannelInstanceInfo, checked: boolean) => {
|
||||
if (pendingToggle || savingFields) return;
|
||||
setPendingToggle({ id: instance.id, checked });
|
||||
setNotice(null);
|
||||
try {
|
||||
const viewProps: ChannelInstancesPanelViewProps = {
|
||||
feature,
|
||||
showBrandLogos,
|
||||
instances,
|
||||
customization,
|
||||
onToggleInstance: async (instance, checked) => {
|
||||
const payload = checked
|
||||
? await enableNanobotFeature(client, feature.name, { instanceId: instance.id })
|
||||
: await disableNanobotFeature(client, feature.name, { instanceId: instance.id });
|
||||
onFeaturesUpdate(payload);
|
||||
} catch (err) {
|
||||
setNotice((err as Error).message);
|
||||
} finally {
|
||||
setPendingToggle(null);
|
||||
}
|
||||
},
|
||||
onSaveInstance: async (instance, values) => {
|
||||
const payload = await configureChannel(client, feature.name, values, {
|
||||
enable: instance.enabled,
|
||||
instanceId: instance.id,
|
||||
});
|
||||
if (payload.nanobot_features) onFeaturesUpdate(payload.nanobot_features);
|
||||
},
|
||||
};
|
||||
|
||||
const saveSelectedInstanceSettings = async () => {
|
||||
if (!selected || pendingToggle || savingFields) return;
|
||||
setSavingFields(true);
|
||||
setNotice(null);
|
||||
try {
|
||||
const payload = await configureChannel(
|
||||
client,
|
||||
feature.name,
|
||||
channelValuesForSave(instanceFields, fieldValues),
|
||||
{ enable: selected.enabled, instanceId: selected.id },
|
||||
);
|
||||
if (payload.nanobot_features) {
|
||||
onFeaturesUpdate(payload.nanobot_features);
|
||||
}
|
||||
setNotice(tx("settings.channels.savedSettings", "Settings saved."));
|
||||
} catch (err) {
|
||||
setNotice((err as Error).message);
|
||||
} finally {
|
||||
setSavingFields(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>
|
||||
<div className="pe-20">
|
||||
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
|
||||
<h3 className="sr-only">{displayName}</h3>
|
||||
</div>
|
||||
|
||||
<ChannelRuntimeError message={feature.runtime_error} />
|
||||
|
||||
<div className="mt-5 space-y-3">
|
||||
{instances.map((instance) => {
|
||||
const expanded = selected?.id === instance.id && editor?.expanded === true;
|
||||
const toggling = pendingToggle?.id === instance.id;
|
||||
const checked = toggling ? pendingToggle.checked : instanceToggleChecked(instance);
|
||||
const instanceSummary = customization.renderInstanceSummary
|
||||
? customization.renderInstanceSummary(instance)
|
||||
: instance.id;
|
||||
const instanceAction = customization.renderInstanceAction?.(instance);
|
||||
const hasInstanceOverview = Boolean(instanceSummary || instanceAction);
|
||||
return (
|
||||
<article
|
||||
key={instance.id}
|
||||
className={cn(
|
||||
"overflow-hidden rounded-floating transition-colors",
|
||||
expanded
|
||||
? "bg-background"
|
||||
: "bg-background/70",
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-3">
|
||||
<div className="flex min-w-0 flex-[1_1_12rem] items-center gap-3">
|
||||
<ChannelInstanceAvatar
|
||||
feature={feature}
|
||||
instance={instance}
|
||||
showBrandLogos={showBrandLogos}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-foreground">
|
||||
{channelInstanceDisplayName(instance)}
|
||||
</span>
|
||||
<ChannelInstanceStatusBadge
|
||||
instance={instance}
|
||||
configuredLabel={customization.configuredLabel}
|
||||
needsSetupLabel={customization.needsSetupLabel}
|
||||
/>
|
||||
</div>
|
||||
<div className="ms-auto flex shrink-0 items-center gap-3">
|
||||
{instanceFields.length ? (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"
|
||||
onClick={() =>
|
||||
setEditor((current) => ({
|
||||
id: instance.id,
|
||||
expanded: current?.id !== instance.id || !current.expanded,
|
||||
}))
|
||||
}
|
||||
aria-expanded={expanded}
|
||||
>
|
||||
{tx("settings.channels.advanced", "Advanced")}
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
"h-3.5 w-3.5 transition-transform motion-reduce:transition-none",
|
||||
expanded && "rotate-180",
|
||||
)}
|
||||
aria-hidden
|
||||
/>
|
||||
</button>
|
||||
) : null}
|
||||
{toggling ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-hidden />
|
||||
) : null}
|
||||
<ToggleButton
|
||||
checked={checked}
|
||||
disabled={
|
||||
Boolean(pendingToggle)
|
||||
|| savingFields
|
||||
|| !instance.configured
|
||||
}
|
||||
ariaLabel={customization.toggleAriaLabel?.(instance)
|
||||
?? t("settings.channels.toggleInstance", {
|
||||
name: channelInstanceDisplayName(instance),
|
||||
defaultValue: "{{name}} instance",
|
||||
})}
|
||||
label={checked ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
|
||||
onChange={(checked) => void toggleInstance(instance, checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasInstanceOverview || (expanded && instanceFields.length > 0) ? (
|
||||
<div className="space-y-3 px-4 pb-4 pt-1">
|
||||
{hasInstanceOverview ? <section className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
{instanceSummary ? (
|
||||
<p className="min-w-0 flex-1 truncate font-mono text-[11.5px] leading-6 text-muted-foreground">
|
||||
{instanceSummary}
|
||||
</p>
|
||||
) : <span className="flex-1" />}
|
||||
{instanceAction}
|
||||
</section> : null}
|
||||
{expanded && instanceFields.length > 0 ? (
|
||||
<div className={cn(
|
||||
"text-[12px] leading-5 text-muted-foreground",
|
||||
hasInstanceOverview && "border-t border-border/50 pt-3",
|
||||
)}>
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void saveSelectedInstanceSettings();
|
||||
}}
|
||||
>
|
||||
<CredentialForm
|
||||
fields={instanceFields}
|
||||
values={fieldValues}
|
||||
configuredFields={selectedConfiguredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={(key, value) =>
|
||||
setFieldValues((current) => ({ ...current, [key]: value }))
|
||||
}
|
||||
onToggleSecret={(key) =>
|
||||
setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }))
|
||||
}
|
||||
compact
|
||||
/>
|
||||
<div className="mt-3 flex justify-end">
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 rounded-full bg-muted/70 px-3 text-[12px] font-semibold settings-hover"
|
||||
disabled={savingFields || Boolean(pendingToggle)}
|
||||
>
|
||||
{savingFields ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : null}
|
||||
{tx("settings.channels.saveSettings", "Save settings")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{customization.footer}
|
||||
|
||||
{notice ? (
|
||||
<div className="mt-3 rounded-control border border-destructive/20 px-3 py-2 text-[12px] leading-5 text-destructive">
|
||||
{notice}
|
||||
</div>
|
||||
) : null}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function channelInstanceDisplayName(instance: NanobotChannelInstanceInfo): string {
|
||||
const displayName = instance.display_name?.trim();
|
||||
if (displayName) return displayName;
|
||||
const localName = instance.name?.trim();
|
||||
if (localName) return localName;
|
||||
return instance.id;
|
||||
}
|
||||
|
||||
function instanceToggleChecked(instance: NanobotChannelInstanceInfo): boolean {
|
||||
return instance.runtime_status === "running" || instance.runtime_status === "starting";
|
||||
}
|
||||
|
||||
function ChannelInstanceStatusBadge({
|
||||
instance,
|
||||
configuredLabel,
|
||||
needsSetupLabel,
|
||||
}: {
|
||||
instance: NanobotChannelInstanceInfo;
|
||||
configuredLabel?: string;
|
||||
needsSetupLabel?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
let status = instance.configured ? "configured" : "needs_setup";
|
||||
let label = instance.configured
|
||||
? t("settings.channels.instanceConfigured", { defaultValue: "Configured" })
|
||||
: needsSetupLabel ?? t("settings.channels.instanceNeedsSetup", { defaultValue: "Needs setup" });
|
||||
if (instance.runtime_status === "failed") {
|
||||
status = "invalid";
|
||||
label = t("settings.channels.runtimeFailed", { defaultValue: "Failed" });
|
||||
} else if (instance.runtime_status === "starting") {
|
||||
label = t("settings.channels.runtimeStarting", { defaultValue: "Starting" });
|
||||
} else if (instance.enabled && instance.runtime_status !== "running") {
|
||||
label = t("settings.channels.runtimeStopped", { defaultValue: "Not running" });
|
||||
} else if (instance.runtime_status === "running") {
|
||||
status = "connected";
|
||||
label = configuredLabel
|
||||
?? t("settings.channels.validation.connected", { defaultValue: "Connected" });
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1 text-[11.5px] font-medium",
|
||||
channelValidationStatusClass(status),
|
||||
)}
|
||||
>
|
||||
{channelValidationStatusIcon(status)}
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ChannelInstanceAvatar({
|
||||
feature,
|
||||
instance,
|
||||
showBrandLogos,
|
||||
}: {
|
||||
feature: NanobotFeatureInfo;
|
||||
instance: NanobotChannelInstanceInfo;
|
||||
showBrandLogos: boolean;
|
||||
}) {
|
||||
const presentation = channelUiPresentation(feature.name, feature.webui);
|
||||
const [avatarFailed, setAvatarFailed] = useState(false);
|
||||
const fallbackLogoUrls = useMemo(() => logoFallbackUrls(presentation?.logoUrl), [presentation?.logoUrl]);
|
||||
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(fallbackLogoUrls);
|
||||
const remoteAvatarUrl = !avatarFailed ? instance.avatar_url?.trim() : "";
|
||||
const imageUrl = remoteAvatarUrl || (showBrandLogos ? logoUrl : "");
|
||||
const Icon = presentation?.icon;
|
||||
const initials = presentation?.initials ?? feature.display_name.slice(0, 2).toUpperCase();
|
||||
const color = presentation?.color ?? "#3370FF";
|
||||
|
||||
useEffect(() => {
|
||||
setAvatarFailed(false);
|
||||
}, [instance.avatar_url]);
|
||||
|
||||
return (
|
||||
<span
|
||||
className="grid h-11 w-11 shrink-0 place-items-center overflow-hidden rounded-full bg-background text-[10px] font-bold"
|
||||
style={{ color }}
|
||||
aria-hidden
|
||||
>
|
||||
{remoteAvatarUrl ? (
|
||||
<img
|
||||
src={remoteAvatarUrl}
|
||||
alt=""
|
||||
decoding="async"
|
||||
loading="lazy"
|
||||
className="h-full w-full object-cover"
|
||||
onError={() => setAvatarFailed(true)}
|
||||
/>
|
||||
) : imageUrl ? (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt=""
|
||||
decoding="async"
|
||||
loading="lazy"
|
||||
className="h-6 w-6 object-contain"
|
||||
onLoad={onLogoLoad}
|
||||
onError={onLogoError}
|
||||
/>
|
||||
) : Icon ? (
|
||||
<Icon className="h-5 w-5" strokeWidth={2.25} />
|
||||
) : (
|
||||
initials
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function channelInstanceFields(
|
||||
feature: NanobotFeatureInfo,
|
||||
fields: ChannelConfigField[] | undefined,
|
||||
manualFields: ChannelConfigField[] | undefined,
|
||||
): ChannelConfigField[] {
|
||||
const available = new Map(
|
||||
[...(fields ?? []), ...(manualFields ?? [])].map((field) => [field.key, field]),
|
||||
);
|
||||
if (!feature.setup) return [...available.values()];
|
||||
return feature.setup.fields.flatMap((field) => {
|
||||
const resolved = available.get(field.key);
|
||||
return resolved ? [resolved] : [];
|
||||
});
|
||||
return renderView ? renderView(viewProps) : <ChannelInstancesPanelView {...viewProps} />;
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
import { useEffect, useMemo, useState, type ReactNode } from "react";
|
||||
import { ChevronDown, Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { channelUiPresentation } from "@/channel-plugins/registry";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import type { ChannelConfigField } from "@/channel-plugins/catalog";
|
||||
import {
|
||||
CredentialForm,
|
||||
channelValuesForSave,
|
||||
defaultChannelFieldValues,
|
||||
} from "@/components/settings/channels/CredentialForm";
|
||||
import {
|
||||
channelValidationStatusClass,
|
||||
channelValidationStatusIcon,
|
||||
} from "@/components/settings/channels/ChannelValidationProgress";
|
||||
import {
|
||||
CHANNEL_SETUP_PANEL_CLASS_NAME,
|
||||
ChannelLogo,
|
||||
ChannelRuntimeError,
|
||||
channelSetup,
|
||||
localizedChannelDisplayName,
|
||||
} from "@/components/settings/channels/ChannelIdentity";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||
import { logoFallbackUrls } from "@/lib/provider-brand";
|
||||
import type {
|
||||
NanobotChannelInstanceInfo,
|
||||
NanobotFeatureInfo,
|
||||
} from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type ChannelInstancesPanelCustomization = {
|
||||
toggleAriaLabel?: (instance: NanobotChannelInstanceInfo) => string;
|
||||
configuredLabel?: string;
|
||||
needsSetupLabel?: string;
|
||||
renderInstanceSummary?: (instance: NanobotChannelInstanceInfo) => ReactNode;
|
||||
renderInstanceAction?: (instance: NanobotChannelInstanceInfo) => ReactNode;
|
||||
footer?: ReactNode;
|
||||
};
|
||||
|
||||
export type ChannelInstancesPanelViewProps = {
|
||||
feature: NanobotFeatureInfo;
|
||||
showBrandLogos: boolean;
|
||||
instances?: NanobotChannelInstanceInfo[];
|
||||
onToggleInstance: (instance: NanobotChannelInstanceInfo, checked: boolean) => void | Promise<void>;
|
||||
onSaveInstance: (instance: NanobotChannelInstanceInfo, values: Record<string, string>) => void | Promise<void>;
|
||||
customization?: ChannelInstancesPanelCustomization;
|
||||
};
|
||||
|
||||
export function ChannelInstancesPanelView({
|
||||
feature,
|
||||
showBrandLogos,
|
||||
instances: providedInstances,
|
||||
onToggleInstance,
|
||||
onSaveInstance,
|
||||
customization = {},
|
||||
}: ChannelInstancesPanelViewProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const displayName = localizedChannelDisplayName(feature, t);
|
||||
const instances = providedInstances ?? feature.instances ?? [];
|
||||
const [editor, setEditor] = useState<{ id: string; expanded: boolean } | null>(null);
|
||||
const selectedId = editor?.id;
|
||||
const [pendingToggle, setPendingToggle] = useState<{ id: string; checked: boolean } | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const selected = selectedId ? instances.find((instance) => instance.id === selectedId) : undefined;
|
||||
const setup = useMemo(
|
||||
() => channelSetup(feature, i18n.resolvedLanguage ?? i18n.language),
|
||||
[feature.name, feature.setup, i18n.language, i18n.resolvedLanguage],
|
||||
);
|
||||
const instanceFields = useMemo(
|
||||
() => channelInstanceFields(feature, setup.fields, setup.manualFields),
|
||||
[feature, setup.fields, setup.manualFields],
|
||||
);
|
||||
const [fieldValues, setFieldValues] = useState<Record<string, string>>(() =>
|
||||
defaultChannelFieldValues(instanceFields, selected?.config_values),
|
||||
);
|
||||
const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});
|
||||
const [savingFields, setSavingFields] = useState(false);
|
||||
const selectedValuesKey = JSON.stringify(
|
||||
defaultChannelFieldValues(instanceFields, selected?.config_values),
|
||||
);
|
||||
const selectedConfiguredFields = useMemo(
|
||||
() => new Set(selected?.configured_fields ?? []),
|
||||
[selected?.configured_fields],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedId && !instances.some((instance) => instance.id === selectedId)) {
|
||||
setEditor(null);
|
||||
}
|
||||
}, [instances, selectedId]);
|
||||
|
||||
useEffect(() => {
|
||||
setFieldValues(defaultChannelFieldValues(instanceFields, selected?.config_values));
|
||||
setVisibleSecrets({});
|
||||
}, [selected?.id, selectedValuesKey]);
|
||||
|
||||
const toggleInstance = async (instance: NanobotChannelInstanceInfo, checked: boolean) => {
|
||||
if (pendingToggle || savingFields) return;
|
||||
setPendingToggle({ id: instance.id, checked });
|
||||
setNotice(null);
|
||||
try {
|
||||
await onToggleInstance(instance, checked);
|
||||
} catch (err) {
|
||||
setNotice((err as Error).message);
|
||||
} finally {
|
||||
setPendingToggle(null);
|
||||
}
|
||||
};
|
||||
|
||||
const saveSelectedInstanceSettings = async () => {
|
||||
if (!selected || pendingToggle || savingFields) return;
|
||||
setSavingFields(true);
|
||||
setNotice(null);
|
||||
try {
|
||||
await onSaveInstance(selected, channelValuesForSave(instanceFields, fieldValues));
|
||||
setNotice(tx("settings.channels.savedSettings", "Settings saved."));
|
||||
} catch (err) {
|
||||
setNotice((err as Error).message);
|
||||
} finally {
|
||||
setSavingFields(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>
|
||||
<div className="pe-20">
|
||||
<ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />
|
||||
<h3 className="sr-only">{displayName}</h3>
|
||||
</div>
|
||||
|
||||
<ChannelRuntimeError message={feature.runtime_error} />
|
||||
|
||||
<div className="mt-5 space-y-3">
|
||||
{instances.map((instance) => {
|
||||
const expanded = selected?.id === instance.id && editor?.expanded === true;
|
||||
const toggling = pendingToggle?.id === instance.id;
|
||||
const checked = toggling ? pendingToggle.checked : instanceToggleChecked(instance);
|
||||
const instanceSummary = customization.renderInstanceSummary
|
||||
? customization.renderInstanceSummary(instance)
|
||||
: instance.id;
|
||||
const instanceAction = customization.renderInstanceAction?.(instance);
|
||||
const hasInstanceOverview = Boolean(instanceSummary || instanceAction);
|
||||
return (
|
||||
<article
|
||||
key={instance.id}
|
||||
className={cn(
|
||||
"overflow-hidden rounded-floating transition-colors",
|
||||
expanded
|
||||
? "bg-background"
|
||||
: "bg-background/70",
|
||||
)}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-3">
|
||||
<div className="flex min-w-0 flex-[1_1_12rem] items-center gap-3">
|
||||
<ChannelInstanceAvatar
|
||||
feature={feature}
|
||||
instance={instance}
|
||||
showBrandLogos={showBrandLogos}
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-[13px] font-semibold text-foreground">
|
||||
{channelInstanceDisplayName(instance)}
|
||||
</span>
|
||||
<ChannelInstanceStatusBadge
|
||||
instance={instance}
|
||||
configuredLabel={customization.configuredLabel}
|
||||
needsSetupLabel={customization.needsSetupLabel}
|
||||
/>
|
||||
</div>
|
||||
<div className="ms-auto flex shrink-0 items-center gap-3">
|
||||
{instanceFields.length ? (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"
|
||||
onClick={() =>
|
||||
setEditor((current) => ({
|
||||
id: instance.id,
|
||||
expanded: current?.id !== instance.id || !current.expanded,
|
||||
}))
|
||||
}
|
||||
aria-expanded={expanded}
|
||||
>
|
||||
{tx("settings.channels.advanced", "Advanced")}
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
"h-3.5 w-3.5 transition-transform motion-reduce:transition-none",
|
||||
expanded && "rotate-180",
|
||||
)}
|
||||
aria-hidden
|
||||
/>
|
||||
</button>
|
||||
) : null}
|
||||
{toggling ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" aria-hidden />
|
||||
) : null}
|
||||
<ToggleButton
|
||||
checked={checked}
|
||||
disabled={
|
||||
Boolean(pendingToggle)
|
||||
|| savingFields
|
||||
|| !instance.configured
|
||||
}
|
||||
ariaLabel={customization.toggleAriaLabel?.(instance)
|
||||
?? t("settings.channels.toggleInstance", {
|
||||
name: channelInstanceDisplayName(instance),
|
||||
defaultValue: "{{name}} instance",
|
||||
})}
|
||||
label={checked ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
|
||||
onChange={(checked) => void toggleInstance(instance, checked)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{hasInstanceOverview || (expanded && instanceFields.length > 0) ? (
|
||||
<div className="space-y-3 px-4 pb-4 pt-1">
|
||||
{hasInstanceOverview ? <section className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
{instanceSummary ? (
|
||||
<p className="min-w-0 flex-1 truncate font-mono text-[11.5px] leading-6 text-muted-foreground">
|
||||
{instanceSummary}
|
||||
</p>
|
||||
) : <span className="flex-1" />}
|
||||
{instanceAction}
|
||||
</section> : null}
|
||||
{expanded && instanceFields.length > 0 ? (
|
||||
<div className={cn(
|
||||
"text-[12px] leading-5 text-muted-foreground",
|
||||
hasInstanceOverview && "border-t border-border/50 pt-3",
|
||||
)}>
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void saveSelectedInstanceSettings();
|
||||
}}
|
||||
>
|
||||
<CredentialForm
|
||||
fields={instanceFields}
|
||||
values={fieldValues}
|
||||
configuredFields={selectedConfiguredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={(key, value) =>
|
||||
setFieldValues((current) => ({ ...current, [key]: value }))
|
||||
}
|
||||
onToggleSecret={(key) =>
|
||||
setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }))
|
||||
}
|
||||
compact
|
||||
/>
|
||||
<div className="mt-3 flex justify-end">
|
||||
<Button
|
||||
type="submit"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 rounded-full bg-muted/70 px-3 text-[12px] font-semibold settings-hover"
|
||||
disabled={savingFields || Boolean(pendingToggle)}
|
||||
>
|
||||
{savingFields ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : null}
|
||||
{tx("settings.channels.saveSettings", "Save settings")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{customization.footer}
|
||||
|
||||
{notice ? (
|
||||
<div className="mt-3 rounded-control border border-destructive/20 px-3 py-2 text-[12px] leading-5 text-destructive">
|
||||
{notice}
|
||||
</div>
|
||||
) : null}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function channelInstanceDisplayName(instance: NanobotChannelInstanceInfo): string {
|
||||
const displayName = instance.display_name?.trim();
|
||||
if (displayName) return displayName;
|
||||
const localName = instance.name?.trim();
|
||||
if (localName) return localName;
|
||||
return instance.id;
|
||||
}
|
||||
|
||||
function instanceToggleChecked(instance: NanobotChannelInstanceInfo): boolean {
|
||||
return instance.runtime_status === "running" || instance.runtime_status === "starting";
|
||||
}
|
||||
|
||||
function ChannelInstanceStatusBadge({
|
||||
instance,
|
||||
configuredLabel,
|
||||
needsSetupLabel,
|
||||
}: {
|
||||
instance: NanobotChannelInstanceInfo;
|
||||
configuredLabel?: string;
|
||||
needsSetupLabel?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
let status = instance.configured ? "configured" : "needs_setup";
|
||||
let label = instance.configured
|
||||
? t("settings.channels.instanceConfigured", { defaultValue: "Configured" })
|
||||
: needsSetupLabel ?? t("settings.channels.instanceNeedsSetup", { defaultValue: "Needs setup" });
|
||||
if (instance.runtime_status === "failed") {
|
||||
status = "invalid";
|
||||
label = t("settings.channels.runtimeFailed", { defaultValue: "Failed" });
|
||||
} else if (instance.runtime_status === "starting") {
|
||||
label = t("settings.channels.runtimeStarting", { defaultValue: "Starting" });
|
||||
} else if (instance.enabled && instance.runtime_status !== "running") {
|
||||
label = t("settings.channels.runtimeStopped", { defaultValue: "Not running" });
|
||||
} else if (instance.runtime_status === "running") {
|
||||
status = "connected";
|
||||
label = configuredLabel
|
||||
?? t("settings.channels.validation.connected", { defaultValue: "Connected" });
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex shrink-0 items-center gap-1.5 rounded-full px-2.5 py-1 text-[11.5px] font-medium",
|
||||
channelValidationStatusClass(status),
|
||||
)}
|
||||
>
|
||||
{channelValidationStatusIcon(status)}
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ChannelInstanceAvatar({
|
||||
feature,
|
||||
instance,
|
||||
showBrandLogos,
|
||||
}: {
|
||||
feature: NanobotFeatureInfo;
|
||||
instance: NanobotChannelInstanceInfo;
|
||||
showBrandLogos: boolean;
|
||||
}) {
|
||||
const presentation = channelUiPresentation(feature.name, feature.webui);
|
||||
const [avatarFailed, setAvatarFailed] = useState(false);
|
||||
const fallbackLogoUrls = useMemo(() => logoFallbackUrls(presentation?.logoUrl), [presentation?.logoUrl]);
|
||||
const { logoUrl, onLogoError, onLogoLoad } = useLogoFallback(fallbackLogoUrls);
|
||||
const remoteAvatarUrl = !avatarFailed ? instance.avatar_url?.trim() : "";
|
||||
const imageUrl = remoteAvatarUrl || (showBrandLogos ? logoUrl : "");
|
||||
const Icon = presentation?.icon;
|
||||
const initials = presentation?.initials ?? feature.display_name.slice(0, 2).toUpperCase();
|
||||
const color = presentation?.color ?? "#3370FF";
|
||||
|
||||
useEffect(() => {
|
||||
setAvatarFailed(false);
|
||||
}, [instance.avatar_url]);
|
||||
|
||||
return (
|
||||
<span
|
||||
className="grid h-11 w-11 shrink-0 place-items-center overflow-hidden rounded-full bg-background text-[10px] font-bold"
|
||||
style={{ color }}
|
||||
aria-hidden
|
||||
>
|
||||
{remoteAvatarUrl ? (
|
||||
<img
|
||||
src={remoteAvatarUrl}
|
||||
alt=""
|
||||
decoding="async"
|
||||
loading="lazy"
|
||||
className="h-full w-full object-cover"
|
||||
onError={() => setAvatarFailed(true)}
|
||||
/>
|
||||
) : imageUrl ? (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt=""
|
||||
decoding="async"
|
||||
loading="lazy"
|
||||
className="h-6 w-6 object-contain"
|
||||
onLoad={onLogoLoad}
|
||||
onError={onLogoError}
|
||||
/>
|
||||
) : Icon ? (
|
||||
<Icon className="h-5 w-5" strokeWidth={2.25} />
|
||||
) : (
|
||||
initials
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function channelInstanceFields(
|
||||
feature: NanobotFeatureInfo,
|
||||
fields: ChannelConfigField[] | undefined,
|
||||
manualFields: ChannelConfigField[] | undefined,
|
||||
): ChannelConfigField[] {
|
||||
const available = new Map(
|
||||
[...(fields ?? []), ...(manualFields ?? [])].map((field) => [field.key, field]),
|
||||
);
|
||||
if (!feature.setup) return [...available.values()];
|
||||
return feature.setup.fields.flatMap((field) => {
|
||||
const resolved = available.get(field.key);
|
||||
return resolved ? [resolved] : [];
|
||||
});
|
||||
}
|
||||
@@ -1,10 +1,5 @@
|
||||
import { channelValidationMessage } from "./validationMessages";
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import QRCode from "qrcode";
|
||||
import { Check, Loader2, RotateCcw } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { usePageVisibility } from "@/hooks/usePageVisibility";
|
||||
import {
|
||||
cancelChannelConnect,
|
||||
@@ -17,25 +12,14 @@ import type {
|
||||
} from "@/lib/types";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
|
||||
export type ChannelQrConnectLabels = {
|
||||
qrAlt?: string;
|
||||
scanTitle: string;
|
||||
scanDescription: string;
|
||||
waiting: string;
|
||||
connected: string;
|
||||
stopped: string;
|
||||
connecting: string;
|
||||
scanAgain: string;
|
||||
connect: string;
|
||||
};
|
||||
import {
|
||||
ChannelQrConnectFlowView,
|
||||
type ChannelQrConnectFlowViewProps,
|
||||
type ChannelQrConnectLabels,
|
||||
type ChannelQrConnectPendingContext,
|
||||
} from "./ChannelQrConnectFlowView";
|
||||
|
||||
export type ChannelQrConnectPendingContext = {
|
||||
connect: ChannelConnectPayload;
|
||||
busy: boolean;
|
||||
poll: (
|
||||
params?: Readonly<Record<string, string>>,
|
||||
) => Promise<ChannelConnectPayload | null>;
|
||||
};
|
||||
export type { ChannelQrConnectLabels, ChannelQrConnectPendingContext } from "./ChannelQrConnectFlowView";
|
||||
|
||||
export function ChannelQrConnectFlow({
|
||||
channelName,
|
||||
@@ -55,6 +39,7 @@ export function ChannelQrConnectFlow({
|
||||
suppressSucceeded = false,
|
||||
onActiveChange,
|
||||
renderActions,
|
||||
renderView,
|
||||
}: {
|
||||
token: string;
|
||||
channelName: string;
|
||||
@@ -75,13 +60,11 @@ export function ChannelQrConnectFlow({
|
||||
suppressSucceeded?: boolean;
|
||||
onActiveChange?: (active: boolean) => void;
|
||||
renderActions?: (connectButton: ReactNode) => ReactNode;
|
||||
renderView?: (props: ChannelQrConnectFlowViewProps) => ReactNode;
|
||||
}) {
|
||||
const { client } = useClient();
|
||||
const pageVisible = usePageVisibility();
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const [connect, setConnect] = useState<ChannelConnectPayload | null>(null);
|
||||
const [qrDataUrl, setQrDataUrl] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const handledRequestId = useRef(0);
|
||||
@@ -89,38 +72,10 @@ export function ChannelQrConnectFlow({
|
||||
const pollInFlight = useRef(false);
|
||||
|
||||
const pending = connect?.status === "pending";
|
||||
const succeeded = !pending && (connected || connect?.status === "succeeded");
|
||||
const canStart = !pending && !busy;
|
||||
useEffect(() => {
|
||||
onActiveChange?.(pending || busy);
|
||||
}, [pending, busy, onActiveChange]);
|
||||
const pollingPaused = Boolean(connect && pausePolling?.(connect));
|
||||
const displayMessage = connect
|
||||
? resolveMessage?.(connect) ?? (connect.message ? channelValidationMessage(connect.message, t) : undefined)
|
||||
: undefined;
|
||||
|
||||
useEffect(() => {
|
||||
if (!showQrCode || !connect?.qr_url) {
|
||||
setQrDataUrl("");
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void QRCode.toDataURL(connect.qr_url, {
|
||||
width: 184,
|
||||
margin: 1,
|
||||
color: { dark: "#111827", light: "#ffffff" },
|
||||
})
|
||||
.then((url) => {
|
||||
if (!cancelled) setQrDataUrl(url);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setQrDataUrl("");
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [connect?.qr_url, showQrCode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!connect?.session_id
|
||||
@@ -258,116 +213,23 @@ export function ChannelQrConnectFlow({
|
||||
}
|
||||
};
|
||||
|
||||
const renderActionRow = renderActions ?? ((connectButton: ReactNode) => (
|
||||
<div className="flex flex-wrap justify-end gap-2">{connectButton}</div>
|
||||
));
|
||||
|
||||
return (
|
||||
<div className="mt-3 space-y-3">
|
||||
{autoStart && busy && !connect ? (
|
||||
<div role="status" className="grid min-h-[228px] place-items-center">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
|
||||
<span className="sr-only">{labels.connecting}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{pending && minimalPending && showQrCode ? (
|
||||
<div className="flex min-h-[228px] flex-col items-center justify-center gap-4 py-4">
|
||||
<div className="grid h-[196px] w-[196px] place-items-center rounded-control bg-background shadow-[inset_0_0_0_1px_oklch(0_0_0/0.1)] dark:shadow-[inset_0_0_0_1px_oklch(1_0_0/0.1)]">
|
||||
{qrDataUrl ? (
|
||||
<img
|
||||
src={qrDataUrl}
|
||||
alt={labels.qrAlt ?? labels.scanTitle}
|
||||
className="h-[184px] w-[184px]"
|
||||
/>
|
||||
) : (
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
|
||||
)}
|
||||
</div>
|
||||
{renderPending?.({ connect, busy, poll: submitPoll })}
|
||||
</div>
|
||||
) : pending ? (
|
||||
<div className={`grid gap-4 rounded-control border border-border/70 p-4 ${showQrCode ? "sm:grid-cols-[auto_minmax(0,1fr)]" : ""}`}>
|
||||
{showQrCode ? <div className="grid h-[196px] w-[196px] place-items-center rounded-control border border-border/60 bg-background">
|
||||
{qrDataUrl ? (
|
||||
<img
|
||||
src={qrDataUrl}
|
||||
alt={labels.qrAlt ?? labels.scanTitle}
|
||||
className="h-[184px] w-[184px]"
|
||||
/>
|
||||
) : (
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
|
||||
)}
|
||||
</div> : null}
|
||||
<div className="flex min-w-0 flex-col justify-center">
|
||||
<div className="text-[13px] font-semibold text-foreground">
|
||||
{labels.scanTitle}
|
||||
</div>
|
||||
<p className="mt-1 text-[12.5px] leading-5 text-muted-foreground">
|
||||
{!showQrCode || qrDataUrl ? labels.scanDescription : null}
|
||||
</p>
|
||||
{renderPending?.({ connect, busy, poll: submitPoll }) ?? (
|
||||
<div className="mt-3 flex items-center gap-2 text-[12px] text-muted-foreground">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
{!showQrCode || qrDataUrl ? labels.waiting : labels.connecting}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-4 flex flex-wrap justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
onClick={() => void cancel()}
|
||||
disabled={busy}
|
||||
>
|
||||
{tx("settings.actions.cancel", "Cancel")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{succeeded && !suppressSucceeded ? (
|
||||
<div className="flex items-center gap-2 rounded-control border border-emerald-500/20 px-3 py-2 text-[12px] font-medium text-emerald-700 dark:text-emerald-200">
|
||||
<Check className="h-3.5 w-3.5" aria-hidden />
|
||||
{displayMessage ?? labels.connected}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{connect && ["expired", "failed", "cancelled"].includes(connect.status)
|
||||
&& !(connected && connect.status === "cancelled") ? (
|
||||
<div className="rounded-control border border-border/60 px-3 py-2 text-[12px] leading-5 text-muted-foreground">
|
||||
{displayMessage || labels.stopped}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<div className="rounded-control border border-destructive/20 px-3 py-2 text-[12px] leading-5 text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!pending && !(autoStart && busy && !connect) ? renderActionRow(
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
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}
|
||||
>
|
||||
{busy ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : succeeded ? (
|
||||
<RotateCcw className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
) : null}
|
||||
{pending
|
||||
? labels.connecting
|
||||
: succeeded
|
||||
? labels.scanAgain
|
||||
: idleLabel ?? labels.connect}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
const viewProps: ChannelQrConnectFlowViewProps = {
|
||||
connect,
|
||||
busy,
|
||||
error,
|
||||
onStart: () => void start(forceOnRepeat && !pending && (connected || connect?.status === "succeeded")),
|
||||
onCancel: () => void cancel(),
|
||||
onPoll: submitPoll,
|
||||
idleLabel,
|
||||
connected,
|
||||
autoStart,
|
||||
minimalPending,
|
||||
showQrCode,
|
||||
labels,
|
||||
renderPending,
|
||||
resolveMessage,
|
||||
suppressSucceeded,
|
||||
renderActions,
|
||||
};
|
||||
return renderView ? renderView(viewProps) : <ChannelQrConnectFlowView {...viewProps} />;
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import QRCode from "qrcode";
|
||||
import { Check, Loader2, RotateCcw } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { ChannelConnectPayload } from "@/lib/types";
|
||||
import { channelValidationMessage } from "./validationMessages";
|
||||
|
||||
export type ChannelQrConnectLabels = {
|
||||
qrAlt?: string;
|
||||
scanTitle: string;
|
||||
scanDescription: string;
|
||||
waiting: string;
|
||||
connected: string;
|
||||
stopped: string;
|
||||
connecting: string;
|
||||
scanAgain: string;
|
||||
connect: string;
|
||||
};
|
||||
|
||||
export type ChannelQrConnectPendingContext = {
|
||||
connect: ChannelConnectPayload;
|
||||
busy: boolean;
|
||||
poll: (
|
||||
params?: Readonly<Record<string, string>>,
|
||||
) => Promise<ChannelConnectPayload | null>;
|
||||
};
|
||||
|
||||
export type ChannelQrConnectFlowViewProps = {
|
||||
connect: ChannelConnectPayload | null;
|
||||
busy: boolean;
|
||||
error: string | null;
|
||||
onStart: () => void;
|
||||
onCancel: () => void;
|
||||
onPoll: ChannelQrConnectPendingContext["poll"];
|
||||
idleLabel?: string;
|
||||
connected?: boolean;
|
||||
autoStart?: boolean;
|
||||
minimalPending?: boolean;
|
||||
showQrCode?: boolean;
|
||||
labels: ChannelQrConnectLabels;
|
||||
renderPending?: (context: ChannelQrConnectPendingContext) => ReactNode;
|
||||
resolveMessage?: (payload: ChannelConnectPayload) => string | undefined;
|
||||
suppressSucceeded?: boolean;
|
||||
renderActions?: (connectButton: ReactNode) => ReactNode;
|
||||
};
|
||||
|
||||
export function ChannelQrConnectFlowView({
|
||||
connect,
|
||||
busy,
|
||||
error,
|
||||
onStart,
|
||||
onCancel,
|
||||
onPoll,
|
||||
idleLabel,
|
||||
connected = false,
|
||||
autoStart = false,
|
||||
minimalPending = false,
|
||||
showQrCode = true,
|
||||
labels,
|
||||
renderPending,
|
||||
resolveMessage,
|
||||
suppressSucceeded = false,
|
||||
renderActions,
|
||||
}: ChannelQrConnectFlowViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const [qrDataUrl, setQrDataUrl] = useState("");
|
||||
const pending = connect?.status === "pending";
|
||||
const succeeded = !pending && (connected || connect?.status === "succeeded");
|
||||
const canStart = !pending && !busy;
|
||||
const displayMessage = connect
|
||||
? resolveMessage?.(connect) ?? (connect.message ? channelValidationMessage(connect.message, t) : undefined)
|
||||
: undefined;
|
||||
|
||||
useEffect(() => {
|
||||
if (!showQrCode || !connect?.qr_url) {
|
||||
setQrDataUrl("");
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void QRCode.toDataURL(connect.qr_url, {
|
||||
width: 184,
|
||||
margin: 1,
|
||||
color: { dark: "#111827", light: "#ffffff" },
|
||||
})
|
||||
.then((url) => {
|
||||
if (!cancelled) setQrDataUrl(url);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setQrDataUrl("");
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [connect?.qr_url, showQrCode]);
|
||||
|
||||
const renderActionRow = renderActions ?? ((connectButton: ReactNode) => (
|
||||
<div className="flex flex-wrap justify-end gap-2">{connectButton}</div>
|
||||
));
|
||||
|
||||
return (
|
||||
<div className="mt-3 space-y-3">
|
||||
{autoStart && busy && !connect ? (
|
||||
<div role="status" className="grid min-h-[228px] place-items-center">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
|
||||
<span className="sr-only">{labels.connecting}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{pending && minimalPending && showQrCode ? (
|
||||
<div className="flex min-h-[228px] flex-col items-center justify-center gap-4 py-4">
|
||||
<div className="grid h-[196px] w-[196px] place-items-center rounded-control bg-background shadow-[inset_0_0_0_1px_oklch(0_0_0/0.1)] dark:shadow-[inset_0_0_0_1px_oklch(1_0_0/0.1)]">
|
||||
{qrDataUrl ? (
|
||||
<img
|
||||
src={qrDataUrl}
|
||||
alt={labels.qrAlt ?? labels.scanTitle}
|
||||
className="h-[184px] w-[184px]"
|
||||
/>
|
||||
) : (
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
|
||||
)}
|
||||
</div>
|
||||
{renderPending?.({ connect, busy, poll: onPoll })}
|
||||
</div>
|
||||
) : pending ? (
|
||||
<div className={`grid gap-4 rounded-control border border-border/70 p-4 ${showQrCode ? "sm:grid-cols-[auto_minmax(0,1fr)]" : ""}`}>
|
||||
{showQrCode ? <div className="grid h-[196px] w-[196px] place-items-center rounded-control border border-border/60 bg-background">
|
||||
{qrDataUrl ? (
|
||||
<img
|
||||
src={qrDataUrl}
|
||||
alt={labels.qrAlt ?? labels.scanTitle}
|
||||
className="h-[184px] w-[184px]"
|
||||
/>
|
||||
) : (
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" aria-hidden />
|
||||
)}
|
||||
</div> : null}
|
||||
<div className="flex min-w-0 flex-col justify-center">
|
||||
<div className="text-[13px] font-semibold text-foreground">
|
||||
{labels.scanTitle}
|
||||
</div>
|
||||
<p className="mt-1 text-[12.5px] leading-5 text-muted-foreground">
|
||||
{!showQrCode || qrDataUrl ? labels.scanDescription : null}
|
||||
</p>
|
||||
{renderPending?.({ connect, busy, poll: onPoll }) ?? (
|
||||
<div className="mt-3 flex items-center gap-2 text-[12px] text-muted-foreground">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
{!showQrCode || qrDataUrl ? labels.waiting : labels.connecting}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-4 flex flex-wrap justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
onClick={() => onCancel()}
|
||||
disabled={busy}
|
||||
>
|
||||
{tx("settings.actions.cancel", "Cancel")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{succeeded && !suppressSucceeded ? (
|
||||
<div className="flex items-center gap-2 rounded-control border border-emerald-500/20 px-3 py-2 text-[12px] font-medium text-emerald-700 dark:text-emerald-200">
|
||||
<Check className="h-3.5 w-3.5" aria-hidden />
|
||||
{displayMessage ?? labels.connected}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{connect && ["expired", "failed", "cancelled"].includes(connect.status)
|
||||
&& !(connected && connect.status === "cancelled") ? (
|
||||
<div className="rounded-control border border-border/60 px-3 py-2 text-[12px] leading-5 text-muted-foreground">
|
||||
{displayMessage || labels.stopped}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<div className="rounded-control border border-destructive/20 px-3 py-2 text-[12px] leading-5 text-destructive">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!pending && !(autoStart && busy && !connect) ? renderActionRow(
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 rounded-full border-border/65 bg-background/80 px-3 text-[12px] font-semibold settings-hover"
|
||||
onClick={() => onStart()}
|
||||
disabled={!canStart}
|
||||
>
|
||||
{busy ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : succeeded ? (
|
||||
<RotateCcw className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
) : null}
|
||||
{pending
|
||||
? labels.connecting
|
||||
: succeeded
|
||||
? labels.scanAgain
|
||||
: idleLabel ?? labels.connect}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,9 +11,6 @@ import {
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import {
|
||||
Check,
|
||||
ChevronDown,
|
||||
Clipboard,
|
||||
Loader2,
|
||||
Plus,
|
||||
} from "lucide-react";
|
||||
@@ -24,20 +21,17 @@ import type {
|
||||
ChannelFeatureAction,
|
||||
ChannelPluginConnectFlowProps,
|
||||
} from "@/channel-plugins/types";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
|
||||
import {
|
||||
type ChannelProviderPreset,
|
||||
type ChannelSetupPresentation,
|
||||
} from "@/channel-plugins/catalog";
|
||||
import {
|
||||
ChannelFieldGroups,
|
||||
channelRequirementErrors,
|
||||
channelServerValidationErrors,
|
||||
focusFirstChannelFieldError,
|
||||
} from "@/components/settings/channels/ChannelCredentialFields";
|
||||
import {
|
||||
CredentialForm,
|
||||
channelValuesForSubmit,
|
||||
defaultChannelFieldValues,
|
||||
} from "@/components/settings/channels/CredentialForm";
|
||||
@@ -49,11 +43,7 @@ import {
|
||||
channelToggleChecked,
|
||||
localizedChannelDisplayName,
|
||||
} from "@/components/settings/channels/ChannelIdentity";
|
||||
import {
|
||||
ChannelProviderPresets,
|
||||
ChannelSetupActions,
|
||||
} from "@/components/settings/channels/ChannelSetupParts";
|
||||
import { ChannelValidationProgress } from "@/components/settings/channels/ChannelValidationProgress";
|
||||
import { ChannelSetupSurfaceView } from "@/components/settings/channels/ChannelSetupSurfaceView";
|
||||
import { ChannelInstancesPanel } from "@/components/settings/channels/ChannelInstancesPanel";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -235,9 +225,6 @@ function ChannelSetupSurface({
|
||||
(field) => field.secret && configuredFields.has(field.key),
|
||||
);
|
||||
const availablePresets = feature.configured ? [] : setup.presets ?? [];
|
||||
const hasAdvanced = advancedFields.length > 0
|
||||
|| savedSecretFields.length > 0
|
||||
|| availablePresets.length > 0;
|
||||
const [fieldValues, setFieldValues] = useState<Record<string, string>>(() =>
|
||||
defaultChannelFieldValues(editableFields, feature.config_values),
|
||||
);
|
||||
@@ -507,230 +494,23 @@ function ChannelSetupSurface({
|
||||
}
|
||||
};
|
||||
|
||||
const inlineActions = mode === "credentials" && primaryFields.length === 1
|
||||
&& !advancedOpen && !setup.presets?.length && !setup.actions?.length;
|
||||
const credentialActions = mode === "credentials" ? (
|
||||
<div className="ms-auto flex min-h-10 flex-wrap items-center justify-end gap-x-3 gap-y-2 sm:min-h-9">
|
||||
{feature.setup?.verifies_connection ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-10 rounded-full px-3 text-[12px] font-semibold sm:h-9"
|
||||
onClick={() => void checkCurrentSettings()}
|
||||
disabled={actionPending}
|
||||
>
|
||||
{tx("settings.channels.checkConnection", "Check connection")}
|
||||
</Button>
|
||||
) : null}
|
||||
<ToggleButton checked={enabled} disabled={actionPending}
|
||||
label={tx("settings.channels.enable", "Enable")}
|
||||
onChange={(next) => void toggleEnabled(next)} />
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (mode === "credentials") void saveCredentialSettings();
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 pe-20">
|
||||
{header}
|
||||
<div className="ms-auto flex min-h-8 items-center gap-2">
|
||||
<span
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 text-[11px] leading-4 text-muted-foreground",
|
||||
!autoSaving && autoSaveState !== "saved" && "sr-only",
|
||||
)}
|
||||
>
|
||||
{autoSaving ? (
|
||||
<>
|
||||
<Loader2 className="h-3 w-3 animate-spin" aria-hidden />
|
||||
{tx("settings.actions.saving", "Saving")}
|
||||
</>
|
||||
) : autoSaveState === "saved" ? (
|
||||
<>
|
||||
<Check className="h-3 w-3" aria-hidden />
|
||||
{tx("settings.channels.savedSettings", "Settings saved.")}
|
||||
</>
|
||||
) : null}
|
||||
</span>
|
||||
{hasAdvanced ? (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"
|
||||
aria-expanded={advancedOpen}
|
||||
aria-controls={advancedPanelId}
|
||||
onClick={() => setAdvancedOpen((current) => !current)}
|
||||
>
|
||||
{tx("settings.channels.advanced", "Advanced")}
|
||||
<ChevronDown className={cn(
|
||||
"h-3.5 w-3.5 transition-transform motion-reduce:transition-none",
|
||||
advancedOpen && "rotate-180",
|
||||
)} aria-hidden />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<ChannelRuntimeError message={feature.runtime_error} />
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<section className={cn("min-w-0", inlineActions ? "flex-[1_1_20rem]" : "w-full")}>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex max-w-full flex-wrap justify-end gap-2">
|
||||
{mode === "webui" ? (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11.5px] font-medium text-emerald-700 dark:text-emerald-200">
|
||||
<Check className="h-3.5 w-3.5" aria-hidden />
|
||||
{tx("settings.channels.managedByWebui", "Managed by WebUI")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<ChannelSetupActions feature={feature} setup={setup} onNotice={setNotice} />
|
||||
|
||||
{mode === "connect" && ConnectFlow ? (
|
||||
<Suspense fallback={<ChannelPluginLoading compact />}>
|
||||
<ConnectFlow
|
||||
token={token}
|
||||
feature={feature}
|
||||
idleLabel={setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}
|
||||
connectRequestId={connectRequestId}
|
||||
onFeaturesUpdate={onFeaturesUpdate}
|
||||
/>
|
||||
</Suspense>
|
||||
) : mode === "connect" ? (
|
||||
<>
|
||||
<div className="mt-3 flex flex-wrap justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold settings-hover"
|
||||
onClick={() =>
|
||||
setNotice(
|
||||
tx(
|
||||
"settings.channels.connectPreview",
|
||||
"Run the command below in your terminal to connect.",
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
{setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}
|
||||
</Button>
|
||||
{setup.command ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
onClick={copyCommand}
|
||||
>
|
||||
<Clipboard className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
{tx("settings.channels.copyCommand", "Copy command")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{setup.command ? (
|
||||
<code className="mt-3 block rounded-control border border-border/50 bg-muted/45 px-2.5 py-2 font-mono text-[11px] leading-5 text-foreground">
|
||||
{setup.command}
|
||||
</code>
|
||||
) : null}
|
||||
</>
|
||||
) : mode === "credentials" ? (
|
||||
<>
|
||||
{primaryFields.length ? (
|
||||
<ChannelFieldGroups
|
||||
fields={primaryFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onFieldBlur={saveSecretOnBlur}
|
||||
onToggleSecret={toggleSecret}
|
||||
errors={fieldErrors}
|
||||
clearedSecrets={clearedSecrets}
|
||||
onClearSecret={setSecretCleared}
|
||||
requirements={setup.requirements ?? []}
|
||||
sectionLabels={setup.sectionLabels}
|
||||
disabled={actionPending}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{hasAdvanced ? (
|
||||
<div id={advancedPanelId} hidden={!advancedOpen} className="min-w-0 w-full space-y-3 text-[12px] leading-5 text-muted-foreground">
|
||||
{availablePresets.length ? (
|
||||
<ChannelProviderPresets
|
||||
presets={availablePresets}
|
||||
onApply={applyPreset}
|
||||
label={setup.presetLabel}
|
||||
disabled={actionPending}
|
||||
/>
|
||||
) : null}
|
||||
<div className="space-y-2">
|
||||
{savedSecretFields.filter((field) => !(fieldValues[field.key] ?? "").trim()).map((field) => (
|
||||
<div key={field.key} className="flex min-h-9 flex-wrap items-center justify-between gap-x-4 gap-y-1">
|
||||
<span>{field.label}</span>
|
||||
<button type="button" className="min-h-8 text-[12px] hover:text-foreground"
|
||||
onClick={() => setSecretCleared(field.key, !clearedSecrets.has(field.key))}>
|
||||
{clearedSecrets.has(field.key)
|
||||
? tx("settings.channels.keepSavedSecret", "Keep saved credential")
|
||||
: tx("settings.channels.removeSavedSecret", "Remove saved credential")}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{advancedFields.length ? (
|
||||
<div onBlur={() => void saveConnectionSettings()}>
|
||||
<CredentialForm
|
||||
fields={advancedFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onFieldBlur={saveSecretOnBlur}
|
||||
onToggleSecret={toggleSecret}
|
||||
errors={fieldErrors}
|
||||
clearedSecrets={clearedSecrets}
|
||||
onClearSecret={setSecretCleared}
|
||||
compact
|
||||
disabled={actionPending}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{credentialActions}
|
||||
</div>
|
||||
{mode === "credentials" && feature.setup?.verifies_connection
|
||||
&& (validation || validating) ? (
|
||||
<div>
|
||||
<ChannelValidationProgress
|
||||
validation={validation}
|
||||
validating={validating}
|
||||
feature={feature}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className={cn(
|
||||
"rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground",
|
||||
!notice && "sr-only",
|
||||
)}
|
||||
>
|
||||
{notice ?? ""}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
return <ChannelSetupSurfaceView
|
||||
header={header} feature={feature} setup={setup}
|
||||
primaryFields={primaryFields} advancedFields={advancedFields} savedSecretFields={savedSecretFields}
|
||||
availablePresets={availablePresets} configuredFields={configuredFields}
|
||||
fieldValues={fieldValues} visibleSecrets={visibleSecrets} clearedSecrets={clearedSecrets} fieldErrors={fieldErrors}
|
||||
actionPending={actionPending} enabled={enabled} autoSaving={autoSaving} autoSaveState={autoSaveState}
|
||||
advancedOpen={advancedOpen} advancedPanelId={advancedPanelId} validation={validation} validating={validating} notice={notice}
|
||||
onAdvancedOpenChange={setAdvancedOpen} onChangeField={setFieldValue} onFieldBlur={saveSecretOnBlur}
|
||||
onToggleSecret={toggleSecret} onClearSecret={setSecretCleared} onApplyPreset={applyPreset}
|
||||
onSubmit={saveCredentialSettings} onCheckConnection={checkCurrentSettings} onToggleEnabled={toggleEnabled}
|
||||
onSaveConnectionSettings={saveConnectionSettings} onCopyCommand={copyCommand} onNotice={setNotice}
|
||||
connectFlow={mode === "connect" && ConnectFlow ? <Suspense fallback={<ChannelPluginLoading compact />}>
|
||||
<ConnectFlow token={token} feature={feature}
|
||||
idleLabel={setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}
|
||||
connectRequestId={connectRequestId} onFeaturesUpdate={onFeaturesUpdate} />
|
||||
</Suspense> : undefined}
|
||||
/>;
|
||||
}
|
||||
|
||||
function ChannelPluginLoading({ compact = false }: { compact?: boolean }) {
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Check, ChevronDown, Clipboard, Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import type { ChannelConfigField, ChannelProviderPreset, ChannelSetupPresentation } from "@/channel-plugins/catalog";
|
||||
import { ChannelFieldGroups } from "./ChannelCredentialFields";
|
||||
import { CredentialForm } from "./CredentialForm";
|
||||
import { ChannelRuntimeError } from "./ChannelIdentity";
|
||||
import { ChannelProviderPresets, ChannelSetupActions } from "./ChannelSetupParts";
|
||||
import { ChannelValidationProgress } from "./ChannelValidationProgress";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { ChannelValidationPayload, NanobotFeatureInfo } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export interface ChannelSetupSurfaceViewProps {
|
||||
header: ReactNode;
|
||||
feature: NanobotFeatureInfo;
|
||||
setup: ChannelSetupPresentation;
|
||||
primaryFields: ChannelConfigField[];
|
||||
advancedFields: ChannelConfigField[];
|
||||
savedSecretFields: ChannelConfigField[];
|
||||
availablePresets: ChannelProviderPreset[];
|
||||
configuredFields: Set<string>;
|
||||
fieldValues: Record<string, string>;
|
||||
visibleSecrets: Record<string, boolean>;
|
||||
clearedSecrets: Set<string>;
|
||||
fieldErrors: Record<string, string>;
|
||||
actionPending: boolean;
|
||||
enabled: boolean;
|
||||
autoSaving: boolean;
|
||||
autoSaveState: "idle" | "saved";
|
||||
advancedOpen: boolean;
|
||||
advancedPanelId: string;
|
||||
validation: ChannelValidationPayload | null;
|
||||
validating: boolean;
|
||||
notice: string | null;
|
||||
connectFlow?: ReactNode;
|
||||
onAdvancedOpenChange: (open: boolean) => void;
|
||||
onChangeField: (key: string, value: string) => void;
|
||||
onFieldBlur: (key: string) => void;
|
||||
onToggleSecret: (key: string) => void;
|
||||
onClearSecret: (key: string, clear: boolean) => void;
|
||||
onApplyPreset: (preset: ChannelProviderPreset) => void;
|
||||
onSubmit: () => void;
|
||||
onCheckConnection: () => void;
|
||||
onToggleEnabled: (enabled: boolean) => void;
|
||||
onSaveConnectionSettings: () => void;
|
||||
onCopyCommand: () => void;
|
||||
onNotice: (notice: string | null) => void;
|
||||
}
|
||||
|
||||
export function ChannelSetupSurfaceView({
|
||||
header, feature, setup, primaryFields, advancedFields, savedSecretFields, availablePresets,
|
||||
configuredFields, fieldValues, visibleSecrets, clearedSecrets, fieldErrors, actionPending,
|
||||
enabled, autoSaving, autoSaveState, advancedOpen, advancedPanelId, validation, validating,
|
||||
notice, connectFlow, onAdvancedOpenChange,
|
||||
onChangeField: setFieldValue, onFieldBlur: saveSecretOnBlur, onToggleSecret: toggleSecret,
|
||||
onClearSecret: setSecretCleared, onApplyPreset: applyPreset, onSubmit: saveCredentialSettings,
|
||||
onCheckConnection: checkCurrentSettings, onToggleEnabled: toggleEnabled,
|
||||
onSaveConnectionSettings: saveConnectionSettings, onCopyCommand: copyCommand, onNotice: setNotice,
|
||||
}: ChannelSetupSurfaceViewProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const mode = setup.mode ?? "credentials";
|
||||
const hasAdvanced = advancedFields.length > 0 || savedSecretFields.length > 0 || availablePresets.length > 0;
|
||||
const inlineActions = mode === "credentials" && primaryFields.length === 1
|
||||
&& !advancedOpen && !setup.presets?.length && !setup.actions?.length;
|
||||
const credentialActions = mode === "credentials" ? (
|
||||
<div className="ms-auto flex min-h-10 flex-wrap items-center justify-end gap-x-3 gap-y-2 sm:min-h-9">
|
||||
{feature.setup?.verifies_connection ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-10 rounded-full px-3 text-[12px] font-semibold sm:h-9"
|
||||
onClick={() => void checkCurrentSettings()}
|
||||
disabled={actionPending}
|
||||
>
|
||||
{tx("settings.channels.checkConnection", "Check connection")}
|
||||
</Button>
|
||||
) : null}
|
||||
<ToggleButton checked={enabled} disabled={actionPending}
|
||||
label={tx("settings.channels.enable", "Enable")}
|
||||
onChange={(next) => void toggleEnabled(next)} />
|
||||
</div>
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (mode === "credentials") void saveCredentialSettings();
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 pe-20">
|
||||
{header}
|
||||
<div className="ms-auto flex min-h-8 items-center gap-2">
|
||||
<span
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1.5 text-[11px] leading-4 text-muted-foreground",
|
||||
!autoSaving && autoSaveState !== "saved" && "sr-only",
|
||||
)}
|
||||
>
|
||||
{autoSaving ? (
|
||||
<>
|
||||
<Loader2 className="h-3 w-3 animate-spin" aria-hidden />
|
||||
{tx("settings.actions.saving", "Saving")}
|
||||
</>
|
||||
) : autoSaveState === "saved" ? (
|
||||
<>
|
||||
<Check className="h-3 w-3" aria-hidden />
|
||||
{tx("settings.channels.savedSettings", "Settings saved.")}
|
||||
</>
|
||||
) : null}
|
||||
</span>
|
||||
{hasAdvanced ? (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex min-h-8 items-center gap-1.5 rounded px-1 text-[12px] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"
|
||||
aria-expanded={advancedOpen}
|
||||
aria-controls={advancedPanelId}
|
||||
onClick={() => onAdvancedOpenChange(!advancedOpen)}
|
||||
>
|
||||
{tx("settings.channels.advanced", "Advanced")}
|
||||
<ChevronDown className={cn(
|
||||
"h-3.5 w-3.5 transition-transform motion-reduce:transition-none",
|
||||
advancedOpen && "rotate-180",
|
||||
)} aria-hidden />
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<ChannelRuntimeError message={feature.runtime_error} />
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<section className={cn("min-w-0", inlineActions ? "flex-[1_1_20rem]" : "w-full")}>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex max-w-full flex-wrap justify-end gap-2">
|
||||
{mode === "webui" ? (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11.5px] font-medium text-emerald-700 dark:text-emerald-200">
|
||||
<Check className="h-3.5 w-3.5" aria-hidden />
|
||||
{tx("settings.channels.managedByWebui", "Managed by WebUI")}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<ChannelSetupActions feature={feature} setup={setup} onNotice={setNotice} />
|
||||
|
||||
{mode === "connect" && connectFlow ? (
|
||||
connectFlow
|
||||
) : mode === "connect" ? (
|
||||
<>
|
||||
<div className="mt-3 flex flex-wrap justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 rounded-full bg-background/80 px-3 text-[12px] font-semibold settings-hover"
|
||||
onClick={() =>
|
||||
setNotice(
|
||||
tx(
|
||||
"settings.channels.connectPreview",
|
||||
"Run the command below in your terminal to connect.",
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
{setup.primaryActionLabel ?? tx("settings.channels.connect", "Connect")}
|
||||
</Button>
|
||||
{setup.command ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="h-8 rounded-full px-3 text-[12px] font-semibold"
|
||||
onClick={copyCommand}
|
||||
>
|
||||
<Clipboard className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
{tx("settings.channels.copyCommand", "Copy command")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{setup.command ? (
|
||||
<code className="mt-3 block rounded-control border border-border/50 bg-muted/45 px-2.5 py-2 font-mono text-[11px] leading-5 text-foreground">
|
||||
{setup.command}
|
||||
</code>
|
||||
) : null}
|
||||
</>
|
||||
) : mode === "credentials" ? (
|
||||
<>
|
||||
{primaryFields.length ? (
|
||||
<ChannelFieldGroups
|
||||
fields={primaryFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onFieldBlur={saveSecretOnBlur}
|
||||
onToggleSecret={toggleSecret}
|
||||
errors={fieldErrors}
|
||||
clearedSecrets={clearedSecrets}
|
||||
onClearSecret={setSecretCleared}
|
||||
requirements={setup.requirements ?? []}
|
||||
sectionLabels={setup.sectionLabels}
|
||||
disabled={actionPending}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{hasAdvanced ? (
|
||||
<div id={advancedPanelId} hidden={!advancedOpen} className="min-w-0 w-full space-y-3 text-[12px] leading-5 text-muted-foreground">
|
||||
{availablePresets.length ? (
|
||||
<ChannelProviderPresets
|
||||
presets={availablePresets}
|
||||
onApply={applyPreset}
|
||||
label={setup.presetLabel}
|
||||
disabled={actionPending}
|
||||
/>
|
||||
) : null}
|
||||
<div className="space-y-2">
|
||||
{savedSecretFields.filter((field) => !(fieldValues[field.key] ?? "").trim()).map((field) => (
|
||||
<div key={field.key} className="flex min-h-9 flex-wrap items-center justify-between gap-x-4 gap-y-1">
|
||||
<span>{field.label}</span>
|
||||
<button type="button" className="min-h-8 text-[12px] hover:text-foreground"
|
||||
onClick={() => setSecretCleared(field.key, !clearedSecrets.has(field.key))}>
|
||||
{clearedSecrets.has(field.key)
|
||||
? tx("settings.channels.keepSavedSecret", "Keep saved credential")
|
||||
: tx("settings.channels.removeSavedSecret", "Remove saved credential")}
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{advancedFields.length ? (
|
||||
<div onBlur={() => void saveConnectionSettings()}>
|
||||
<CredentialForm
|
||||
fields={advancedFields}
|
||||
values={fieldValues}
|
||||
configuredFields={configuredFields}
|
||||
visibleSecrets={visibleSecrets}
|
||||
onChange={setFieldValue}
|
||||
onFieldBlur={saveSecretOnBlur}
|
||||
onToggleSecret={toggleSecret}
|
||||
errors={fieldErrors}
|
||||
clearedSecrets={clearedSecrets}
|
||||
onClearSecret={setSecretCleared}
|
||||
compact
|
||||
disabled={actionPending}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{credentialActions}
|
||||
</div>
|
||||
{mode === "credentials" && feature.setup?.verifies_connection
|
||||
&& (validation || validating) ? (
|
||||
<div>
|
||||
<ChannelValidationProgress
|
||||
validation={validation}
|
||||
validating={validating}
|
||||
feature={feature}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className={cn(
|
||||
"rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground",
|
||||
!notice && "sr-only",
|
||||
)}
|
||||
>
|
||||
{notice ?? ""}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { modelAPIConfigurable, preferredModelAPI, REQUEST_API_LABELS } from "@/components/settings/models/modelAPI";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { SettingsRow } from "@/components/settings/shared/SettingsControls";
|
||||
import { SettingsHint } from "@/components/settings/shared/SettingsHint";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useAutomaticModelAPI } from "@/components/settings/models/useAutomaticM
|
||||
import { useModelPresetDrag } from "@/components/settings/models/useModelPresetDrag";
|
||||
import { ReasoningEffortPicker } from "@/components/settings/models/ReasoningEffortPicker";
|
||||
import { RemoveActionButton } from "@/components/settings/shared/RemoveActionButton";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { useAutoSave } from "@/components/settings/shared/useAutoSave";
|
||||
import { useEffect, useId, useRef, useState, type Dispatch, type SetStateAction } from "react";
|
||||
import {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { MODEL_REQUEST_APIS, REQUEST_API_LABELS } from "@/components/settings/models/modelAPI";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { SettingsHint } from "@/components/settings/shared/SettingsHint";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import type { ModelAPIConfig, ModelRequestAPI } from "@/lib/types";
|
||||
|
||||
@@ -20,7 +20,7 @@ import { ProviderIcon } from "@/components/settings/shared/ProviderIcon";
|
||||
import { ProviderSearchList } from "@/components/settings/models/ProviderSearchList";
|
||||
export { ProviderIcon } from "@/components/settings/shared/ProviderIcon";
|
||||
import { CapabilityInstallNotice } from "@/components/settings/shared/SettingsControls";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { ModelAPIControl } from "@/components/settings/models/ModelAPIControl";
|
||||
import { ProviderAPIControl } from "@/components/settings/models/ProviderAPIControl";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { BookOpen, ExternalLink, Github, MessageCircle } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { SettingsGroup } from "@/components/settings/shared/SettingsControls";
|
||||
|
||||
export function AboutSettingsView({ reportIssueUrl, versionCheck, starLink }: {
|
||||
reportIssueUrl: string;
|
||||
versionCheck: ReactNode;
|
||||
starLink: ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const links = [
|
||||
{ key: "sourceCode", icon: Github, href: "https://github.com/HKUDS/nanobot" },
|
||||
{ key: "documentation", icon: BookOpen, href: "https://nanobot.wiki/" },
|
||||
{ key: "reportIssue", icon: MessageCircle, href: reportIssueUrl },
|
||||
];
|
||||
return (
|
||||
<div className="flex flex-1 flex-col gap-5">
|
||||
<div className="flex flex-col items-center gap-4 py-6 text-center">
|
||||
<img src="/brand/nanobot_mark.svg" alt="" className="h-16 w-16 select-none" draggable={false} />
|
||||
<h1><img src="/brand/nanobot_wordmark.svg" alt="nanobot" className="h-auto w-40 select-none dark:brightness-150" draggable={false} /></h1>
|
||||
{versionCheck}
|
||||
</div>
|
||||
<SettingsGroup>
|
||||
{links.map(({ key, icon: Icon, href }) => (
|
||||
<a key={key} href={href} target="_blank" rel="noopener noreferrer"
|
||||
className="settings-list-row flex select-none items-center gap-3 text-[14px] settings-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
<Icon className="h-4 w-4 text-muted-foreground" aria-hidden />
|
||||
<span className="flex-1">{t(`settings.about.${key}`)}</span>
|
||||
<ExternalLink className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />
|
||||
</a>
|
||||
))}
|
||||
</SettingsGroup>
|
||||
<div className="mt-auto pt-8 text-center">
|
||||
{starLink}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
|
||||
import { SettingsGroup, SettingsRow, SettingsSectionTitle } from "@/components/settings/shared/SettingsControls";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { SegmentedControl } from "@/components/ui/segmented-control";
|
||||
import type { FileEditDisplayMode, LocalActivityMode, LocalPreferences } from "@/lib/local-preferences";
|
||||
|
||||
export function AppearanceSettingsView({
|
||||
theme,
|
||||
onToggleTheme,
|
||||
localPrefs,
|
||||
onChangeLocalPrefs,
|
||||
onChangeBrowserNotifications,
|
||||
}: {
|
||||
theme: "light" | "dark";
|
||||
onToggleTheme: () => void;
|
||||
localPrefs: LocalPreferences;
|
||||
onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;
|
||||
onChangeBrowserNotifications: (enabled: boolean) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
return (
|
||||
<div className="settings-stack">
|
||||
<section>
|
||||
<SettingsSectionTitle>{t("settings.sections.interface")}</SettingsSectionTitle>
|
||||
<SettingsGroup>
|
||||
<SettingsRow title={t("settings.rows.theme")}>
|
||||
<SegmentedControl
|
||||
value={theme}
|
||||
ariaLabel={t("settings.rows.theme")}
|
||||
className="bg-muted p-0.5"
|
||||
itemClassName="px-3"
|
||||
options={[
|
||||
{ value: "light", label: t("settings.values.light") },
|
||||
{ value: "dark", label: t("settings.values.dark") },
|
||||
]}
|
||||
onChange={(nextTheme) => {
|
||||
if (nextTheme !== theme) onToggleTheme();
|
||||
}}
|
||||
/>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow title={t("settings.rows.language")}>
|
||||
<LanguageSwitcher />
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<SettingsSectionTitle>{tx("settings.sections.localPreferences", "Local preferences")}</SettingsSectionTitle>
|
||||
<SettingsGroup>
|
||||
<SettingsRow title={tx("settings.rows.activityMode", "Activity detail")}>
|
||||
<SegmentedControl
|
||||
value={localPrefs.activityMode}
|
||||
options={[
|
||||
{ value: "auto", label: tx("settings.values.auto", "Auto") },
|
||||
{ value: "expanded", label: tx("settings.values.expanded", "Expanded") },
|
||||
]}
|
||||
onChange={(activityMode) =>
|
||||
onChangeLocalPrefs((prev) => ({ ...prev, activityMode: activityMode as LocalActivityMode }))
|
||||
}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow title={tx("settings.rows.fileEditDisplay", "File edit display")}>
|
||||
<SegmentedControl
|
||||
value={localPrefs.fileEditDisplayMode}
|
||||
options={[
|
||||
{ value: "summary", label: tx("settings.values.summary", "Summary") },
|
||||
{ value: "diff", label: tx("settings.values.diff", "Diff") },
|
||||
{ value: "collapsed_diff", label: tx("settings.values.collapsedDiff", "Collapsed diff") },
|
||||
]}
|
||||
onChange={(fileEditDisplayMode) =>
|
||||
onChangeLocalPrefs((prev) => ({
|
||||
...prev,
|
||||
fileEditDisplayMode: fileEditDisplayMode as FileEditDisplayMode,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow title={tx("settings.rows.codeWrap", "Code wrapping")}>
|
||||
<ToggleButton
|
||||
checked={localPrefs.codeWrap}
|
||||
onChange={(codeWrap) => onChangeLocalPrefs((prev) => ({ ...prev, codeWrap }))}
|
||||
ariaLabel={tx("settings.rows.codeWrap", "Code wrapping")}
|
||||
label={localPrefs.codeWrap ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
title={tx("settings.rows.brandLogos", "Brand logos")}
|
||||
description={tx(
|
||||
"settings.legal.thirdPartyBrands",
|
||||
"Product names, logos, and brands are property of their respective owners. Use is for identification only and does not imply endorsement.",
|
||||
)}
|
||||
>
|
||||
<ToggleButton
|
||||
checked={localPrefs.brandLogos}
|
||||
onChange={(brandLogos) => onChangeLocalPrefs((prev) => ({ ...prev, brandLogos }))}
|
||||
ariaLabel={tx("settings.rows.brandLogos", "Brand logos")}
|
||||
label={localPrefs.brandLogos ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
title={tx("settings.rows.browserNotifications", "Task notifications")}
|
||||
description={tx(
|
||||
"settings.help.browserNotifications",
|
||||
"Notify only when this page is in the background. Off by default.",
|
||||
)}
|
||||
>
|
||||
<ToggleButton
|
||||
checked={localPrefs.browserNotifications}
|
||||
onChange={onChangeBrowserNotifications}
|
||||
ariaLabel={tx("settings.rows.browserNotifications", "Task notifications")}
|
||||
label={localPrefs.browserNotifications
|
||||
? tx("settings.values.on", "On")
|
||||
: tx("settings.values.off", "Off")}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
title={tx("settings.rows.notificationSound", "Completion sound")}
|
||||
description={tx(
|
||||
"settings.help.notificationSound",
|
||||
"Play a short chime when a turn finishes, even when this page is in the background. Off by default.",
|
||||
)}
|
||||
>
|
||||
<ToggleButton
|
||||
checked={localPrefs.notificationSound}
|
||||
onChange={(notificationSound) =>
|
||||
onChangeLocalPrefs((prev) => ({ ...prev, notificationSound }))}
|
||||
ariaLabel={tx("settings.rows.notificationSound", "Completion sound")}
|
||||
label={localPrefs.notificationSound
|
||||
? tx("settings.values.on", "On")
|
||||
: tx("settings.values.off", "Off")}
|
||||
/>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,38 +6,27 @@ import {
|
||||
} from "@/components/icons/product-icons";
|
||||
import { useContext, useState, type Dispatch, type SetStateAction } from "react";
|
||||
import {
|
||||
ArrowUpCircle,
|
||||
BookOpen,
|
||||
MessageCircle,
|
||||
Check,
|
||||
ChevronRight,
|
||||
ExternalLink,
|
||||
Github,
|
||||
Loader2,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { HostNavigationContext } from "@/components/remote/HostSwitcher";
|
||||
import { StarLink } from "@/components/StarPrompt";
|
||||
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
|
||||
import { AboutSettingsView } from "./AboutSettingsView";
|
||||
import { AppearanceSettingsView } from "./AppearanceSettingsView";
|
||||
import { VersionCheckRowView, type VersionCheckState, type VersionInfoProps } from "./VersionCheckRowView";
|
||||
import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings";
|
||||
import type { SettingsSectionKey } from "@/components/settings/contracts";
|
||||
import { settingsProviderConfigured } from "@/components/settings/shared/ModelControls";
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsRow,
|
||||
SettingsSectionTitle,
|
||||
} from "@/components/settings/shared/SettingsControls";
|
||||
import { TokenUsageCard } from "@/components/settings/TokenUsageCard";
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { SegmentedControl } from "@/components/ui/segmented-control";
|
||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||
import { checkVersion } from "@/lib/api";
|
||||
import type {
|
||||
FileEditDisplayMode,
|
||||
LocalActivityMode,
|
||||
LocalPreferences,
|
||||
} from "@/lib/local-preferences";
|
||||
import { providerBrand, providerDisplayLabel } from "@/lib/provider-brand";
|
||||
@@ -138,10 +127,7 @@ export function OverviewSettings({
|
||||
);
|
||||
}
|
||||
|
||||
type VersionInfoProps = { currentVersion?: string; currentCommit?: string | null };
|
||||
|
||||
export function AboutSettings({ settings }: { settings: SettingsPayload }) {
|
||||
const { t } = useTranslation();
|
||||
const hostPicker = useContext(HostNavigationContext);
|
||||
const currentVersion = settings.version?.current;
|
||||
const currentCommit = settings.version?.commit;
|
||||
@@ -165,46 +151,15 @@ export function AboutSettings({ settings }: { settings: SettingsPayload }) {
|
||||
reportIssueUrl.searchParams.set("browser", navigator.userAgent);
|
||||
reportIssueUrl.searchParams.set("connection", hostPicker?.kind === "embedded"
|
||||
? "Remote host" : hostPicker ? "Local host" : "Direct WebUI");
|
||||
const links = [
|
||||
{ key: "sourceCode", icon: Github, href: "https://github.com/HKUDS/nanobot" },
|
||||
{ key: "documentation", icon: BookOpen, href: "https://nanobot.wiki/" },
|
||||
{ key: "reportIssue", icon: MessageCircle, href: reportIssueUrl.href },
|
||||
];
|
||||
return (
|
||||
<div className="flex flex-1 flex-col gap-5">
|
||||
<div className="flex flex-col items-center gap-4 py-6 text-center">
|
||||
<img src="/brand/nanobot_mark.svg" alt="" className="h-16 w-16 select-none" draggable={false} />
|
||||
<h1><img src="/brand/nanobot_wordmark.svg" alt="nanobot" className="h-auto w-40 select-none dark:brightness-150" draggable={false} /></h1>
|
||||
<VersionCheckRow currentVersion={currentVersion} currentCommit={currentCommit} />
|
||||
</div>
|
||||
<SettingsGroup>
|
||||
{links.map(({ key, icon: Icon, href }) => (
|
||||
<a key={key} href={href} target="_blank" rel="noopener noreferrer"
|
||||
className="settings-list-row flex select-none items-center gap-3 text-[14px] settings-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
<Icon className="h-4 w-4 text-muted-foreground" aria-hidden />
|
||||
<span className="flex-1">{t(`settings.about.${key}`)}</span>
|
||||
<ExternalLink className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />
|
||||
</a>
|
||||
))}
|
||||
</SettingsGroup>
|
||||
<div className="mt-auto pt-8 text-center">
|
||||
<StarLink />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return <AboutSettingsView reportIssueUrl={reportIssueUrl.href}
|
||||
versionCheck={<VersionCheckRow currentVersion={currentVersion} currentCommit={currentCommit} />}
|
||||
starLink={<StarLink />} />;
|
||||
}
|
||||
|
||||
function VersionCheckRow({ currentVersion, currentCommit }: VersionInfoProps) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
const { token } = useClient();
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [result, setResult] = useState<
|
||||
| { type: "up-to-date" }
|
||||
| { type: "update"; latestVersion: string; pypiUrl?: string }
|
||||
| { type: "error"; message: string }
|
||||
| null
|
||||
>(null);
|
||||
const [result, setResult] = useState<VersionCheckState>(null);
|
||||
|
||||
const handleCheck = async () => {
|
||||
setChecking(true);
|
||||
@@ -227,223 +182,35 @@ function VersionCheckRow({ currentVersion, currentCommit }: VersionInfoProps) {
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="min-w-0">
|
||||
<div className="sr-only">
|
||||
{tx("settings.about.version", "Version")}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[12px] leading-5 text-muted-foreground">
|
||||
{currentVersion ? `v${currentVersion}` : "nanobot"}
|
||||
{currentCommit && (
|
||||
<>
|
||||
<span aria-hidden> (</span>
|
||||
<a href={`https://github.com/HKUDS/nanobot/commit/${currentCommit}`}
|
||||
target="_blank" rel="noopener noreferrer" title={currentCommit}
|
||||
className="font-mono hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
{currentCommit.slice(0, 7)}
|
||||
</a>
|
||||
<span aria-hidden>)</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-col items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => void handleCheck()}
|
||||
disabled={checking}
|
||||
className="rounded-full"
|
||||
>
|
||||
{checking ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : (
|
||||
<ArrowUpCircle className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
)}
|
||||
{checking
|
||||
? tx("settings.about.checking", "Checking...")
|
||||
: tx("settings.about.checkForUpdates", "Check for updates")}
|
||||
</Button>
|
||||
{result?.type === "up-to-date" ? (
|
||||
<span className="inline-flex items-center gap-1.5 text-[12px] text-emerald-600 dark:text-emerald-300">
|
||||
<Check className="h-3 w-3" aria-hidden />
|
||||
{tx("settings.about.upToDate", "You're up to date")}
|
||||
</span>
|
||||
) : null}
|
||||
{result?.type === "update" ? (
|
||||
<span className="inline-flex items-center gap-1.5 text-[12px] text-blue-600 dark:text-blue-300">
|
||||
<ArrowUpCircle className="h-3 w-3" aria-hidden />
|
||||
{t("settings.about.updateAvailable", {
|
||||
defaultValue: "Update available v{{version}}",
|
||||
version: result.latestVersion,
|
||||
})}
|
||||
{result.pypiUrl ? (
|
||||
<a
|
||||
href={result.pypiUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-0.5 underline-offset-2 hover:underline"
|
||||
>
|
||||
PyPI
|
||||
<ExternalLink className="h-2.5 w-2.5" aria-hidden />
|
||||
</a>
|
||||
) : null}
|
||||
</span>
|
||||
) : null}
|
||||
{result?.type === "error" ? (
|
||||
<span className="text-[12px] text-destructive">{result.message}</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
return <VersionCheckRowView currentVersion={currentVersion} currentCommit={currentCommit}
|
||||
checking={checking} result={result} onCheck={() => void handleCheck()} />;
|
||||
}
|
||||
|
||||
export function AppearanceSettings({
|
||||
theme,
|
||||
onToggleTheme,
|
||||
localPrefs,
|
||||
onChangeLocalPrefs,
|
||||
}: {
|
||||
export function AppearanceSettings({ theme, onToggleTheme, localPrefs, onChangeLocalPrefs }: {
|
||||
theme: "light" | "dark";
|
||||
onToggleTheme: () => void;
|
||||
localPrefs: LocalPreferences;
|
||||
onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
return (
|
||||
<div className="settings-stack">
|
||||
<section>
|
||||
<SettingsSectionTitle>{t("settings.sections.interface")}</SettingsSectionTitle>
|
||||
<SettingsGroup>
|
||||
<SettingsRow title={t("settings.rows.theme")}>
|
||||
<SegmentedControl
|
||||
value={theme}
|
||||
ariaLabel={t("settings.rows.theme")}
|
||||
className="bg-muted p-0.5"
|
||||
itemClassName="px-3"
|
||||
options={[
|
||||
{ value: "light", label: t("settings.values.light") },
|
||||
{ value: "dark", label: t("settings.values.dark") },
|
||||
]}
|
||||
onChange={(nextTheme) => {
|
||||
if (nextTheme !== theme) onToggleTheme();
|
||||
}}
|
||||
/>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow title={t("settings.rows.language")}>
|
||||
<LanguageSwitcher />
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<SettingsSectionTitle>{tx("settings.sections.localPreferences", "Local preferences")}</SettingsSectionTitle>
|
||||
<SettingsGroup>
|
||||
<SettingsRow title={tx("settings.rows.activityMode", "Activity detail")}>
|
||||
<SegmentedControl
|
||||
value={localPrefs.activityMode}
|
||||
options={[
|
||||
{ value: "auto", label: tx("settings.values.auto", "Auto") },
|
||||
{ value: "expanded", label: tx("settings.values.expanded", "Expanded") },
|
||||
]}
|
||||
onChange={(activityMode) =>
|
||||
onChangeLocalPrefs((prev) => ({ ...prev, activityMode: activityMode as LocalActivityMode }))
|
||||
}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow title={tx("settings.rows.fileEditDisplay", "File edit display")}>
|
||||
<SegmentedControl
|
||||
value={localPrefs.fileEditDisplayMode}
|
||||
options={[
|
||||
{ value: "summary", label: tx("settings.values.summary", "Summary") },
|
||||
{ value: "diff", label: tx("settings.values.diff", "Diff") },
|
||||
{ value: "collapsed_diff", label: tx("settings.values.collapsedDiff", "Collapsed diff") },
|
||||
]}
|
||||
onChange={(fileEditDisplayMode) =>
|
||||
onChangeLocalPrefs((prev) => ({
|
||||
...prev,
|
||||
fileEditDisplayMode: fileEditDisplayMode as FileEditDisplayMode,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow title={tx("settings.rows.codeWrap", "Code wrapping")}>
|
||||
<ToggleButton
|
||||
checked={localPrefs.codeWrap}
|
||||
onChange={(codeWrap) => onChangeLocalPrefs((prev) => ({ ...prev, codeWrap }))}
|
||||
ariaLabel={tx("settings.rows.codeWrap", "Code wrapping")}
|
||||
label={localPrefs.codeWrap ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
title={tx("settings.rows.brandLogos", "Brand logos")}
|
||||
description={tx(
|
||||
"settings.legal.thirdPartyBrands",
|
||||
"Product names, logos, and brands are property of their respective owners. Use is for identification only and does not imply endorsement.",
|
||||
)}
|
||||
>
|
||||
<ToggleButton
|
||||
checked={localPrefs.brandLogos}
|
||||
onChange={(brandLogos) => onChangeLocalPrefs((prev) => ({ ...prev, brandLogos }))}
|
||||
ariaLabel={tx("settings.rows.brandLogos", "Brand logos")}
|
||||
label={localPrefs.brandLogos ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
title={tx("settings.rows.browserNotifications", "Task notifications")}
|
||||
description={tx(
|
||||
"settings.help.browserNotifications",
|
||||
"Notify only when this page is in the background. Off by default.",
|
||||
)}
|
||||
>
|
||||
<ToggleButton
|
||||
checked={localPrefs.browserNotifications}
|
||||
onChange={(enabled) => {
|
||||
if (!enabled) {
|
||||
onChangeLocalPrefs((prev) => ({ ...prev, browserNotifications: false }));
|
||||
return;
|
||||
}
|
||||
if (typeof Notification === "undefined") return;
|
||||
if (Notification.permission === "granted") {
|
||||
onChangeLocalPrefs((prev) => ({ ...prev, browserNotifications: true }));
|
||||
return;
|
||||
}
|
||||
void Notification.requestPermission().then((permission) => {
|
||||
if (permission === "granted") {
|
||||
onChangeLocalPrefs((prev) => ({ ...prev, browserNotifications: true }));
|
||||
}
|
||||
});
|
||||
}}
|
||||
ariaLabel={tx("settings.rows.browserNotifications", "Task notifications")}
|
||||
label={localPrefs.browserNotifications
|
||||
? tx("settings.values.on", "On")
|
||||
: tx("settings.values.off", "Off")}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
title={tx("settings.rows.notificationSound", "Completion sound")}
|
||||
description={tx(
|
||||
"settings.help.notificationSound",
|
||||
"Play a short chime when a turn finishes, even when this page is in the background. Off by default.",
|
||||
)}
|
||||
>
|
||||
<ToggleButton
|
||||
checked={localPrefs.notificationSound}
|
||||
onChange={(notificationSound) =>
|
||||
onChangeLocalPrefs((prev) => ({ ...prev, notificationSound }))}
|
||||
ariaLabel={tx("settings.rows.notificationSound", "Completion sound")}
|
||||
label={localPrefs.notificationSound
|
||||
? tx("settings.values.on", "On")
|
||||
: tx("settings.values.off", "Off")}
|
||||
/>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
const changeBrowserNotifications = (enabled: boolean) => {
|
||||
if (!enabled) {
|
||||
onChangeLocalPrefs((prev) => ({ ...prev, browserNotifications: false }));
|
||||
return;
|
||||
}
|
||||
if (typeof Notification === "undefined") return;
|
||||
if (Notification.permission === "granted") {
|
||||
onChangeLocalPrefs((prev) => ({ ...prev, browserNotifications: true }));
|
||||
return;
|
||||
}
|
||||
void Notification.requestPermission().then((permission) => {
|
||||
if (permission === "granted") {
|
||||
onChangeLocalPrefs((prev) => ({ ...prev, browserNotifications: true }));
|
||||
}
|
||||
});
|
||||
};
|
||||
return <AppearanceSettingsView theme={theme} onToggleTheme={onToggleTheme}
|
||||
localPrefs={localPrefs} onChangeLocalPrefs={onChangeLocalPrefs}
|
||||
onChangeBrowserNotifications={changeBrowserNotifications} />;
|
||||
}
|
||||
|
||||
function OverviewRowIcon({
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { ArrowUpCircle, Check, ExternalLink, Loader2 } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export type VersionInfoProps = { currentVersion?: string; currentCommit?: string | null };
|
||||
export type VersionCheckState =
|
||||
| { type: "up-to-date" }
|
||||
| { type: "update"; latestVersion: string; pypiUrl?: string }
|
||||
| { type: "error"; message: string }
|
||||
| null;
|
||||
|
||||
export function VersionCheckRowView({ currentVersion, currentCommit, checking, result, onCheck }: VersionInfoProps & {
|
||||
checking: boolean;
|
||||
result: VersionCheckState;
|
||||
onCheck: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="min-w-0">
|
||||
<div className="sr-only">
|
||||
{tx("settings.about.version", "Version")}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[12px] leading-5 text-muted-foreground">
|
||||
{currentVersion ? `v${currentVersion}` : "nanobot"}
|
||||
{currentCommit && (
|
||||
<>
|
||||
<span aria-hidden> (</span>
|
||||
<a href={`https://github.com/HKUDS/nanobot/commit/${currentCommit}`}
|
||||
target="_blank" rel="noopener noreferrer" title={currentCommit}
|
||||
className="font-mono hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
{currentCommit.slice(0, 7)}
|
||||
</a>
|
||||
<span aria-hidden>)</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-col items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={onCheck}
|
||||
disabled={checking}
|
||||
className="rounded-full"
|
||||
>
|
||||
{checking ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
|
||||
) : (
|
||||
<ArrowUpCircle className="mr-1.5 h-3.5 w-3.5" aria-hidden />
|
||||
)}
|
||||
{checking
|
||||
? tx("settings.about.checking", "Checking...")
|
||||
: tx("settings.about.checkForUpdates", "Check for updates")}
|
||||
</Button>
|
||||
{result?.type === "up-to-date" ? (
|
||||
<span className="inline-flex items-center gap-1.5 text-[12px] text-emerald-600 dark:text-emerald-300">
|
||||
<Check className="h-3 w-3" aria-hidden />
|
||||
{tx("settings.about.upToDate", "You're up to date")}
|
||||
</span>
|
||||
) : null}
|
||||
{result?.type === "update" ? (
|
||||
<span className="inline-flex items-center gap-1.5 text-[12px] text-blue-600 dark:text-blue-300">
|
||||
<ArrowUpCircle className="h-3 w-3" aria-hidden />
|
||||
{t("settings.about.updateAvailable", {
|
||||
defaultValue: "Update available v{{version}}",
|
||||
version: result.latestVersion,
|
||||
})}
|
||||
{result.pypiUrl ? (
|
||||
<a
|
||||
href={result.pypiUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-0.5 underline-offset-2 hover:underline"
|
||||
>
|
||||
PyPI
|
||||
<ExternalLink className="h-2.5 w-2.5" aria-hidden />
|
||||
</a>
|
||||
) : null}
|
||||
</span>
|
||||
) : null}
|
||||
{result?.type === "error" ? (
|
||||
<span className="text-[12px] text-destructive">{result.message}</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { forwardRef, type ButtonHTMLAttributes, type ReactNode } from "react";
|
||||
import { Plus } from "lucide-react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export const SettingsAddButton = forwardRef<HTMLButtonElement,
|
||||
ButtonHTMLAttributes<HTMLButtonElement> & { trailing?: ReactNode }
|
||||
>(({ children, trailing, className, type = "button", ...props }, ref) => (
|
||||
<button {...props} ref={ref} type={type}
|
||||
className={cn("settings-list-row flex w-full items-center gap-3 py-2.5 text-left transition-colors settings-hover disabled:cursor-not-allowed disabled:opacity-50", className)}>
|
||||
<span className="flex min-w-0 flex-1 items-center gap-3">
|
||||
<span className="grid h-8 w-8 shrink-0 place-items-center rounded-[9px] bg-muted text-muted-foreground">
|
||||
<Plus className="h-5 w-5" aria-hidden />
|
||||
</span>
|
||||
<span className="truncate text-[14px] font-medium text-foreground">{children}</span>
|
||||
</span>
|
||||
{trailing}
|
||||
</button>
|
||||
));
|
||||
SettingsAddButton.displayName = "SettingsAddButton";
|
||||
@@ -1,7 +1,7 @@
|
||||
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 { ToggleButton } from "@/components/ui/toggle-button";
|
||||
import { SettingsGroup, SettingsRow } from "@/components/settings/shared/SettingsControls";
|
||||
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
||||
import { Disclosure } from "@/components/ui/disclosure";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { CircleAlert, Loader2, X } from "lucide-react";
|
||||
import { useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
|
||||
import { AutomationRunDialog, type AutomationRunRecord } from "@/components/settings/system/AutomationRunDialog";
|
||||
import type { AutomationRunRecord } from "@/components/settings/system/AutomationRunDialogView";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { formControlFocusClassName } from "@/components/ui/form-control";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
@@ -29,13 +29,22 @@ type CalendarCopy = {
|
||||
system: string;
|
||||
};
|
||||
|
||||
export interface AutomationCalendarRunProps {
|
||||
job: SessionAutomationJob;
|
||||
run: AutomationRunRecord;
|
||||
locale: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCloseAutoFocus: (event: Event) => void;
|
||||
}
|
||||
|
||||
interface AutomationCalendarProps {
|
||||
token?: string;
|
||||
jobs: SessionAutomationJob[];
|
||||
month: Date;
|
||||
locale: string;
|
||||
copy: CalendarCopy;
|
||||
onInspect: (job: SessionAutomationJob, trigger: HTMLElement) => void;
|
||||
renderRunDialog: (props: AutomationCalendarRunProps) => ReactNode;
|
||||
}
|
||||
|
||||
function startOfDay(date: Date): Date {
|
||||
@@ -217,7 +226,7 @@ function CalendarOverflowEntries({ entries, dayLabel, locale, copy, onInspect }:
|
||||
);
|
||||
}
|
||||
|
||||
export function AutomationCalendar({ token = "", jobs, month, locale, copy, onInspect }: AutomationCalendarProps) {
|
||||
export function AutomationCalendar({ jobs, month, locale, copy, onInspect, renderRunDialog }: AutomationCalendarProps) {
|
||||
const calendarRef = useRef<HTMLElement | null>(null);
|
||||
const runTrigger = useRef<HTMLElement | null>(null);
|
||||
const [selectedRun, setSelectedRun] = useState<{ job: SessionAutomationJob; run: AutomationRunRecord } | null>(null);
|
||||
@@ -349,18 +358,17 @@ export function AutomationCalendar({ token = "", jobs, month, locale, copy, onIn
|
||||
)}
|
||||
</div> : null}
|
||||
|
||||
{selectedRun ? <AutomationRunDialog
|
||||
token={token}
|
||||
job={selectedRun.job} run={selectedRun.run} locale={locale} open={runOpen}
|
||||
onOpenChange={setRunOpen}
|
||||
onCloseAutoFocus={(event) => {
|
||||
{selectedRun ? renderRunDialog({
|
||||
job: selectedRun.job, run: selectedRun.run, locale, open: runOpen,
|
||||
onOpenChange: setRunOpen,
|
||||
onCloseAutoFocus: (event) => {
|
||||
event.preventDefault();
|
||||
if (runOpen) return;
|
||||
setSelectedRun(null);
|
||||
const target = runTrigger.current?.isConnected ? runTrigger.current : calendarRef.current;
|
||||
target?.focus({ preventScroll: true });
|
||||
}}
|
||||
/> : null}
|
||||
},
|
||||
}) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,193 +1,32 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ChannelLogo } from "@/components/settings/channels/ChannelIdentity";
|
||||
import { channelUiOwner, channelUiPresentation } from "@/channel-plugins/registry";
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
|
||||
import { AutomationChatBindingView, type AutomationChatNames, type ChangeAutomationChat } from "./AutomationChatBindingView";
|
||||
import { fetchAutomationChats } from "@/lib/api";
|
||||
import { readLocalPreferences } from "@/lib/local-preferences";
|
||||
import type { AutomationChat, AutomationChatsPayload, AutomationChatUpdate, NanobotFeatureInfo, SessionAutomationJob } from "@/lib/types";
|
||||
import type { AutomationChatsPayload, SessionAutomationJob } from "@/lib/types";
|
||||
|
||||
export type ChangeAutomationChat = (job: SessionAutomationJob, values: AutomationChatUpdate) => Promise<void>;
|
||||
export type AutomationChatNames = ReadonlyMap<string, { title: string; handle: string }>;
|
||||
|
||||
function ChatIdentity({ chat, title }: { chat: AutomationChat; title: string }) {
|
||||
const { t } = useTranslation();
|
||||
const owner = channelUiOwner(chat.channel);
|
||||
const presentation = channelUiPresentation(chat.channel);
|
||||
const platform = chat.channel === "websocket" ? t("settings.automations.chat.web")
|
||||
: channelTranslator(t, owner)("displayName", presentation?.displayName ?? chat.channel);
|
||||
const feature: NanobotFeatureInfo = {
|
||||
name: chat.channel, display_name: platform, type: "channel", enabled: true,
|
||||
installed: true, ready: true, status: "ready", install_supported: false, requires_restart: false,
|
||||
};
|
||||
return <span className="flex min-w-0 items-center gap-2.5 text-start">
|
||||
<span aria-hidden className="relative h-6 w-6 shrink-0">
|
||||
{chat.channel === "websocket" ? <img src="/brand/nanobot_mark.svg" alt="" className="h-6 w-6" />
|
||||
: <span className="absolute left-0 top-0 origin-top-left scale-75"><ChannelLogo feature={feature} showBrandLogos={readLocalPreferences().brandLogos} /></span>}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-col gap-0.5">
|
||||
<span className="break-words text-sm leading-5 [overflow-wrap:anywhere]">{title}</span>
|
||||
<span className="text-xs leading-4 text-muted-foreground">{platform}</span>
|
||||
</span>
|
||||
</span>;
|
||||
}
|
||||
export type { AutomationChatNames, ChangeAutomationChat } from "./AutomationChatBindingView";
|
||||
|
||||
export function AutomationChatBinding({ job, token, chatNames, onSave, children }: {
|
||||
job: SessionAutomationJob; token: string; onSave: ChangeAutomationChat;
|
||||
chatNames?: AutomationChatNames;
|
||||
children: (picker: ReactNode) => ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, values?: Record<string, string>) => t(`settings.automations.chat.${key}`, values);
|
||||
const [data, setData] = useState<AutomationChatsPayload | null>(null);
|
||||
const [loadError, setLoadError] = useState(false);
|
||||
const [reload, setReload] = useState(0);
|
||||
const [draft, setDraft] = useState<{ target: AutomationChat; previous: AutomationChat; revision: string; message: string; editingMessage?: boolean } | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [saved, setSaved] = useState<{ target: AutomationChat; previous: AutomationChat } | null>(null);
|
||||
const heading = useRef<HTMLHeadingElement>(null);
|
||||
const trigger = useRef<HTMLButtonElement>(null);
|
||||
const returning = useRef(false);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoadError(false);
|
||||
void fetchAutomationChats(token, job.id, controller.signal).then(value => {
|
||||
if (!controller.signal.aborted) {
|
||||
setData(value);
|
||||
setSaved(previous => previous?.target.id === value.current?.id ? previous : null);
|
||||
}
|
||||
if (!controller.signal.aborted) setData(value);
|
||||
}).catch(() => { if (!controller.signal.aborted) setLoadError(true); });
|
||||
return () => controller.abort();
|
||||
}, [token, job.id, job.chat_binding_revision, reload]);
|
||||
const reviewing = draft !== null;
|
||||
const locked = saving || Boolean(job.state.pending);
|
||||
const pickerDisabled = locked || !data?.chats.length || loadError || (!reviewing && data.revision !== job.chat_binding_revision);
|
||||
useEffect(() => {
|
||||
if (reviewing) heading.current?.focus();
|
||||
}, [reviewing]);
|
||||
useEffect(() => {
|
||||
if (!reviewing && !pickerDisabled && returning.current) {
|
||||
trigger.current?.focus(); returning.current = false;
|
||||
}
|
||||
}, [reviewing, pickerDisabled]);
|
||||
const back = () => { returning.current = true; setDraft(null); };
|
||||
const current = data?.current;
|
||||
const fallback: AutomationChat = { id: "current", title: job.origin?.title || tx("current"), channel: job.origin?.channel || "websocket" };
|
||||
const baseTitle = (chat: AutomationChat) => chatNames?.get(chat.id)?.title ?? chat.title;
|
||||
const counts = new Map<string, number>();
|
||||
for (const chat of data?.chats ?? []) {
|
||||
const title = baseTitle(chat);
|
||||
counts.set(title, (counts.get(title) ?? 0) + 1);
|
||||
}
|
||||
const chatTitle = (chat: AutomationChat) => {
|
||||
const title = baseTitle(chat);
|
||||
const name = chatNames?.get(chat.id);
|
||||
return name && (counts.get(title) ?? 0) > 1 ? `${title} · @${name.handle}` : title;
|
||||
};
|
||||
const identity = (chat: AutomationChat) => <ChatIdentity chat={chat} title={chatTitle(chat)} />;
|
||||
const targetUnavailable = Boolean(draft && data && !data.chats.some(chat => chat.id === draft.target.id && !chat.unavailable));
|
||||
const picker = (review: boolean) => <Select value={review ? draft?.target.id : current?.id ?? "current"}
|
||||
disabled={pickerDisabled} onValueChange={id => {
|
||||
const target = data?.chats.find(chat => chat.id === id);
|
||||
if (!target || target.unavailable || id === current?.id) return;
|
||||
setError("");
|
||||
setDraft(previous => previous ? { ...previous, target } : {
|
||||
target, previous: current ?? fallback,
|
||||
revision: job.chat_binding_revision!, message: job.payload.message,
|
||||
});
|
||||
}}>
|
||||
<SelectTrigger ref={review ? undefined : trigger} aria-label={tx(review ? "new" : "label")}
|
||||
aria-busy={!loadError && (!data || data.revision !== job.chat_binding_revision)}
|
||||
className="h-auto min-h-14 w-full py-2 disabled:opacity-100 disabled:[&>svg]:opacity-40 [&>span:first-child]:min-w-0 [&>span:first-child]:flex-1 [&>span:first-child]:text-start">
|
||||
<SelectValue>{identity((review ? draft?.target : current) ?? fallback)}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{!current ? <SelectItem value="current" disabled>{identity(fallback)}</SelectItem> : null}
|
||||
{data?.chats.map(chat => <SelectItem key={chat.id} value={chat.id} textValue={`${chatTitle(chat)} ${chat.channel}`}
|
||||
disabled={chat.unavailable || (review && chat.id === current?.id)}
|
||||
className="h-auto min-h-11 py-2 [&>span:first-child]:min-w-0 [&>span:first-child]:max-w-[calc(100vw-5rem)] [&>span:first-child]:w-full">{identity(chat)}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>;
|
||||
const save = async () => {
|
||||
if (!draft || locked || targetUnavailable || !draft.message.trim()) return;
|
||||
setSaving(true); setError("");
|
||||
try {
|
||||
await onSave(job, { target_id: draft.target.id, revision: draft.revision, message: draft.message });
|
||||
setData(previous => previous ? { ...previous, current: draft.target } : previous);
|
||||
setSaved({ target: draft.target, previous: draft.previous }); back(); setReload(value => value + 1);
|
||||
} catch (cause) {
|
||||
const reasons: Record<string, string> = {
|
||||
automation_chat_conflict: "conflict", automation_chat_busy: "schedulerBusy",
|
||||
automation_chat_unavailable: "unavailable",
|
||||
};
|
||||
setError(tx(cause instanceof Error ? reasons[cause.message] ?? "failed" : "failed"));
|
||||
} finally { setSaving(false); }
|
||||
};
|
||||
if (!draft) return children(<div className="space-y-2">
|
||||
<p className="text-[13px] font-medium">{tx("label")}</p>
|
||||
{picker(false)}
|
||||
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
|
||||
<p role={saved ? "status" : undefined} className="text-[12px] leading-5 text-muted-foreground">
|
||||
{job.state.pending ? tx("busy") : saved ? tx("saved", { chat: chatTitle(saved.target) }) : tx("hint")}
|
||||
</p>
|
||||
{saved && current?.id === saved.target.id && data?.chats.some(chat => chat.id === saved.previous.id && !chat.unavailable) ? (
|
||||
<Button variant="link" size="sm" className="h-11 justify-start whitespace-normal p-0 text-start text-[12px] sm:h-auto" disabled={pickerDisabled}
|
||||
onClick={() => {
|
||||
setError("");
|
||||
setDraft({ target: saved.previous, previous: current, revision: data.revision, message: job.payload.message });
|
||||
}}>{tx("changeBack", { chat: chatTitle(saved.previous) })}</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{loadError ? <Button variant="link" size="sm" onClick={() => setReload(value => value + 1)}>{tx("retry")}</Button> : null}
|
||||
{data && data.chats.length <= (current ? 1 : 0) ? <p className="text-[12px] leading-5 text-muted-foreground">{tx("available")}</p> : null}
|
||||
</div>);
|
||||
return <>
|
||||
<DialogHeader className="shrink-0 px-6 pb-4 pr-12 pt-5 text-left">
|
||||
<DialogTitle ref={heading} tabIndex={-1} className="break-words text-lg font-medium leading-snug tracking-normal outline-none">{tx("change")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="min-h-0 space-y-4 overflow-y-auto overscroll-contain px-6 [text-wrap:pretty]">
|
||||
<div className="space-y-3">
|
||||
<div role="group" aria-label={tx("previous")} className="flex min-w-0 items-center gap-3 pb-1 text-muted-foreground">
|
||||
<span className="shrink-0 text-[12px]">{tx("previous")}</span>
|
||||
{identity(draft.previous)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<p className="text-[13px] font-medium">{tx("new")}</p>
|
||||
{picker(true)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-[13px] leading-5">{tx("effect")}</p>
|
||||
<p className="text-[12px] leading-5 text-muted-foreground">{tx("history")}</p>
|
||||
</div>
|
||||
<div className="space-y-2 rounded-2xl bg-muted/50 px-4 pb-4 pt-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<p className="text-[12px] text-muted-foreground">{tx("message")}</p>
|
||||
{!draft.editingMessage ? <Button variant="link" size="sm" disabled={saving}
|
||||
className="h-11 shrink-0 p-0 text-[12px] sm:h-9"
|
||||
onClick={() => setDraft({ ...draft, editingMessage: true })}>{tx("editInstructions")}</Button> : null}
|
||||
</div>
|
||||
{draft.editingMessage ? <>
|
||||
<Textarea autoFocus aria-label={tx("message")} rows={3} value={draft.message} disabled={saving}
|
||||
onChange={event => setDraft({ ...draft, message: event.target.value })}
|
||||
className="min-h-20 resize-y text-base leading-6 sm:text-[13px] sm:leading-5" />
|
||||
<p className="text-[12px] leading-5 text-muted-foreground">{tx("editInstructionsHint")}</p>
|
||||
</> : <p className="whitespace-pre-wrap break-words text-[13px] leading-5 [overflow-wrap:anywhere]">{draft.message}</p>}
|
||||
</div>
|
||||
<p className="text-[12px] leading-5 text-muted-foreground">{tx("review")}</p>
|
||||
{error || targetUnavailable ? <p role="alert" className="text-[12px] leading-5 text-destructive">{error || tx("unavailable")}</p> : null}
|
||||
</div>
|
||||
<DialogFooter className="mt-4 shrink-0 flex-row justify-end gap-2 border-t border-border/45 px-6 py-3">
|
||||
<Button variant="ghost" size="sm" disabled={saving} className="h-auto min-h-11 min-w-0 whitespace-normal font-normal text-muted-foreground sm:min-h-9" onClick={back}>{t("settings.automations.cancel")}</Button>
|
||||
<Button size="sm" className="grid h-auto min-h-11 min-w-0 whitespace-normal sm:min-h-9" disabled={locked || targetUnavailable || !draft.message.trim()} aria-busy={saving} onClick={() => void save()}>
|
||||
<span className="col-start-1 row-start-1" aria-hidden={saving || undefined} style={saving ? { visibility: "hidden" } : undefined}>{tx(draft.editingMessage ? "saveAndChange" : "confirm")}</span>
|
||||
<span className="col-start-1 row-start-1" aria-hidden={!saving || undefined} style={!saving ? { visibility: "hidden" } : undefined}>{tx("saving")}</span>
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>;
|
||||
return <AutomationChatBindingView job={job} data={data} loadError={loadError}
|
||||
chatNames={chatNames} showBrandLogos={readLocalPreferences().brandLogos} onSave={onSave}
|
||||
onReload={() => setReload(value => value + 1)} onSaved={target => {
|
||||
setData(previous => previous ? { ...previous, current: target } : previous);
|
||||
setReload(value => value + 1);
|
||||
}}>{children}</AutomationChatBindingView>;
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ChannelLogo } from "@/components/settings/channels/ChannelIdentity";
|
||||
import { channelUiOwner, channelUiPresentation } from "@/channel-plugins/registry";
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from "@/components/ui/select";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import type { AutomationChat, AutomationChatsPayload, AutomationChatUpdate, NanobotFeatureInfo, SessionAutomationJob } from "@/lib/types";
|
||||
|
||||
export type ChangeAutomationChat = (job: SessionAutomationJob, values: AutomationChatUpdate) => Promise<void>;
|
||||
export type AutomationChatNames = ReadonlyMap<string, { title: string; handle: string }>;
|
||||
|
||||
function ChatIdentity({ chat, title, showBrandLogos }: { chat: AutomationChat; title: string; showBrandLogos: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const owner = channelUiOwner(chat.channel);
|
||||
const presentation = channelUiPresentation(chat.channel);
|
||||
const platform = chat.channel === "websocket" ? t("settings.automations.chat.web")
|
||||
: channelTranslator(t, owner)("displayName", presentation?.displayName ?? chat.channel);
|
||||
const feature: NanobotFeatureInfo = {
|
||||
name: chat.channel, display_name: platform, type: "channel", enabled: true,
|
||||
installed: true, ready: true, status: "ready", install_supported: false, requires_restart: false,
|
||||
};
|
||||
return <span className="flex min-w-0 items-center gap-2.5 text-start">
|
||||
<span aria-hidden className="relative h-6 w-6 shrink-0">
|
||||
{chat.channel === "websocket" ? <img src="/brand/nanobot_mark.svg" alt="" className="h-6 w-6" />
|
||||
: <span className="absolute left-0 top-0 origin-top-left scale-75"><ChannelLogo feature={feature} showBrandLogos={showBrandLogos} /></span>}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-col gap-0.5">
|
||||
<span className="break-words text-sm leading-5 [overflow-wrap:anywhere]">{title}</span>
|
||||
<span className="text-xs leading-4 text-muted-foreground">{platform}</span>
|
||||
</span>
|
||||
</span>;
|
||||
}
|
||||
|
||||
export function AutomationChatBindingView({ job, data, loadError, chatNames, showBrandLogos, onSave, onSaved, onReload, children }: {
|
||||
job: SessionAutomationJob;
|
||||
data: AutomationChatsPayload | null;
|
||||
loadError: boolean;
|
||||
chatNames?: AutomationChatNames;
|
||||
showBrandLogos: boolean;
|
||||
onSave: ChangeAutomationChat;
|
||||
onSaved: (target: AutomationChat) => void;
|
||||
onReload: () => void;
|
||||
children: (picker: ReactNode) => ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tx = (key: string, values?: Record<string, string>) => t(`settings.automations.chat.${key}`, values);
|
||||
const [draft, setDraft] = useState<{ target: AutomationChat; previous: AutomationChat; revision: string; message: string; editingMessage?: boolean } | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [saved, setSaved] = useState<{ target: AutomationChat; previous: AutomationChat } | null>(null);
|
||||
const heading = useRef<HTMLHeadingElement>(null);
|
||||
const trigger = useRef<HTMLButtonElement>(null);
|
||||
const returning = useRef(false);
|
||||
useEffect(() => {
|
||||
if (data) setSaved(previous => previous?.target.id === data.current?.id ? previous : null);
|
||||
}, [data]);
|
||||
const reviewing = draft !== null;
|
||||
const locked = saving || Boolean(job.state.pending);
|
||||
const pickerDisabled = locked || !data?.chats.length || loadError || (!reviewing && data.revision !== job.chat_binding_revision);
|
||||
useEffect(() => {
|
||||
if (reviewing) heading.current?.focus();
|
||||
}, [reviewing]);
|
||||
useEffect(() => {
|
||||
if (!reviewing && !pickerDisabled && returning.current) {
|
||||
trigger.current?.focus(); returning.current = false;
|
||||
}
|
||||
}, [reviewing, pickerDisabled]);
|
||||
const back = () => { returning.current = true; setDraft(null); };
|
||||
const current = data?.current;
|
||||
const fallback: AutomationChat = { id: "current", title: job.origin?.title || tx("current"), channel: job.origin?.channel || "websocket" };
|
||||
const baseTitle = (chat: AutomationChat) => chatNames?.get(chat.id)?.title ?? chat.title;
|
||||
const counts = new Map<string, number>();
|
||||
for (const chat of data?.chats ?? []) {
|
||||
const title = baseTitle(chat);
|
||||
counts.set(title, (counts.get(title) ?? 0) + 1);
|
||||
}
|
||||
const chatTitle = (chat: AutomationChat) => {
|
||||
const title = baseTitle(chat);
|
||||
const name = chatNames?.get(chat.id);
|
||||
return name && (counts.get(title) ?? 0) > 1 ? `${title} · @${name.handle}` : title;
|
||||
};
|
||||
const identity = (chat: AutomationChat) => <ChatIdentity chat={chat} title={chatTitle(chat)} showBrandLogos={showBrandLogos} />;
|
||||
const targetUnavailable = Boolean(draft && data && !data.chats.some(chat => chat.id === draft.target.id && !chat.unavailable));
|
||||
const picker = (review: boolean) => <Select value={review ? draft?.target.id : current?.id ?? "current"}
|
||||
disabled={pickerDisabled} onValueChange={id => {
|
||||
const target = data?.chats.find(chat => chat.id === id);
|
||||
if (!target || target.unavailable || id === current?.id) return;
|
||||
setError("");
|
||||
setDraft(previous => previous ? { ...previous, target } : {
|
||||
target, previous: current ?? fallback,
|
||||
revision: job.chat_binding_revision!, message: job.payload.message,
|
||||
});
|
||||
}}>
|
||||
<SelectTrigger ref={review ? undefined : trigger} aria-label={tx(review ? "new" : "label")}
|
||||
aria-busy={!loadError && (!data || data.revision !== job.chat_binding_revision)}
|
||||
className="h-auto min-h-14 w-full py-2 disabled:opacity-100 disabled:[&>svg]:opacity-40 [&>span:first-child]:min-w-0 [&>span:first-child]:flex-1 [&>span:first-child]:text-start">
|
||||
<SelectValue>{identity((review ? draft?.target : current) ?? fallback)}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{!current ? <SelectItem value="current" disabled>{identity(fallback)}</SelectItem> : null}
|
||||
{data?.chats.map(chat => <SelectItem key={chat.id} value={chat.id} textValue={`${chatTitle(chat)} ${chat.channel}`}
|
||||
disabled={chat.unavailable || (review && chat.id === current?.id)}
|
||||
className="h-auto min-h-11 py-2 [&>span:first-child]:min-w-0 [&>span:first-child]:max-w-[calc(100vw-5rem)] [&>span:first-child]:w-full">{identity(chat)}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>;
|
||||
const save = async () => {
|
||||
if (!draft || locked || targetUnavailable || !draft.message.trim()) return;
|
||||
setSaving(true); setError("");
|
||||
try {
|
||||
await onSave(job, { target_id: draft.target.id, revision: draft.revision, message: draft.message });
|
||||
onSaved(draft.target);
|
||||
setSaved({ target: draft.target, previous: draft.previous }); back();
|
||||
} catch (cause) {
|
||||
const reasons: Record<string, string> = {
|
||||
automation_chat_conflict: "conflict", automation_chat_busy: "schedulerBusy",
|
||||
automation_chat_unavailable: "unavailable",
|
||||
};
|
||||
setError(tx(cause instanceof Error ? reasons[cause.message] ?? "failed" : "failed"));
|
||||
} finally { setSaving(false); }
|
||||
};
|
||||
if (!draft) return children(<div className="space-y-2">
|
||||
<p className="text-[13px] font-medium">{tx("label")}</p>
|
||||
{picker(false)}
|
||||
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
|
||||
<p role={saved ? "status" : undefined} className="text-[12px] leading-5 text-muted-foreground">
|
||||
{job.state.pending ? tx("busy") : saved ? tx("saved", { chat: chatTitle(saved.target) }) : tx("hint")}
|
||||
</p>
|
||||
{saved && current?.id === saved.target.id && data?.chats.some(chat => chat.id === saved.previous.id && !chat.unavailable) ? (
|
||||
<Button variant="link" size="sm" className="h-11 justify-start whitespace-normal p-0 text-start text-[12px] sm:h-auto" disabled={pickerDisabled}
|
||||
onClick={() => {
|
||||
setError("");
|
||||
setDraft({ target: saved.previous, previous: current, revision: data.revision, message: job.payload.message });
|
||||
}}>{tx("changeBack", { chat: chatTitle(saved.previous) })}</Button>
|
||||
) : null}
|
||||
</div>
|
||||
{loadError ? <Button variant="link" size="sm" onClick={onReload}>{tx("retry")}</Button> : null}
|
||||
{data && data.chats.length <= (current ? 1 : 0) ? <p className="text-[12px] leading-5 text-muted-foreground">{tx("available")}</p> : null}
|
||||
</div>);
|
||||
return <>
|
||||
<DialogHeader className="shrink-0 px-6 pb-4 pr-12 pt-5 text-left">
|
||||
<DialogTitle ref={heading} tabIndex={-1} className="break-words text-lg font-medium leading-snug tracking-normal outline-none">{tx("change")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="min-h-0 space-y-4 overflow-y-auto overscroll-contain px-6 [text-wrap:pretty]">
|
||||
<div className="space-y-3">
|
||||
<div role="group" aria-label={tx("previous")} className="flex min-w-0 items-center gap-3 pb-1 text-muted-foreground">
|
||||
<span className="shrink-0 text-[12px]">{tx("previous")}</span>
|
||||
{identity(draft.previous)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<p className="text-[13px] font-medium">{tx("new")}</p>
|
||||
{picker(true)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-[13px] leading-5">{tx("effect")}</p>
|
||||
<p className="text-[12px] leading-5 text-muted-foreground">{tx("history")}</p>
|
||||
</div>
|
||||
<div className="space-y-2 rounded-2xl bg-muted/50 px-4 pb-4 pt-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<p className="text-[12px] text-muted-foreground">{tx("message")}</p>
|
||||
{!draft.editingMessage ? <Button variant="link" size="sm" disabled={saving}
|
||||
className="h-11 shrink-0 p-0 text-[12px] sm:h-9"
|
||||
onClick={() => setDraft({ ...draft, editingMessage: true })}>{tx("editInstructions")}</Button> : null}
|
||||
</div>
|
||||
{draft.editingMessage ? <>
|
||||
<Textarea autoFocus aria-label={tx("message")} rows={3} value={draft.message} disabled={saving}
|
||||
onChange={event => setDraft({ ...draft, message: event.target.value })}
|
||||
className="min-h-20 resize-y text-base leading-6 sm:text-[13px] sm:leading-5" />
|
||||
<p className="text-[12px] leading-5 text-muted-foreground">{tx("editInstructionsHint")}</p>
|
||||
</> : <p className="whitespace-pre-wrap break-words text-[13px] leading-5 [overflow-wrap:anywhere]">{draft.message}</p>}
|
||||
</div>
|
||||
<p className="text-[12px] leading-5 text-muted-foreground">{tx("review")}</p>
|
||||
{error || targetUnavailable ? <p role="alert" className="text-[12px] leading-5 text-destructive">{error || tx("unavailable")}</p> : null}
|
||||
</div>
|
||||
<DialogFooter className="mt-4 shrink-0 flex-row justify-end gap-2 border-t border-border/45 px-6 py-3">
|
||||
<Button variant="ghost" size="sm" disabled={saving} className="h-auto min-h-11 min-w-0 whitespace-normal font-normal text-muted-foreground sm:min-h-9" onClick={back}>{t("settings.automations.cancel")}</Button>
|
||||
<Button size="sm" className="grid h-auto min-h-11 min-w-0 whitespace-normal sm:min-h-9" disabled={locked || targetUnavailable || !draft.message.trim()} aria-busy={saving} onClick={() => void save()}>
|
||||
<span className="col-start-1 row-start-1" aria-hidden={saving || undefined} style={saving ? { visibility: "hidden" } : undefined}>{tx(draft.editingMessage ? "saveAndChange" : "confirm")}</span>
|
||||
<span className="col-start-1 row-start-1" aria-hidden={!saving || undefined} style={!saving ? { visibility: "hidden" } : undefined}>{tx("saving")}</span>
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>;
|
||||
}
|
||||
@@ -1,15 +1,10 @@
|
||||
import { CircleAlert } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { MarkdownText } from "@/components/MarkdownText";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import type { SessionAutomationJob } from "@/lib/types";
|
||||
import { AutomationRunDialogView, type AutomationRunRecord } from "./AutomationRunDialogView";
|
||||
import { fetchAutomationRunResult } from "@/lib/api";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { SessionAutomationJob } from "@/lib/types";
|
||||
|
||||
export type AutomationRunRecord = NonNullable<SessionAutomationJob["state"]["run_history"]>[number];
|
||||
export type { AutomationRunRecord } from "./AutomationRunDialogView";
|
||||
|
||||
export function AutomationRunDialog({ token = "", job, run, locale, open, onOpenChange, onCloseAutoFocus }: {
|
||||
token?: string;
|
||||
@@ -20,7 +15,6 @@ export function AutomationRunDialog({ token = "", job, run, locale, open, onOpen
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCloseAutoFocus: (event: Event) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const kind = job.kind === "local_trigger" ? "local_trigger" : "cron";
|
||||
const resultKey = JSON.stringify([token, kind, job.id, run.run_at_ms, attempt]);
|
||||
@@ -49,79 +43,8 @@ export function AutomationRunDialog({ token = "", job, run, locale, open, onOpen
|
||||
return () => controller.abort();
|
||||
}, [job.id, kind, open, resultKey, run.run_at_ms, token]);
|
||||
const currentResult = result?.key === resultKey ? result : null;
|
||||
const failed = run.status === "error";
|
||||
const status = run.status === "ok"
|
||||
? t("settings.automations.status.completed")
|
||||
: failed ? t("settings.automations.status.failed")
|
||||
: run.status === "skipped" ? t("settings.automations.skipped")
|
||||
: t("settings.automations.calendar.recorded");
|
||||
const duration = run.duration_ms;
|
||||
const chatKey = run.webui_session_key !== undefined ? run.webui_session_key
|
||||
: job.origin?.channel === "websocket" ? job.origin.session_key : null;
|
||||
const chatHref = chatKey ? `#/chat/${encodeURIComponent(chatKey)}` : null;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
{...(!open ? { inert: "", "aria-hidden": true } : {})}
|
||||
className="flex max-h-[calc(100dvh-2rem)] max-w-[520px] flex-col gap-0 p-0 text-sm font-normal leading-normal text-foreground"
|
||||
onCloseAutoFocus={onCloseAutoFocus}
|
||||
>
|
||||
<DialogHeader className="shrink-0 px-6 pb-4 pr-14 pt-5 text-left">
|
||||
<DialogTitle className="min-w-0 break-words text-lg font-medium leading-snug tracking-normal text-balance">
|
||||
{job.name || job.id}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-sm font-normal text-muted-foreground">
|
||||
<time dateTime={new Date(run.run_at_ms).toISOString()}>
|
||||
{new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short" }).format(run.run_at_ms)}
|
||||
</time>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="min-h-0 space-y-4 overflow-y-auto overscroll-contain px-6 pb-6">
|
||||
<dl className="space-y-3">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<dt className="text-muted-foreground">{t("settings.automations.runDetails.result")}</dt>
|
||||
<dd className={cn("flex items-center gap-1.5 text-end", failed && "text-destructive")}>
|
||||
{failed ? <CircleAlert className="h-3.5 w-3.5 shrink-0" strokeWidth={1.5} aria-hidden /> : null}
|
||||
{status}
|
||||
</dd>
|
||||
</div>
|
||||
{duration != null && Number.isFinite(duration) && duration >= 0 ? (
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<dt className="text-muted-foreground">{t("settings.automations.runDetails.duration")}</dt>
|
||||
<dd className="text-end tabular-nums">{new Intl.NumberFormat(locale, {
|
||||
style: "unit", unit: "second", unitDisplay: "short",
|
||||
maximumFractionDigits: duration < 1000 ? 3 : 1,
|
||||
}).format(duration / 1000)}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
</dl>
|
||||
{run.error ? <p className={cn("whitespace-pre-wrap break-words [overflow-wrap:anywhere]", failed && "text-destructive")}>{run.error}</p> : null}
|
||||
{!currentResult || currentResult.status === "loading" ? (
|
||||
<p role="status" className="text-muted-foreground">{t("settings.automations.runDetails.loading")}</p>
|
||||
) : currentResult.status === "error" ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<p role="alert" className="text-muted-foreground">{t("settings.automations.runDetails.loadError")}</p>
|
||||
<Button variant="ghost" size="sm" onClick={() => setAttempt((value) => value + 1)}>
|
||||
{t("settings.automations.runDetails.retry")}
|
||||
</Button>
|
||||
</div>
|
||||
) : currentResult.response?.trim() ? (
|
||||
<MarkdownText className="min-w-0 text-sm [overflow-wrap:anywhere]">{currentResult.response}</MarkdownText>
|
||||
) : (
|
||||
<p className="text-muted-foreground">{t(currentResult.response === null
|
||||
? "settings.automations.runDetails.noOutput"
|
||||
: "settings.automations.runDetails.emptyOutput")}</p>
|
||||
)}
|
||||
</div>
|
||||
{chatHref ? (
|
||||
<div className="flex shrink-0 justify-end border-t border-border/45 px-6 py-3">
|
||||
<Button asChild variant="ghost" size="sm" className="font-normal text-muted-foreground">
|
||||
<a href={chatHref}>{t("settings.automations.emptyAction")}</a>
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
return <AutomationRunDialogView job={job} run={run} locale={locale} open={open}
|
||||
result={currentResult ?? { status: "loading", response: null }}
|
||||
onRetry={() => setAttempt((value) => value + 1)}
|
||||
onOpenChange={onOpenChange} onCloseAutoFocus={onCloseAutoFocus} />;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { CircleAlert } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { MarkdownText } from "@/components/MarkdownText";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import type { SessionAutomationJob } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type AutomationRunRecord = NonNullable<SessionAutomationJob["state"]["run_history"]>[number];
|
||||
export type AutomationRunResult = {
|
||||
status: "loading" | "loaded" | "error";
|
||||
response: string | null;
|
||||
};
|
||||
|
||||
export function AutomationRunDialogView({ job, run, locale, open, result, onRetry, onOpenChange, onCloseAutoFocus }: {
|
||||
job: SessionAutomationJob;
|
||||
run: AutomationRunRecord;
|
||||
locale: string;
|
||||
open: boolean;
|
||||
result: AutomationRunResult;
|
||||
onRetry: () => void;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCloseAutoFocus: (event: Event) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const failed = run.status === "error";
|
||||
const status = run.status === "ok"
|
||||
? t("settings.automations.status.completed")
|
||||
: failed ? t("settings.automations.status.failed")
|
||||
: run.status === "skipped" ? t("settings.automations.skipped")
|
||||
: t("settings.automations.calendar.recorded");
|
||||
const duration = run.duration_ms;
|
||||
const chatKey = run.webui_session_key !== undefined ? run.webui_session_key
|
||||
: job.origin?.channel === "websocket" ? job.origin.session_key : null;
|
||||
const chatHref = chatKey ? `#/chat/${encodeURIComponent(chatKey)}` : null;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
{...(!open ? { inert: "", "aria-hidden": true } : {})}
|
||||
className="flex max-h-[calc(100dvh-2rem)] max-w-[520px] flex-col gap-0 p-0 text-sm font-normal leading-normal text-foreground"
|
||||
onCloseAutoFocus={onCloseAutoFocus}
|
||||
>
|
||||
<DialogHeader className="shrink-0 px-6 pb-4 pr-14 pt-5 text-left">
|
||||
<DialogTitle className="min-w-0 break-words text-lg font-medium leading-snug tracking-normal text-balance">
|
||||
{job.name || job.id}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-sm font-normal text-muted-foreground">
|
||||
<time dateTime={new Date(run.run_at_ms).toISOString()}>
|
||||
{new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short" }).format(run.run_at_ms)}
|
||||
</time>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="min-h-0 space-y-4 overflow-y-auto overscroll-contain px-6 pb-6">
|
||||
<dl className="space-y-3">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<dt className="text-muted-foreground">{t("settings.automations.runDetails.result")}</dt>
|
||||
<dd className={cn("flex items-center gap-1.5 text-end", failed && "text-destructive")}>
|
||||
{failed ? <CircleAlert className="h-3.5 w-3.5 shrink-0" strokeWidth={1.5} aria-hidden /> : null}
|
||||
{status}
|
||||
</dd>
|
||||
</div>
|
||||
{duration != null && Number.isFinite(duration) && duration >= 0 ? (
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<dt className="text-muted-foreground">{t("settings.automations.runDetails.duration")}</dt>
|
||||
<dd className="text-end tabular-nums">{new Intl.NumberFormat(locale, {
|
||||
style: "unit", unit: "second", unitDisplay: "short",
|
||||
maximumFractionDigits: duration < 1000 ? 3 : 1,
|
||||
}).format(duration / 1000)}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
</dl>
|
||||
{run.error ? <p className={cn("whitespace-pre-wrap break-words [overflow-wrap:anywhere]", failed && "text-destructive")}>{run.error}</p> : null}
|
||||
{result.status === "loading" ? (
|
||||
<p role="status" className="text-muted-foreground">{t("settings.automations.runDetails.loading")}</p>
|
||||
) : result.status === "error" ? (
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<p role="alert" className="text-muted-foreground">{t("settings.automations.runDetails.loadError")}</p>
|
||||
<Button variant="ghost" size="sm" onClick={onRetry}>
|
||||
{t("settings.automations.runDetails.retry")}
|
||||
</Button>
|
||||
</div>
|
||||
) : result.response?.trim() ? (
|
||||
<MarkdownText className="min-w-0 text-sm [overflow-wrap:anywhere]">{result.response}</MarkdownText>
|
||||
) : (
|
||||
<p className="text-muted-foreground">{t(result.response === null
|
||||
? "settings.automations.runDetails.noOutput"
|
||||
: "settings.automations.runDetails.emptyOutput")}</p>
|
||||
)}
|
||||
</div>
|
||||
{chatHref ? (
|
||||
<div className="flex shrink-0 justify-end border-t border-border/45 px-6 py-3">
|
||||
<Button asChild variant="ghost" size="sm" className="font-normal text-muted-foreground">
|
||||
<a href={chatHref}>{t("settings.automations.emptyAction")}</a>
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { channelTranslator } from "@/channel-plugins/i18n";
|
||||
import { channelUiOwner, channelUiPresentation } from "@/channel-plugins/registry";
|
||||
import { AutomationCalendar } from "@/components/settings/system/AutomationCalendar";
|
||||
import { AutomationRunDialog } from "@/components/settings/system/AutomationRunDialog";
|
||||
import { AutomationChatBinding, type AutomationChatNames, type ChangeAutomationChat } from "@/components/settings/system/AutomationChatBinding";
|
||||
import { AutomationRunAtPicker, parseAutomationRunAt } from "@/components/settings/system/AutomationRunAtPicker";
|
||||
import {
|
||||
@@ -349,7 +350,7 @@ export function AutomationsSettings({
|
||||
</section>
|
||||
) : (
|
||||
<AutomationCalendar
|
||||
token={token}
|
||||
renderRunDialog={(props) => <AutomationRunDialog token={token} {...props} />}
|
||||
jobs={filtered}
|
||||
month={month}
|
||||
locale={locale}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { ToggleButton } from "@/components/ui/toggle-button";
|
||||
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";
|
||||
|
||||
Reference in new issue
Block a user