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:
chengyongru authored and GitHub committed 2026-10-14 00:11:00 +08:00
1 parent db804ef94a
commit 30e43aec82
109 files changed
+7874 -3459

No files matched your search

+1 -7
View File
@@ -1,8 +1,6 @@
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider";
import type { ConnectionStatus } from "@/lib/types";
const COPY: Record<ConnectionStatus, { color: string }> = {
@@ -24,12 +22,8 @@ const COPY: Record<ConnectionStatus, { color: string }> = {
},
};
export function ConnectionBadge() {
export function ConnectionBadge({ status }: { status: ConnectionStatus }) {
const { t } = useTranslation();
const { client } = useClient();
const [status, setStatus] = useState<ConnectionStatus>(client.status);
useEffect(() => client.onStatus(setStatus), [client]);
const meta = COPY[status];
const pulsing =
+12 -90
View File
@@ -1,10 +1,5 @@
import { useEffect, useRef, useState } from "react";
import { AlertCircle } from "lucide-react";
import { useTranslation } from "react-i18next";
import { CodeBlock } from "@/components/CodeBlock";
import { ImageLightbox } from "@/components/ImageLightbox";
import { fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";
import { useCallback, useEffect, useRef, useState } from "react";
import { FilePreviewPanelView, type FilePreviewPanelState } from "@/components/FilePreviewPanelView";
import { ApiError, fetchFilePreview } from "@/lib/api";
import type { FilePreviewPayload } from "@/lib/types";
@@ -16,11 +11,6 @@ interface FilePreviewPanelProps {
initialPreview?: FilePreviewPayload;
}
type PreviewState =
| { status: "loading" }
| { status: "error"; error: unknown }
| { status: "ready"; payload: FilePreviewPayload };
export function FilePreviewPanel({
sessionKey,
path,
@@ -28,8 +18,7 @@ export function FilePreviewPanel({
loadPreview,
initialPreview,
}: FilePreviewPanelProps) {
const { t } = useTranslation();
const [state, setState] = useState<PreviewState>(() => initialPreview
const [state, setState] = useState<FilePreviewPanelState>(() => initialPreview
? { status: "ready", payload: initialPreview } : { status: "loading" });
const [imageOpen, setImageOpen] = useState(false);
// Cache aging must not restart an already open preview on unrelated rerenders.
@@ -53,86 +42,19 @@ export function FilePreviewPanel({
? previous : { status: "ready", payload });
})
.catch((error: unknown) => {
if (!cancelled) setState({ status: "error", error });
if (!cancelled) setState({ status: "error",
...(error instanceof ApiError ? {
message: error.message,
routeMissing: error.status === 404 && /API route not found/i.test(error.message),
} : {}),
});
});
return () => {
cancelled = true;
};
}, [path, sessionKey, loadPreview]);
const displayPath = state.status === "ready" ? state.payload.display_path : path;
const { name } = splitFilePath(displayPath);
const fileName = name || displayPath;
const errorMessage = state.status === "error"
? (state.error instanceof ApiError
? (state.error.status === 404 && /API route not found/i.test(state.error.message)
? t("filePreview.routeMissing", {
defaultValue: "File preview needs the latest gateway. Restart nanobot gateway and try again.",
})
: state.error.message)
: t("filePreview.failed", { defaultValue: "Could not preview this file." }))
: null;
return (
<section aria-label={t("filePreview.aria")} data-testid="file-preview-panel" className="flex min-h-0 flex-1 flex-col">
<div data-file-preview-scroll tabIndex={0}
className="min-h-0 flex-1 overflow-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60">
{state.status === "loading" ? (
<div role="status" aria-label={t("filePreview.loading", { defaultValue: "Loading preview..." })}
className="flex h-full flex-col justify-center gap-3 p-6" aria-busy="true">
<span className="sr-only">{t("filePreview.loading", { defaultValue: "Loading preview..." })}</span>
<div aria-hidden className="mx-auto w-full max-w-sm space-y-3 animate-pulse [animation-duration:900ms] motion-reduce:animate-none">
{fileKindForPath(path) === "image" ? <div className="aspect-[8/5] rounded-compact bg-muted/40" />
: <>{["w-2/3", "w-full", "w-5/6", "w-3/4"].map((width) =>
<div key={width} className={`h-1.5 rounded-full bg-muted/40 ${width}`} />)}</>}
</div>
</div>
) : state.status === "error" ? (
<div className="flex h-full items-center justify-center px-8 text-center text-sm text-muted-foreground">
<div className="max-w-sm">
<AlertCircle
className="mx-auto mb-3 h-5 w-5 text-muted-foreground/70"
aria-hidden
/>
<p>{errorMessage}</p>
</div>
</div>
) : state.payload.kind === "image" ? (
<div className="flex min-h-full items-center justify-center p-4">
<button type="button" aria-label={`${t("lightbox.open")}: ${fileName}`} onClick={() => setImageOpen(true)}
className="flex max-h-full max-w-full cursor-zoom-in items-center justify-center rounded-compact focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<img
src={state.payload.data_url}
alt={fileName}
className="max-h-full max-w-full object-contain"
onError={() => setState({ status: "error", error: new Error("Invalid image") })}
/>
</button>
<ImageLightbox images={[{ url: state.payload.data_url, name: fileName }]} index={imageOpen ? 0 : null}
onIndexChange={() => {}} onOpenChange={setImageOpen} />
</div>
) : (
<div className="min-h-full">
{state.payload.truncated ? (
<div className="mx-4 mt-3 rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-200">
{t("filePreview.truncated", {
defaultValue: "Preview is truncated because this file is large.",
})}
</div>
) : null}
<CodeBlock
language={state.payload.language}
code={state.payload.content}
chrome="none"
highlight
showLineNumbers
wrapLongLines={false}
viewportHighlight
className="min-h-full"
/>
</div>
)}
</div>
</section>
);
const reportImageError = useCallback(() => setState({ status: "error" }), []);
return <FilePreviewPanelView path={path} state={state} imageOpen={imageOpen}
onImageOpenChange={setImageOpen} onImageError={reportImageError} />;
}
@@ -0,0 +1,95 @@
import { useTranslation } from "react-i18next";
import { AlertCircle } from "lucide-react";
import { CodeBlock } from "@/components/CodeBlock";
import { ImageLightbox } from "@/components/ImageLightbox";
import { fileKindForPath, splitFilePath } from "@/components/FileReferenceChip";
import type { FilePreviewPayload } from "@/lib/types";
export type FilePreviewPanelState =
| { status: "loading" }
| { status: "error"; message?: string; routeMissing?: boolean }
| { status: "ready"; payload: FilePreviewPayload };
export function FilePreviewPanelView({ path, state, imageOpen, onImageOpenChange, onImageError }: {
path: string;
state: FilePreviewPanelState;
imageOpen: boolean;
onImageOpenChange: (open: boolean) => void;
onImageError: () => void;
}) {
const { t } = useTranslation();
const displayPath = state.status === "ready" ? state.payload.display_path : path;
const { name } = splitFilePath(displayPath);
const fileName = name || displayPath;
const errorMessage = state.status === "error"
? (state.routeMissing
? t("filePreview.routeMissing", {
defaultValue: "File preview needs the latest gateway. Restart nanobot gateway and try again.",
})
: state.message ?? t("filePreview.failed", { defaultValue: "Could not preview this file." }))
: null;
return (
<section aria-label={t("filePreview.aria")} data-testid="file-preview-panel" className="flex min-h-0 flex-1 flex-col">
<div data-file-preview-scroll tabIndex={0}
className="min-h-0 flex-1 overflow-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60">
{state.status === "loading" ? (
<div role="status" aria-label={t("filePreview.loading", { defaultValue: "Loading preview..." })}
className="flex h-full flex-col justify-center gap-3 p-6" aria-busy="true">
<span className="sr-only">{t("filePreview.loading", { defaultValue: "Loading preview..." })}</span>
<div aria-hidden className="mx-auto w-full max-w-sm space-y-3 animate-pulse [animation-duration:900ms] motion-reduce:animate-none">
{fileKindForPath(path) === "image" ? <div className="aspect-[8/5] rounded-compact bg-muted/40" />
: <>{["w-2/3", "w-full", "w-5/6", "w-3/4"].map((width) =>
<div key={width} className={`h-1.5 rounded-full bg-muted/40 ${width}`} />)}</>}
</div>
</div>
) : state.status === "error" ? (
<div className="flex h-full items-center justify-center px-8 text-center text-sm text-muted-foreground">
<div className="max-w-sm">
<AlertCircle
className="mx-auto mb-3 h-5 w-5 text-muted-foreground/70"
aria-hidden
/>
<p>{errorMessage}</p>
</div>
</div>
) : state.payload.kind === "image" ? (
<div className="flex min-h-full items-center justify-center p-4">
<button type="button" aria-label={`${t("lightbox.open")}: ${fileName}`} onClick={() => onImageOpenChange(true)}
className="flex max-h-full max-w-full cursor-zoom-in items-center justify-center rounded-compact focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<img
src={state.payload.data_url}
alt={fileName}
className="max-h-full max-w-full object-contain"
onError={onImageError}
/>
</button>
<ImageLightbox images={[{ url: state.payload.data_url, name: fileName }]} index={imageOpen ? 0 : null}
onIndexChange={() => {}} onOpenChange={onImageOpenChange} />
</div>
) : (
<div className="min-h-full">
{state.payload.truncated ? (
<div className="mx-4 mt-3 rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-200">
{t("filePreview.truncated", {
defaultValue: "Preview is truncated because this file is large.",
})}
</div>
) : null}
<CodeBlock
language={state.payload.language}
code={state.payload.content}
chrome="none"
highlight
showLineNumbers
wrapLongLines={false}
viewportHighlight
className="min-h-full"
/>
</div>
)}
</div>
</section>
);
}
+13 -79
View File
@@ -1,64 +1,31 @@
import { useEffect, useRef, useState } from "react";
import { ExternalLink, Sparkle, Star, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import starInvitation from "@/assets/star-invitation.webp";
import { Button } from "@/components/ui/button";
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
import { StarLinkView, StarPromptView } from "@/components/StarPromptView";
import { starPromptAction } from "@/lib/api";
import { useClient } from "@/providers/ClientProvider";
import "./StarPrompt.css";
const REPOSITORY_URL = "https://github.com/HKUDS/nanobot";
const actionClassName = "h-full min-h-[46px] min-w-0 !whitespace-normal px-3 py-2.5 text-center text-[15px] font-medium max-[480px]:text-sm";
export function StarLink({ onSaved, fullWidth = false }: {
onSaved?: () => void;
fullWidth?: boolean;
}) {
const { client } = useClient();
const { t } = useTranslation();
const [error, setError] = useState(false);
const dismiss = () => {
setError(false);
void starPromptAction(client, "dismiss").then(onSaved).catch(() => setError(true));
};
const link = (
<a href={REPOSITORY_URL} target="_blank" rel="noopener noreferrer"
className={fullWidth ? undefined : "inline-flex min-h-10 items-center justify-center gap-2 rounded-control px-2 text-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}
onClick={dismiss} onAuxClick={(event) => { if (event.button === 1) dismiss(); }}>
{!fullWidth && <Star className="h-4 w-4 shrink-0" aria-hidden />}
<span className="min-w-0">
{t(fullWidth ? "starPrompt.action" : "starPrompt.footerAction")}
</span>
{fullWidth ? (
<span className="star-prompt-decoration" aria-hidden="true">
<Star className="star-prompt-star" size={23} strokeWidth={1.5} fill="currentColor" />
<Sparkle className="star-prompt-sparkle star-prompt-sparkle-first" size={10} strokeWidth={1.5} fill="currentColor" />
<Sparkle className="star-prompt-sparkle star-prompt-sparkle-second" size={7} strokeWidth={1.5} fill="currentColor" />
</span>
) : <ExternalLink className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />}
</a>
);
return (
<>
{fullWidth ? <Button asChild className={`star-prompt-action relative isolate w-full overflow-visible ${actionClassName}`}>{link}</Button> : link}
{error && <p role="alert" className="text-sm text-destructive">{t("starPrompt.saveError")}</p>}
</>
);
return <StarLinkView fullWidth={fullWidth} error={error} onActivate={dismiss} />;
}
export function StarPrompt({ ready }: { ready: boolean }) {
const { client } = useClient();
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState(false);
const attempted = useRef(false);
const interacted = useRef(false);
const previousFocus = useRef<HTMLElement | null>(null);
const titleRef = useRef<HTMLHeadingElement | null>(null);
const [starError, setStarError] = useState(false);
useEffect(() => {
const cancel = () => { interacted.current = true; };
@@ -101,47 +68,14 @@ export function StarPrompt({ ready }: { ready: boolean }) {
}
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent showCloseButton={false}
className="flex max-h-[calc(100dvh-32px)] max-w-[520px] flex-col gap-0 overflow-y-auto overscroll-contain p-5 pb-2.5 outline-none max-[480px]:p-4 max-[480px]:pb-2"
onOpenAutoFocus={(event) => {
event.preventDefault();
titleRef.current?.focus({ preventScroll: true });
}} onCloseAutoFocus={(event) => {
event.preventDefault();
previousFocus.current?.focus({ preventScroll: true });
}}>
<img src={starInvitation} alt="" width={1672} height={941} draggable={false}
className="aspect-[1672/941] w-full shrink-0 select-none rounded-control bg-muted object-cover" />
<DialogClose aria-label={t("common.close")}
className="absolute right-[23px] top-[23px] grid h-11 w-11 place-items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-white max-[480px]:right-[18px] max-[480px]:top-[18px]">
<span className="grid h-[30px] w-[30px] place-items-center rounded-full bg-black/40 text-white backdrop-blur-sm transition-colors hover:bg-black/60 motion-reduce:transition-none">
<X size={18} strokeWidth={1.75} aria-hidden />
</span>
</DialogClose>
<div className="shrink-0 px-2 pt-[27px] text-left max-[480px]:px-1 max-[480px]:pt-[23px]">
<DialogTitle ref={titleRef} tabIndex={-1}
className="text-[26px] font-semibold leading-[1.4] tracking-[-0.035em] outline-none [overflow-wrap:anywhere] max-[480px]:text-[clamp(18px,5.6vw,24px)]">
{t("starPrompt.title")}
</DialogTitle>
<DialogDescription className="mt-[15px] text-[15px] leading-[1.9] text-muted-foreground max-[480px]:mt-3 max-[480px]:text-[13px] max-[480px]:leading-[1.95]">
<span className="block">{t("starPrompt.intro")}</span>{" "}
<span className="block">{t("starPrompt.invitation")}</span>{" "}
<span className="block">{t("starPrompt.thanks")}</span>
</DialogDescription>
</div>
<div className="mt-[27px] grid shrink-0 grid-cols-2 items-stretch gap-3 px-2 max-[480px]:mt-[23px] max-[480px]:gap-2.5 max-[480px]:px-1">
<Button variant="outline" className={actionClassName}
onClick={() => setOpen(false)}>{t("starPrompt.later")}</Button>
<div className="flex min-w-0 flex-col gap-2">
<StarLink fullWidth onSaved={() => setOpen(false)} />
</div>
</div>
<Button variant="ghost" className="mt-[7px] min-h-11 shrink-0 self-center !whitespace-normal px-4 text-xs font-normal text-muted-foreground" disabled={saving}
onClick={() => void dismissForever()}>{t("starPrompt.never")}</Button>
{error && <p role="alert" className="text-sm text-destructive">{t("starPrompt.saveError")}</p>}
</DialogContent>
</Dialog>
);
const openRepository = () => {
setStarError(false);
void starPromptAction(client, "dismiss").then(() => setOpen(false)).catch(() => setStarError(true));
};
return <StarPromptView open={open} saving={saving} error={error} starError={starError}
onOpenChange={setOpen} onDismissForever={() => void dismissForever()} onStar={openRepository}
onCloseAutoFocus={event => {
event.preventDefault();
previousFocus.current?.focus({ preventScroll: true });
}} />;
}
+97
View File
@@ -0,0 +1,97 @@
import { useRef } from "react";
import { ExternalLink, Sparkle, Star, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import starInvitation from "@/assets/star-invitation.webp";
import { Button } from "@/components/ui/button";
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog";
import "./StarPrompt.css";
const REPOSITORY_URL = "https://github.com/HKUDS/nanobot";
const actionClassName = "h-full min-h-[46px] min-w-0 !whitespace-normal px-3 py-2.5 text-center text-[15px] font-medium max-[480px]:text-sm";
export function StarLinkView({ onActivate, error = false, fullWidth = false }: {
onActivate: () => void;
error?: boolean;
fullWidth?: boolean;
}) {
const { t } = useTranslation();
const link = (
<a href={REPOSITORY_URL} target="_blank" rel="noopener noreferrer"
className={fullWidth ? undefined : "inline-flex min-h-10 items-center justify-center gap-2 rounded-control px-2 text-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}
onClick={onActivate} onAuxClick={(event) => { if (event.button === 1) onActivate(); }}>
{!fullWidth && <Star className="h-4 w-4 shrink-0" aria-hidden />}
<span className="min-w-0">
{t(fullWidth ? "starPrompt.action" : "starPrompt.footerAction")}
</span>
{fullWidth ? (
<span className="star-prompt-decoration" aria-hidden="true">
<Star className="star-prompt-star" size={23} strokeWidth={1.5} fill="currentColor" />
<Sparkle className="star-prompt-sparkle star-prompt-sparkle-first" size={10} strokeWidth={1.5} fill="currentColor" />
<Sparkle className="star-prompt-sparkle star-prompt-sparkle-second" size={7} strokeWidth={1.5} fill="currentColor" />
</span>
) : <ExternalLink className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />}
</a>
);
return (
<>
{fullWidth ? <Button asChild className={`star-prompt-action relative isolate w-full overflow-visible ${actionClassName}`}>{link}</Button> : link}
{error && <p role="alert" className="text-sm text-destructive">{t("starPrompt.saveError")}</p>}
</>
);
}
export function StarPromptView({ open, saving, error, starError = false, onOpenChange, onDismissForever, onStar, onCloseAutoFocus }: {
open: boolean;
saving: boolean;
error: boolean;
starError?: boolean;
onOpenChange: (open: boolean) => void;
onDismissForever: () => void;
onStar: () => void;
onCloseAutoFocus?: (event: Event) => void;
}) {
const { t } = useTranslation();
const titleRef = useRef<HTMLHeadingElement | null>(null);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent showCloseButton={false}
className="flex max-h-[calc(100dvh-32px)] max-w-[520px] flex-col gap-0 overflow-y-auto overscroll-contain p-5 pb-2.5 outline-none max-[480px]:p-4 max-[480px]:pb-2"
onOpenAutoFocus={(event) => {
event.preventDefault();
titleRef.current?.focus({ preventScroll: true });
}} onCloseAutoFocus={onCloseAutoFocus}>
<img src={starInvitation} alt="" width={1672} height={941} draggable={false}
className="aspect-[1672/941] w-full shrink-0 select-none rounded-control bg-muted object-cover" />
<DialogClose aria-label={t("common.close")}
className="absolute right-[23px] top-[23px] grid h-11 w-11 place-items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-white max-[480px]:right-[18px] max-[480px]:top-[18px]">
<span className="grid h-[30px] w-[30px] place-items-center rounded-full bg-black/40 text-white backdrop-blur-sm transition-colors hover:bg-black/60 motion-reduce:transition-none">
<X size={18} strokeWidth={1.75} aria-hidden />
</span>
</DialogClose>
<div className="shrink-0 px-2 pt-[27px] text-left max-[480px]:px-1 max-[480px]:pt-[23px]">
<DialogTitle ref={titleRef} tabIndex={-1}
className="text-[26px] font-semibold leading-[1.4] tracking-[-0.035em] outline-none [overflow-wrap:anywhere] max-[480px]:text-[clamp(18px,5.6vw,24px)]">
{t("starPrompt.title")}
</DialogTitle>
<DialogDescription className="mt-[15px] text-[15px] leading-[1.9] text-muted-foreground max-[480px]:mt-3 max-[480px]:text-[13px] max-[480px]:leading-[1.95]">
<span className="block">{t("starPrompt.intro")}</span>{" "}
<span className="block">{t("starPrompt.invitation")}</span>{" "}
<span className="block">{t("starPrompt.thanks")}</span>
</DialogDescription>
</div>
<div className="mt-[27px] grid shrink-0 grid-cols-2 items-stretch gap-3 px-2 max-[480px]:mt-[23px] max-[480px]:gap-2.5 max-[480px]:px-1">
<Button variant="outline" className={actionClassName}
onClick={() => onOpenChange(false)}>{t("starPrompt.later")}</Button>
<div className="flex min-w-0 flex-col gap-2">
<StarLinkView fullWidth error={starError} onActivate={onStar} />
</div>
</div>
<Button variant="ghost" className="mt-[7px] min-h-11 shrink-0 self-center !whitespace-normal px-4 text-xs font-normal text-muted-foreground" disabled={saving}
onClick={() => void onDismissForever()}>{t("starPrompt.never")}</Button>
{error && <p role="alert" className="text-sm text-destructive">{t("starPrompt.saveError")}</p>}
</DialogContent>
</Dialog>
);
}
+8 -30
View File
@@ -1,8 +1,7 @@
import { useState } from "react";
import { ExternalLink, Info, RotateCw } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { WebPreviewPanelView } from "@/components/WebPreviewPanelView";
import { isLoopbackHost } from "@/lib/network";
import { currentWebPreviewRestriction, parseWebLink } from "@/lib/web-preview";
@@ -15,32 +14,11 @@ export function WebPreviewPanel({ url: value }: WebPreviewPanelProps) {
const [revision, setRevision] = useState(0);
const url = parseWebLink(value);
const restriction = currentWebPreviewRestriction(url);
const buttonClass = "inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
return (
<section aria-label={t("webPreview.title")} data-testid="web-preview-panel" className="flex min-h-0 flex-1 flex-col">
<div className="flex h-9 shrink-0 items-center gap-1 border-b border-border/40 px-2">
<p className="min-w-0 flex-1 truncate px-1 text-xs text-muted-foreground" title={url?.href}>{url?.href}</p>
<Popover>
<PopoverTrigger asChild><button type="button" className={buttonClass} aria-label={t("previewTabs.websiteInfo")} title={t("previewTabs.websiteInfo")}><Info className="size-3.5" aria-hidden /></button></PopoverTrigger>
<PopoverContent align="end" className="w-72 space-y-2 rounded-control p-3 text-xs leading-relaxed text-muted-foreground">
<p>{t("webPreview.isolated")}</p>
<p>{t("webPreview.blockedHint")}</p>
{url && isLoopbackHost(url.hostname) ? <p>{t("webPreview.loopback")}</p> : null}
</PopoverContent>
</Popover>
{!restriction ? <button type="button" className={buttonClass} onClick={() => setRevision((n) => n + 1)} title={t("webPreview.refresh")} aria-label={t("webPreview.refresh")}>
<RotateCw className="h-4 w-4" aria-hidden />
</button> : null}
{url ? <a className={buttonClass} href={url.href} target="_blank" rel="noreferrer noopener" title={t("webPreview.external")} aria-label={t("webPreview.external")}>
<ExternalLink className="h-4 w-4" aria-hidden />
</a> : null}
</div>
{restriction ? <div role="status" className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-6 text-center text-sm text-muted-foreground">
{t(`webPreview.${restriction}`)}
</div> : <iframe key={`${value}:${revision}`} title={t("webPreview.frame", { host: url!.host })}
{...{ credentialless: "" }} sandbox="allow-scripts" referrerPolicy="no-referrer"
allow="camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'; payment 'none'; fullscreen 'none'; display-capture 'none'; usb 'none'; serial 'none'; hid 'none'"
src={url!.href} className="min-h-0 w-full flex-1 border-0 bg-white" />}
</section>
);
return <WebPreviewPanelView url={url} restriction={restriction} loopback={!!url && isLoopbackHost(url.hostname)}
onRefresh={() => setRevision((n) => n + 1)}>
{!restriction ? <iframe key={`${value}:${revision}`} title={t("webPreview.frame", { host: url!.host })}
{...{ credentialless: "" }} sandbox="allow-scripts" referrerPolicy="no-referrer"
allow="camera 'none'; microphone 'none'; geolocation 'none'; clipboard-read 'none'; clipboard-write 'none'; payment 'none'; fullscreen 'none'; display-capture 'none'; usb 'none'; serial 'none'; hid 'none'"
src={url!.href} className="min-h-0 w-full flex-1 border-0 bg-white" /> : null}
</WebPreviewPanelView>;
}
@@ -0,0 +1,41 @@
import type { ReactNode } from "react";
import { ExternalLink, Info, RotateCw } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import type { currentWebPreviewRestriction } from "@/lib/web-preview";
export function WebPreviewPanelView({ url, restriction, loopback, onRefresh, children }: {
url: URL | null;
restriction: ReturnType<typeof currentWebPreviewRestriction>;
loopback: boolean;
onRefresh: () => void;
children?: ReactNode;
}) {
const { t } = useTranslation();
const buttonClass = "inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
return (
<section aria-label={t("webPreview.title")} data-testid="web-preview-panel" className="flex min-h-0 flex-1 flex-col">
<div className="flex h-9 shrink-0 items-center gap-1 border-b border-border/40 px-2">
<p className="min-w-0 flex-1 truncate px-1 text-xs text-muted-foreground" title={url?.href}>{url?.href}</p>
<Popover>
<PopoverTrigger asChild><button type="button" className={buttonClass} aria-label={t("previewTabs.websiteInfo")} title={t("previewTabs.websiteInfo")}><Info className="size-3.5" aria-hidden /></button></PopoverTrigger>
<PopoverContent align="end" className="w-72 space-y-2 rounded-control p-3 text-xs leading-relaxed text-muted-foreground">
<p>{t("webPreview.isolated")}</p>
<p>{t("webPreview.blockedHint")}</p>
{loopback ? <p>{t("webPreview.loopback")}</p> : null}
</PopoverContent>
</Popover>
{!restriction ? <button type="button" className={buttonClass} onClick={onRefresh} title={t("webPreview.refresh")} aria-label={t("webPreview.refresh")}>
<RotateCw className="h-4 w-4" aria-hidden />
</button> : null}
{url ? <a className={buttonClass} href={url.href} target="_blank" rel="noreferrer noopener" title={t("webPreview.external")} aria-label={t("webPreview.external")}>
<ExternalLink className="h-4 w-4" aria-hidden />
</a> : null}
</div>
{restriction ? <div role="status" className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-6 text-center text-sm text-muted-foreground">
{t(`webPreview.${restriction}`)}
</div> : children}
</section>
);
}
+8 -180
View File
@@ -1,190 +1,18 @@
import { createContext, useContext, useEffect, useRef, useState } from "react";
import { Check, ChevronUp, CircleAlert, Laptop, Loader2, Search, Server, Settings2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { ConnectionBadge } from "@/components/ConnectionBadge";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useContext, useEffect, useState } from "react";
import { useClient } from "@/providers/ClientProvider";
import { cn } from "@/lib/utils";
import type { ConnectionStatus } from "@/lib/types";
import type { HostAnchor, EmbeddedHost } from "./host-bridge";
import { HostConnectionStatus } from "./HostConnectionStatus";
import type { HostConnectionState } from "./remote-context";
import { HostNavigationContext } from "./host-navigation";
import { HostSwitcherView } from "./HostSwitcherView";
export interface HostPicker {
kind: "shell";
name: string;
hostname: string;
localName: string;
currentId: string | null;
profiles: { id: string; name: string; host: string; state: HostConnectionState }[];
recentIds: string[];
pending: { id: string; name: string } | null;
error: string;
offline: boolean;
offlineLabel?: string;
select: (id: string | null) => void;
manage: () => void;
cancel: () => void;
clearError: () => void;
restoreFocus: () => void;
}
interface EmbeddedPicker extends EmbeddedHost {
kind: "embedded";
open: (anchor: HostAnchor) => void;
}
export const HostNavigationContext = createContext<HostPicker | EmbeddedPicker | null>(null);
export { HostNavigationContext, type HostPicker } from "./host-navigation";
export { RemoteHostMenu } from "./HostSwitcherView";
function HostMenuContent({ picker, portalContainer }: { picker: HostPicker; portalContainer?: HTMLElement | null }) {
return <DropdownMenuContent side="top" align="end" sideOffset={8} collisionPadding={12}
portalContainer={portalContainer} className="flex w-64 max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden"
onEscapeKeyDown={(event) => { if (event.isComposing) event.preventDefault(); }}
onCloseAutoFocus={(event) => { event.preventDefault(); picker.restoreFocus(); }}>
<HostMenuItems picker={picker} />
</DropdownMenuContent>;
}
/** Mounted with the menu so every opening starts with a fresh, stable list. */
function HostMenuItems({ picker }: { picker: HostPicker }) {
const { t } = useTranslation();
const [searchable] = useState(() => picker.profiles.length > 5);
const [query, setQuery] = useState("");
const [order] = useState(() => [picker.currentId, ...picker.recentIds]);
const search = useRef<HTMLInputElement>(null);
const list = useRef<HTMLDivElement>(null);
const needle = query.trim().toLocaleLowerCase();
const matches = (...values: string[]) => values.some((value) => value.toLocaleLowerCase().includes(needle));
const showLocal = matches(t("remote.local"), picker.localName);
const profiles = picker.profiles.filter(({ name, host }) => matches(name, host));
if (searchable) {
const rank = (id: string) => { const index = order.indexOf(id); return index < 0 ? order.length : index; };
profiles.sort((a, b) => rank(a.id) - rank(b.id));
}
useEffect(() => {
// Don't summon the software keyboard when opening the picker on a touch device.
if (!searchable || window.matchMedia("(pointer: coarse)").matches) return;
const frame = requestAnimationFrame(() => search.current?.focus({ preventScroll: true }));
return () => cancelAnimationFrame(frame);
}, [searchable]);
return <div className="flex min-h-0 flex-col"
onPointerMoveCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }}
onPointerOutCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }}
onKeyDownCapture={(event) => {
if (!searchable) return;
if (event.nativeEvent.isComposing) { event.stopPropagation(); return; }
const items = Array.from(event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitem"]'));
if (event.target === search.current) {
// Keep spaces and IME input out of Radix's menu typeahead.
if (event.key !== "Escape") event.stopPropagation();
if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Tab") {
event.preventDefault();
(event.key === "ArrowUp" || event.shiftKey ? items.at(-1) : items[0])?.focus();
} else if (event.key === "Enter") {
event.preventDefault();
if (needle) list.current?.querySelector<HTMLElement>('[role="menuitem"]')?.click();
}
} else if (event.key === "Tab" || (event.key === "ArrowUp" && event.target === items[0])) {
event.preventDefault(); event.stopPropagation(); search.current?.focus();
}
}}>
{searchable ? <div className="flex shrink-0 items-center gap-2 px-2.5 pb-2 pt-1.5">
<Search aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />
<input ref={search} aria-label={t("remote.searchHosts")} placeholder={t("remote.searchHosts")}
value={query} onChange={(event) => setQuery(event.target.value)} autoComplete="off" spellCheck={false}
className="touch-text-input h-7 min-w-0 flex-1 bg-transparent text-[13px] outline-none placeholder:text-muted-foreground" />
</div> : <DropdownMenuLabel className="shrink-0">{t("remote.switchHost")}</DropdownMenuLabel>}
<div ref={list} role="group" aria-label={t("remote.switchHost")}
className="min-h-0 overflow-y-auto overscroll-contain scrollbar-thin scrollbar-track-transparent">
{showLocal && <DropdownMenuItem onSelect={() => picker.select(null)} className="gap-2.5" aria-current={!picker.currentId || undefined}>
<Laptop className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1"><span className="block">{t("remote.local")}</span><span className="block truncate text-xs text-muted-foreground">{picker.localName}</span></span>
{!picker.currentId && <Check className="h-4 w-4" />}
</DropdownMenuItem>}
{showLocal && !!profiles.length && <DropdownMenuSeparator />}
{profiles.map((profile) => <DropdownMenuItem key={profile.id} onSelect={() => picker.select(profile.id)} className="gap-2.5"
aria-label={`${profile.name} ${profile.host}`} aria-describedby={`host-state-${profile.id}`}
title={`${profile.name}\n${profile.host}`} aria-current={picker.currentId === profile.id || undefined}>
<Server className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1"><span className="block truncate">{profile.name}</span><span className="block truncate text-xs text-muted-foreground">{profile.host}</span></span>
<span id={`host-state-${profile.id}`}><HostConnectionStatus state={profile.state} compact /></span>
{picker.currentId === profile.id && <Check aria-label={t("remote.current")} className="h-4 w-4 shrink-0" />}
</DropdownMenuItem>)}
{!showLocal && !profiles.length && <p role="status" className="px-2.5 py-6 text-center text-xs text-muted-foreground">{t("remote.noMatchingHosts")}</p>}
</div>
<div className="shrink-0">
{picker.pending && <><DropdownMenuSeparator /><DropdownMenuItem onSelect={picker.cancel} className="gap-2.5"><X className="h-4 w-4" />{t("remote.cancelSwitch")}</DropdownMenuItem></>}
{picker.error && <div role="alert" className="flex items-start gap-2 px-2.5 py-2 text-xs leading-5 text-foreground">
<CircleAlert aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{picker.error}<button className="ml-2 underline underline-offset-2" onClick={picker.clearError}>{t("common.close")}</button></span>
</div>}
<DropdownMenuSeparator />
<DropdownMenuItem className="gap-2.5" onSelect={picker.manage}><Settings2 className="h-4 w-4 text-muted-foreground" />{t("remote.manageConnections")}</DropdownMenuItem>
</div>
</div>;
}
/** Shared sidebar control. Remote frames can only open the trusted shell's menu. */
/** Connect the sidebar's presentation to the active host and client. */
export function HostSwitcher({ collapsed = false, portalContainer }: { collapsed?: boolean; portalContainer?: HTMLElement | null }) {
const picker = useContext(HostNavigationContext);
const { client } = useClient();
const { t } = useTranslation();
const [status, setStatus] = useState<ConnectionStatus>(client.status);
useEffect(() => client.onStatus(setStatus), [client]);
const buttonRef = useRef<HTMLButtonElement>(null);
if (!picker) return <ConnectionBadge />;
const shell = picker.kind === "shell" ? picker : null;
const remote = picker.kind === "embedded" || !!shell?.currentId;
const pendingName = picker.kind === "shell" ? picker.pending?.name : picker.pendingName;
const currentStatus = shell?.currentId
? (shell.pending?.id === shell.currentId || shell.profiles.find((profile) => profile.id === shell.currentId)?.state === "connecting" ? "connecting" : shell.offline ? "closed" : "open")
: status;
// A failed switch describes the destination, not the still-active connection.
const failed = !!shell?.offline || currentStatus === "error" || currentStatus === "closed";
const waiting = !!pendingName || currentStatus === "connecting" || currentStatus === "reconnecting";
// The old host stays interactive until the new one is ready. Keep its identity
// visible; progress belongs to the target's row and the accessible status.
const label = picker.name;
const currentLabel = failed ? shell?.offlineLabel || t("remote.offline") : t(`connection.${currentStatus}`);
const identity = picker.name === picker.hostname ? picker.name : `${picker.name}, ${picker.hostname}`;
const current = `${identity}, ${currentLabel}`;
const detail = pendingName ? `${current}. ${t("remote.preparing", { name: pendingName })}` : current;
const button = <Button ref={buttonRef} variant="ghost" size="sm" aria-label={t("remote.switchHost")}
data-host-switcher className={cn("host-no-drag touch-target h-8 min-w-0 gap-2 rounded-xl px-2 text-xs font-normal text-sidebar-content/75 hover:text-sidebar-content",
collapsed ? "w-8 justify-center px-0" : "max-w-full flex-1 justify-start")}
onClick={picker.kind === "embedded" ? () => {
const rect = buttonRef.current?.getBoundingClientRect();
if (rect) picker.open({ left: rect.left, top: rect.top, width: rect.width, height: rect.height });
} : undefined}>
<span className="relative flex shrink-0 items-center justify-center">
{waiting ? <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" /> : failed ? <CircleAlert className="h-4 w-4" />
: remote ? <Server className="h-4 w-4" /> : <Laptop className="h-4 w-4" />}
{!waiting && !failed && <span aria-hidden className={cn("absolute -bottom-0.5 -right-0.5 h-1.5 w-1.5 rounded-full ring-2 ring-sidebar", currentStatus === "open" ? "bg-emerald-500" : "bg-muted-foreground")} />}
</span>
{!collapsed && <><span className="truncate">{label}</span><ChevronUp className="ml-auto h-3 w-3 shrink-0 opacity-60" /></>}
<span className="sr-only" role="status">{detail}</span>
</Button>;
const trigger = <TooltipTrigger asChild>{button}</TooltipTrigger>;
// The mobile sidebar already owns the modal lock; a nested lock can outlive it on navigation.
return <TooltipProvider><Tooltip>
{shell ? <DropdownMenu modal={!portalContainer}><DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger><HostMenuContent picker={shell} portalContainer={portalContainer} /></DropdownMenu> : trigger}
<TooltipContent side="top" className="max-w-[min(24rem,calc(100vw-2rem))] space-y-1 break-words">
<p className="font-medium">{picker.name}</p>
{picker.hostname !== picker.name ? <p className="font-mono text-xs text-muted-foreground">{picker.hostname}</p> : null}
<p>{currentLabel}</p>
{pendingName ? <p>{t("remote.preparing", { name: pendingName })}</p> : null}
{picker.error ? <p className="text-destructive">{picker.error}</p> : null}
</TooltipContent>
</Tooltip></TooltipProvider>;
}
/** Parent-owned menu anchored to the active remote sidebar, never inside its DOM. */
export function RemoteHostMenu({ picker, anchor, onClose }: { picker: HostPicker; anchor: HostAnchor | null; onClose: () => void }) {
return <DropdownMenu open={!!anchor} onOpenChange={(open) => { if (!open) onClose(); }}>
<DropdownMenuTrigger asChild><button tabIndex={-1} aria-hidden className="pointer-events-none fixed opacity-0" style={anchor ? {
left: Math.max(0, Math.min(anchor.left, window.innerWidth - 32)), top: Math.max(0, Math.min(anchor.top, window.innerHeight - 32)),
width: Math.min(anchor.width, window.innerWidth), height: Math.min(anchor.height, 64),
} : { width: 0, height: 0 }} /></DropdownMenuTrigger>
<HostMenuContent picker={picker} />
</DropdownMenu>;
return <HostSwitcherView picker={picker} status={status} collapsed={collapsed} portalContainer={portalContainer} />;
}
@@ -0,0 +1,166 @@
import { useEffect, useRef, useState } from "react";
import { Check, ChevronUp, CircleAlert, Laptop, Loader2, Search, Server, Settings2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { ConnectionBadge } from "@/components/ConnectionBadge";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { cn } from "@/lib/utils";
import type { ConnectionStatus } from "@/lib/types";
import type { HostAnchor } from "./host-bridge";
import type { HostPicker, EmbeddedPicker } from "./host-navigation";
import { HostConnectionStatus } from "./HostConnectionStatus";
function HostMenuContent({ picker, portalContainer }: { picker: HostPicker; portalContainer?: HTMLElement | null }) {
return <DropdownMenuContent side="top" align="end" sideOffset={8} collisionPadding={12}
portalContainer={portalContainer} className="flex w-64 max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden"
onEscapeKeyDown={(event) => { if (event.isComposing) event.preventDefault(); }}
onCloseAutoFocus={(event) => { event.preventDefault(); picker.restoreFocus(); }}>
<HostMenuItems picker={picker} />
</DropdownMenuContent>;
}
/** Mounted with the menu so every opening starts with a fresh, stable list. */
function HostMenuItems({ picker }: { picker: HostPicker }) {
const { t } = useTranslation();
const [searchable] = useState(() => picker.profiles.length > 5);
const [query, setQuery] = useState("");
const [order] = useState(() => [picker.currentId, ...picker.recentIds]);
const search = useRef<HTMLInputElement>(null);
const list = useRef<HTMLDivElement>(null);
const needle = query.trim().toLocaleLowerCase();
const matches = (...values: string[]) => values.some((value) => value.toLocaleLowerCase().includes(needle));
const showLocal = matches(t("remote.local"), picker.localName);
const profiles = picker.profiles.filter(({ name, host }) => matches(name, host));
if (searchable) {
const rank = (id: string) => { const index = order.indexOf(id); return index < 0 ? order.length : index; };
profiles.sort((a, b) => rank(a.id) - rank(b.id));
}
useEffect(() => {
// Don't summon the software keyboard when opening the picker on a touch device.
if (!searchable || window.matchMedia("(pointer: coarse)").matches) return;
const frame = requestAnimationFrame(() => search.current?.focus({ preventScroll: true }));
return () => cancelAnimationFrame(frame);
}, [searchable]);
return <div className="flex min-h-0 flex-col"
onPointerMoveCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }}
onPointerOutCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }}
onKeyDownCapture={(event) => {
if (!searchable) return;
if (event.nativeEvent.isComposing) { event.stopPropagation(); return; }
const items = Array.from(event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitem"]'));
if (event.target === search.current) {
// Keep spaces and IME input out of Radix's menu typeahead.
if (event.key !== "Escape") event.stopPropagation();
if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Tab") {
event.preventDefault();
(event.key === "ArrowUp" || event.shiftKey ? items.at(-1) : items[0])?.focus();
} else if (event.key === "Enter") {
event.preventDefault();
if (needle) list.current?.querySelector<HTMLElement>('[role="menuitem"]')?.click();
}
} else if (event.key === "Tab" || (event.key === "ArrowUp" && event.target === items[0])) {
event.preventDefault(); event.stopPropagation(); search.current?.focus();
}
}}>
{searchable ? <div className="flex shrink-0 items-center gap-2 px-2.5 pb-2 pt-1.5">
<Search aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />
<input ref={search} aria-label={t("remote.searchHosts")} placeholder={t("remote.searchHosts")}
value={query} onChange={(event) => setQuery(event.target.value)} autoComplete="off" spellCheck={false}
className="touch-text-input h-7 min-w-0 flex-1 bg-transparent text-[13px] outline-none placeholder:text-muted-foreground" />
</div> : <DropdownMenuLabel className="shrink-0">{t("remote.switchHost")}</DropdownMenuLabel>}
<div ref={list} role="group" aria-label={t("remote.switchHost")}
className="min-h-0 overflow-y-auto overscroll-contain scrollbar-thin scrollbar-track-transparent">
{showLocal && <DropdownMenuItem onSelect={() => picker.select(null)} className="gap-2.5" aria-current={!picker.currentId || undefined}>
<Laptop className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1"><span className="block">{t("remote.local")}</span><span className="block truncate text-xs text-muted-foreground">{picker.localName}</span></span>
{!picker.currentId && <Check className="h-4 w-4" />}
</DropdownMenuItem>}
{showLocal && !!profiles.length && <DropdownMenuSeparator />}
{profiles.map((profile) => <DropdownMenuItem key={profile.id} onSelect={() => picker.select(profile.id)} className="gap-2.5"
aria-label={`${profile.name} ${profile.host}`} aria-describedby={`host-state-${profile.id}`}
title={`${profile.name}\n${profile.host}`} aria-current={picker.currentId === profile.id || undefined}>
<Server className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1"><span className="block truncate">{profile.name}</span><span className="block truncate text-xs text-muted-foreground">{profile.host}</span></span>
<span id={`host-state-${profile.id}`}><HostConnectionStatus state={profile.state} compact /></span>
{picker.currentId === profile.id && <Check aria-label={t("remote.current")} className="h-4 w-4 shrink-0" />}
</DropdownMenuItem>)}
{!showLocal && !profiles.length && <p role="status" className="px-2.5 py-6 text-center text-xs text-muted-foreground">{t("remote.noMatchingHosts")}</p>}
</div>
<div className="shrink-0">
{picker.pending && <><DropdownMenuSeparator /><DropdownMenuItem onSelect={picker.cancel} className="gap-2.5"><X className="h-4 w-4" />{t("remote.cancelSwitch")}</DropdownMenuItem></>}
{picker.error && <div role="alert" className="flex items-start gap-2 px-2.5 py-2 text-xs leading-5 text-foreground">
<CircleAlert aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{picker.error}<button className="ml-2 underline underline-offset-2" onClick={picker.clearError}>{t("common.close")}</button></span>
</div>}
<DropdownMenuSeparator />
<DropdownMenuItem className="gap-2.5" onSelect={picker.manage}><Settings2 className="h-4 w-4 text-muted-foreground" />{t("remote.manageConnections")}</DropdownMenuItem>
</div>
</div>;
}
/** Shared sidebar control. Remote frames can only open the trusted shell's menu. */
export function HostSwitcherView({ picker, status, collapsed = false, portalContainer }: {
picker: HostPicker | EmbeddedPicker | null;
status: ConnectionStatus;
collapsed?: boolean;
portalContainer?: HTMLElement | null;
}) {
const { t } = useTranslation();
const buttonRef = useRef<HTMLButtonElement>(null);
if (!picker) return <ConnectionBadge status={status} />;
const shell = picker.kind === "shell" ? picker : null;
const remote = picker.kind === "embedded" || !!shell?.currentId;
const pendingName = picker.kind === "shell" ? picker.pending?.name : picker.pendingName;
const currentStatus = shell?.currentId
? (shell.pending?.id === shell.currentId || shell.profiles.find((profile) => profile.id === shell.currentId)?.state === "connecting" ? "connecting" : shell.offline ? "closed" : "open")
: status;
// A failed switch describes the destination, not the still-active connection.
const failed = !!shell?.offline || currentStatus === "error" || currentStatus === "closed";
const waiting = !!pendingName || currentStatus === "connecting" || currentStatus === "reconnecting";
// The old host stays interactive until the new one is ready. Keep its identity
// visible; progress belongs to the target's row and the accessible status.
const label = picker.name;
const currentLabel = failed ? shell?.offlineLabel || t("remote.offline") : t(`connection.${currentStatus}`);
const identity = picker.name === picker.hostname ? picker.name : `${picker.name}, ${picker.hostname}`;
const current = `${identity}, ${currentLabel}`;
const detail = pendingName ? `${current}. ${t("remote.preparing", { name: pendingName })}` : current;
const button = <Button ref={buttonRef} variant="ghost" size="sm" aria-label={t("remote.switchHost")}
data-host-switcher className={cn("host-no-drag touch-target h-8 min-w-0 gap-2 rounded-xl px-2 text-xs font-normal text-sidebar-content/75 hover:text-sidebar-content",
collapsed ? "w-8 justify-center px-0" : "max-w-full flex-1 justify-start")}
onClick={picker.kind === "embedded" ? () => {
const rect = buttonRef.current?.getBoundingClientRect();
if (rect) picker.open({ left: rect.left, top: rect.top, width: rect.width, height: rect.height });
} : undefined}>
<span className="relative flex shrink-0 items-center justify-center">
{waiting ? <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" /> : failed ? <CircleAlert className="h-4 w-4" />
: remote ? <Server className="h-4 w-4" /> : <Laptop className="h-4 w-4" />}
{!waiting && !failed && <span aria-hidden className={cn("absolute -bottom-0.5 -right-0.5 h-1.5 w-1.5 rounded-full ring-2 ring-sidebar", currentStatus === "open" ? "bg-emerald-500" : "bg-muted-foreground")} />}
</span>
{!collapsed && <><span className="truncate">{label}</span><ChevronUp className="ml-auto h-3 w-3 shrink-0 opacity-60" /></>}
<span className="sr-only" role="status">{detail}</span>
</Button>;
const trigger = <TooltipTrigger asChild>{button}</TooltipTrigger>;
// The mobile sidebar already owns the modal lock; a nested lock can outlive it on navigation.
return <TooltipProvider><Tooltip>
{shell ? <DropdownMenu modal={!portalContainer}><DropdownMenuTrigger asChild>{trigger}</DropdownMenuTrigger><HostMenuContent picker={shell} portalContainer={portalContainer} /></DropdownMenu> : trigger}
<TooltipContent side="top" className="max-w-[min(24rem,calc(100vw-2rem))] space-y-1 break-words">
<p className="font-medium">{picker.name}</p>
{picker.hostname !== picker.name ? <p className="font-mono text-xs text-muted-foreground">{picker.hostname}</p> : null}
<p>{currentLabel}</p>
{pendingName ? <p>{t("remote.preparing", { name: pendingName })}</p> : null}
{picker.error ? <p className="text-destructive">{picker.error}</p> : null}
</TooltipContent>
</Tooltip></TooltipProvider>;
}
/** Parent-owned menu anchored to the active remote sidebar, never inside its DOM. */
export function RemoteHostMenu({ picker, anchor, onClose }: { picker: HostPicker; anchor: HostAnchor | null; onClose: () => void }) {
return <DropdownMenu open={!!anchor} onOpenChange={(open) => { if (!open) onClose(); }}>
<DropdownMenuTrigger asChild><button tabIndex={-1} aria-hidden className="pointer-events-none fixed opacity-0" style={anchor ? {
left: Math.max(0, Math.min(anchor.left, window.innerWidth - 32)), top: Math.max(0, Math.min(anchor.top, window.innerHeight - 32)),
width: Math.min(anchor.width, window.innerWidth), height: Math.min(anchor.height, 64),
} : { width: 0, height: 0 }} /></DropdownMenuTrigger>
<HostMenuContent picker={picker} />
</DropdownMenu>;
}
@@ -1,11 +1,9 @@
import { useEffect, useRef, useState } from "react";
import { AlertCircle, Check, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useClient } from "@/providers/ClientProvider";
import { remoteAction } from "@/lib/remote-instances";
import { useRemoteConnections } from "./remote-context";
import { PairRouteSettingsView } from "./PairRouteSettingsView";
/** An explicit escape hatch for a VPN/bound-interface route, not a new SSH form. */
export function PairRouteSettings({ id, onSaved, showHint = true }: { id: string; onSaved?: () => void; showHint?: boolean }) {
@@ -38,21 +36,9 @@ export function PairRouteSettings({ id, onSaved, showHint = true }: { id: string
if (alive.current) setError(t(`remote.errors.${reason instanceof Error ? reason.message : "unknown"}`, { defaultValue: t("remote.errors.unknown") }));
} finally { if (alive.current) setBusy(false); }
};
return <div className="space-y-3">
{showHint && <p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.routeHint")}</p>}
<Select value={route} onValueChange={(value) => { setRoute(value); setError(""); setSaved(false); }} disabled={busy}><SelectTrigger className="w-full min-w-0" aria-label={t("remote.pair.route")}><SelectValue /></SelectTrigger>
<SelectContent>
{hasSavedRoute && <SelectItem value="saved">{t("remote.pair.savedRoute")}</SelectItem>}
<SelectItem value="direct">{t("remote.pair.direct")}</SelectItem>
{connections?.directory?.profiles.filter((profile) => !profile.paired).map((profile) => <SelectItem key={profile.id} value={profile.id} className="h-auto min-h-9 max-w-[calc(100vw-3rem)] py-2 [overflow-wrap:anywhere]">{profile.name}</SelectItem>)}
</SelectContent>
</Select>
{error && <p role="alert" className="remote-alert items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{error}</span></p>}
<div className="flex flex-wrap items-center justify-end gap-3">
{saved && <p role="status" className="mr-auto flex items-center gap-1.5 text-xs text-muted-foreground"><Check aria-hidden className="h-3.5 w-3.5" />{t("remote.saved")}</p>}
<Button className="remote-action" size="sm" disabled={busy || route === original || route === "saved"} aria-busy={busy} onClick={() => { void save(); }}>
{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" />}{t(busy ? "remote.saving" : "remote.save")}
</Button>
</div>
</div>;
return <PairRouteSettingsView hasSavedRoute={hasSavedRoute}
routes={connections?.directory?.profiles.filter((profile) => !profile.paired) ?? []}
route={route} original={original} busy={busy} error={error} saved={saved} showHint={showHint}
onRouteChange={(value) => { setRoute(value); setError(""); setSaved(false); }}
onSave={() => { void save(); }} />;
}
@@ -0,0 +1,41 @@
import { AlertCircle, Check, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import type { RemoteProfile } from "@/lib/remote-instances";
export interface PairRouteSettingsViewProps {
hasSavedRoute: boolean;
routes: Array<Pick<RemoteProfile, "id" | "name">>;
route: string;
original: string;
busy: boolean;
error: string;
saved: boolean;
showHint?: boolean;
onRouteChange: (route: string) => void;
onSave: () => void;
}
export function PairRouteSettingsView({
hasSavedRoute, routes, route, original, busy, error, saved, showHint = true, onRouteChange, onSave,
}: PairRouteSettingsViewProps) {
const { t } = useTranslation();
return <div className="space-y-3">
{showHint && <p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.routeHint")}</p>}
<Select value={route} onValueChange={onRouteChange} disabled={busy}><SelectTrigger className="w-full min-w-0" aria-label={t("remote.pair.route")}><SelectValue /></SelectTrigger>
<SelectContent>
{hasSavedRoute && <SelectItem value="saved">{t("remote.pair.savedRoute")}</SelectItem>}
<SelectItem value="direct">{t("remote.pair.direct")}</SelectItem>
{routes.map((profile) => <SelectItem key={profile.id} value={profile.id} className="h-auto min-h-9 max-w-[calc(100vw-3rem)] py-2 [overflow-wrap:anywhere]">{profile.name}</SelectItem>)}
</SelectContent>
</Select>
{error && <p role="alert" className="remote-alert items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{error}</span></p>}
<div className="flex flex-wrap items-center justify-end gap-3">
{saved && <p role="status" className="mr-auto flex items-center gap-1.5 text-xs text-muted-foreground"><Check aria-hidden className="h-3.5 w-3.5" />{t("remote.saved")}</p>}
<Button className="remote-action" size="sm" disabled={busy || route === original || route === "saved"} aria-busy={busy} onClick={onSave}>
{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" />}{t(busy ? "remote.saving" : "remote.save")}
</Button>
</div>
</div>;
}
+16 -136
View File
@@ -1,32 +1,19 @@
import { useEffect, useId, useRef, useState } from "react";
import { AlertCircle, ArrowLeft, Check, ChevronDown, Copy, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Disclosure, DisclosureContent } from "@/components/ui/disclosure";
import { Textarea } from "@/components/ui/textarea";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useEffect, useRef, useState } from "react";
import { useClient } from "@/providers/ClientProvider";
import { copyTextToClipboard } from "@/lib/clipboard";
import { CodeBlock } from "@/components/CodeBlock";
import { remoteAction } from "@/lib/remote-instances";
import { pairingReturnOrigin, type PairReturn } from "@/lib/remote-pair-return";
import type { ConnectionStatus } from "@/lib/types";
import { useRemoteConnections } from "./remote-context";
import { PairRouteSettings } from "./PairRouteSettings";
import "./remote-layout.css";
type Request = { id: string; command: string; expires: number };
type Preview = { id: string; host: string; hostname: string; fingerprint: string; authorized_until: number; revoke_command: string;
existing_connection?: { id: string; name: string; connected: boolean } };
import { QuickPairSetupView, type PairInvitation, type PairConnectionPreview, type QuickPairPanel } from "./QuickPairSetupView";
/** Public invitation → encrypted receipt → explicit confirmation. No private key inputs. */
export function QuickPairSetup({ returned, active = true, onSSH, onClose }: { returned?: PairReturn | null; active?: boolean; onSSH: () => void; onClose: () => void }) {
const { t } = useTranslation();
const { client } = useClient();
const connections = useRemoteConnections();
const [request, setRequest] = useState<Request | null>(returned ? { id: returned.id, command: "", expires: 0 } : null);
const [preview, setPreview] = useState<Preview | null>(null);
const [request, setRequest] = useState<PairInvitation | null>(returned ? { id: returned.id, command: "", expires: 0 } : null);
const [preview, setPreview] = useState<PairConnectionPreview | null>(null);
const [code, setCode] = useState(returned?.code || "");
const [saved, setSaved] = useState("");
const [busy, setBusy] = useState(false);
@@ -36,14 +23,10 @@ export function QuickPairSetup({ returned, active = true, onSSH, onClose }: { re
const [copied, setCopied] = useState(false);
const [expired, setExpired] = useState(false);
const [manual, setManual] = useState(false);
const [panel, setPanel] = useState<"command" | "help" | null>(null);
const [panel, setPanel] = useState<QuickPairPanel>(null);
const alive = useRef(true);
const initialized = useRef(false);
const requestId = useRef(returned?.id || "");
const manualInput = useRef<HTMLTextAreaElement>(null);
const focusManual = useRef(false);
const codeId = useId();
const panelId = useId();
const waitingForLocal = status !== "open";
const pending = busy || (waitingForLocal && !error);
@@ -84,14 +67,14 @@ export function QuickPairSetup({ returned, active = true, onSSH, onClose }: { re
};
const start = () => run(async () => {
if (requestId.current) await remoteAction(client, "pair_cancel", { id: requestId.current });
const result = await remoteAction<Request>(client, "pair_start", { return_origin: pairingReturnOrigin() });
const result = await remoteAction<PairInvitation>(client, "pair_start", { return_origin: pairingReturnOrigin() });
if (!alive.current) { await remoteAction(client, "pair_cancel", { id: result.id }); return; }
requestId.current = result.id;
setRequest(result); setPreview(null); setCode(""); setCopied(false); setExpired(false); setManual(false); setPanel(null);
});
const review = () => run(async () => {
if (!request) return;
const result = await remoteAction<Preview>(client, "pair_preview", { id: request.id, code });
const result = await remoteAction<PairConnectionPreview>(client, "pair_preview", { id: request.id, code });
if (alive.current) setPreview(result);
});
const connect = () => run(async () => {
@@ -131,116 +114,13 @@ export function QuickPairSetup({ returned, active = true, onSSH, onClose }: { re
else { setPanel("command"); setError("remote.pair.copyFailed"); }
});
};
const invalidReturn = ["pair_invalid", "pair_expired", "pair_used"].some((code) => error === `remote.errors.${code}`);
const requestUnavailable = error === "remote.errors.pair_expired" || error === "remote.errors.pair_used";
const restartAvailable = !saved && (expired || requestUnavailable || (!!error && !request?.command && !preview && (!returned || invalidReturn)));
const visiblePreview = restartAvailable ? null : preview;
const reviewingReturn = !!returned && !request?.command && !visiblePreview && !manual && !restartAvailable;
const title = visiblePreview ? visiblePreview.existing_connection ? "remote.sameInstance.title" : "remote.pair.confirmTitle" : reviewingReturn ? "remote.pair.review" : restartAvailable ? "remote.add"
: manual ? "remote.pair.code" : copied ? "remote.pair.copiedTitle" : "remote.add";
const description = visiblePreview || reviewingReturn ? "remote.pair.confirmLinkDescription" : restartAvailable ? "remote.pair.introHint"
: manual ? "remote.pair.codeHint" : copied ? "remote.pair.afterCopyHint" : "remote.pair.introHint";
const showCopied = copied && !manual && !visiblePreview && !restartAvailable;
const showIllustration = !visiblePreview && !manual && !reviewingReturn && !restartAvailable;
const showBusy = pending && busyVisible;
const actionLabel = restartAvailable ? "remote.pair.restart" : reviewingReturn ? error ? "remote.retry" : "remote.pair.review" : visiblePreview ? saved ? "remote.retry" : visiblePreview.existing_connection ? "remote.sameInstance.saveAndOpen" : "remote.connect"
: manual ? "remote.pair.review" : copied ? "remote.pair.copyAgain" : "remote.pair.copy";
const busyLabel = waitingForLocal ? "remote.pair.waitingForLocal" : visiblePreview ? "remote.connecting" : !restartAvailable && (manual || returned)
? "remote.pair.checkingLink" : "remote.pair.preparing";
return <div className="remote-pair flex min-h-0 flex-col">
<div className="-mx-1 min-h-0 overflow-y-auto overscroll-contain px-1">
<DialogHeader className={showIllustration ? "space-y-0 text-center sm:text-center" : "pr-5 text-left"}>
{showIllustration && <RemoteConnectionIllustration />}
<div aria-live="polite" aria-atomic="true" className="space-y-1.5">
<DialogTitle className={showIllustration ? "flex min-h-5 items-center justify-center gap-2 text-xl leading-snug tracking-normal" : "flex min-h-5 items-center gap-2"}>
{showCopied && <Check aria-hidden="true" className="h-5 w-5 shrink-0 motion-safe:animate-in motion-safe:fade-in duration-150" />}
<span className="min-w-0 [overflow-wrap:anywhere]">{t(title)}</span>
</DialogTitle>
<DialogDescription>{t(description)}</DialogDescription>
</div>
</DialogHeader>
{visiblePreview ? <div className="space-y-4 pt-4">
<div className="rounded-2xl bg-muted/50 p-4">
<p className="font-medium [overflow-wrap:anywhere]">{visiblePreview.existing_connection?.name || visiblePreview.hostname}</p>
<p className="mt-1 break-all text-xs text-muted-foreground">{visiblePreview.host}</p>
</div>
{visiblePreview.existing_connection && <p role="status" className="text-xs leading-5 text-muted-foreground">{t("remote.sameInstance.pairHint")}</p>}
<p className="text-[13px] leading-5">{t("remote.pair.access")}</p>
<p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.expiry", { date: new Date(visiblePreview.authorized_until * 1000).toLocaleDateString() })}</p>
<Disclosure className="text-xs text-muted-foreground" summaryClassName="flex min-h-9 items-center gap-2 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{t("remote.pair.security")}</>}>
<p className="my-2 leading-5">{t("remote.pair.fingerprint")}</p><code className="block break-all">{visiblePreview.fingerprint}</code>
<p className="mb-2 mt-4 leading-5">{t("remote.pair.revoke")}</p><CodeBlock language="bash" code={visiblePreview.revoke_command} highlight={false} className="min-w-0 [&_pre]:[overflow-wrap:anywhere]" />
</Disclosure>
{saved && error && <div className="space-y-2"><p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.retryHint")}</p>
<Disclosure summaryClassName="flex min-h-9 items-center gap-2 rounded-xl text-xs text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" contentClassName="pt-2"
summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{t("remote.pair.route")}</>}><PairRouteSettings id={saved} /></Disclosure>
</div>}
</div> : restartAvailable ? null : <>
{manual && <div className="space-y-2 pt-4"><label htmlFor={codeId} className="sr-only">{t("remote.pair.code")}</label>
<Textarea ref={manualInput} id={codeId} value={code} onChange={(event) => { setCode(event.target.value); setError(""); }} placeholder="nbpc1.…" autoComplete="off" spellCheck={false} disabled={busy || expired} className="min-h-20 resize-none break-all font-mono text-xs" />
</div>}
<div>
<DisclosureContent id={panelId} open={panel === "command" && !!request?.command} className="pt-4">
<div className="rounded-2xl bg-muted/50 p-3">
<code className="block max-h-32 select-text overflow-y-auto text-[11px] leading-5 [overflow-wrap:anywhere]" aria-label={t("remote.pair.command")}>{request?.command}</code>
</div>
</DisclosureContent>
<DisclosureContent open={panel === "help"} className="pt-4">
<div className="space-y-2 rounded-2xl bg-muted/50 p-3 text-xs leading-5 text-muted-foreground">
<p className="font-medium text-foreground">{t("remote.pair.helpTitle")}</p>
<p>{t("remote.pair.requirements")}</p>
<p>{t("remote.pair.runHint")}</p>
<p>{t("remote.pair.validityHint")}</p>
</div>
</DisclosureContent>
</div>
</>}
{expired && !saved && <p role="status" className="mt-4 text-xs leading-5 text-muted-foreground">{t("remote.pair.expired")}</p>}
{error && <p role="alert" className="remote-alert mt-4 items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{t(error, { defaultValue: t("remote.errors.unknown") })}</span></p>}
</div>
<div className={visiblePreview ? "remote-dialog-actions shrink-0 pt-5" : "flex shrink-0 flex-col gap-2 pt-5"}>
{visiblePreview && (!saved ? <Button className="remote-action" variant="ghost" disabled={busy} onClick={() => { setPreview(null); setError(""); if (!request?.command) setManual(true); }}><ArrowLeft className="mr-1 h-4 w-4" />{t("remote.back")}</Button>
: <Button className="remote-action" variant="ghost" onClick={() => { connections?.cancel(); onClose(); }}>{t("common.cancel")}</Button>
)}
<Button variant={showCopied ? "outline" : "default"} className={showCopied ? "remote-action bg-transparent" : "remote-action"} aria-label={t(showBusy ? busyLabel : actionLabel)} aria-busy={pending} disabled={busy || waitingForLocal || (!restartAvailable && (!request || (!visiblePreview && (manual || reviewingReturn ? !code.trim() : !request.command))))} onClick={() => { if (restartAvailable) void start(); else if (visiblePreview) void connect(); else if (manual || reviewingReturn) void review(); else copyCommand(); }}>
{showBusy ? <Loader2 aria-hidden="true" className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" /> : !restartAvailable && !visiblePreview && !manual && !reviewingReturn ? <Copy aria-hidden="true" className="mr-2 h-4 w-4 shrink-0" /> : null}
<span role="status" className="min-w-0">{t(showBusy ? busyLabel : actionLabel)}</span>
</Button>
{!visiblePreview && <div className="remote-pair-alternatives -mx-3 gap-1">
{!restartAvailable && request?.command ? manual ? <Button className="remote-action" variant="ghost" size="sm" disabled={busy} onClick={() => { setManual(false); setPanel(null); setError(""); }}>{t("remote.back")}</Button>
: <Button variant="ghost" size="sm" className="remote-action justify-start text-left text-xs text-muted-foreground" disabled={expired} aria-expanded={panel === "command"} aria-controls={panelId} onClick={() => setPanel(panel === "command" ? null : "command")}>{t("remote.pair.showCommand")}</Button> : <span />}
<DropdownMenu>
<DropdownMenuTrigger asChild><Button variant="ghost" size="sm" className="remote-action justify-end text-right text-xs text-muted-foreground">{t("remote.pair.otherWays")}<ChevronDown aria-hidden="true" className="ml-1 h-3.5 w-3.5 shrink-0" /></Button></DropdownMenuTrigger>
<DropdownMenuContent align="end" onCloseAutoFocus={(event) => {
if (focusManual.current) { event.preventDefault(); focusManual.current = false; manualInput.current?.focus(); }
}}>
<DropdownMenuItem disabled={!request || busy || expired || restartAvailable} onSelect={() => { focusManual.current = true; setManual(true); setPanel(null); setError(""); }}>{t("remote.pair.pasteInstead")}</DropdownMenuItem>
<DropdownMenuItem onSelect={onSSH}>{t("remote.pair.useSSH")}</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem disabled={restartAvailable} onSelect={() => setPanel(panel === "help" ? null : "help")}>{t("remote.pair.helpTitle")}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>}
</div>
</div>;
}
/** Decorative overview, not a live connection-status indicator. */
function RemoteConnectionIllustration() {
return <svg viewBox="0 0 208 88" width="184" height="78" aria-hidden="true" focusable="false" className="mx-auto mb-4 shrink-0 text-foreground/70" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
<path d="M78 51 C111 65 114 28 146 36" className="text-muted-foreground/50" strokeWidth="2.5" />
<rect x="10" y="25" width="68" height="43" rx="3" />
<path d="M4 68 H84 V70 A5 5 0 0 1 79 75 H9 A5 5 0 0 1 4 70 Z" />
<g className="text-muted-foreground">
<rect x="27" y="34" width="34" height="26" rx="2" />
<path d="M32 39 h.01 M36 39 h.01 M40 39 h.01" strokeWidth="2.5" />
</g>
<rect x="146" y="10" width="50" height="70" rx="3" />
<image href="/brand/nanobot_mark.svg" x="155" y="17" width="32" height="32" />
<path d="M146 53 H196 M146 66 H196 M152 60 H177 M152 73 H177 M152 80 V83 H158 V80 M184 80 V83 H190 V80" />
<circle cx="188" cy="60" r="1.8" />
<circle cx="188" cy="73" r="1.8" />
</svg>;
return <QuickPairSetupView
state={{ request, preview, code, saved: !!saved, busy, busyVisible, error, status, copied, expired, manual, panel, returned: !!returned }}
routeSettings={saved ? <PairRouteSettings id={saved} /> : null}
onStart={() => { void start(); }} onReview={() => { void review(); }} onConnect={() => { void connect(); }}
onCopyCommand={copyCommand}
onCodeChange={(value) => { setCode(value); setError(""); }}
onManualChange={(value) => { setManual(value); setPanel(null); setError(""); }} onPanelChange={setPanel}
onBack={() => { setPreview(null); setError(""); if (!request?.command) setManual(true); }}
onCancel={() => { connections?.cancel(); onClose(); }} onSSH={onSSH} />;
}
@@ -0,0 +1,186 @@
import { useId, useRef, type ReactNode } from "react";
import { AlertCircle, ArrowLeft, Check, ChevronDown, Copy, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Disclosure, DisclosureContent } from "@/components/ui/disclosure";
import { Textarea } from "@/components/ui/textarea";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { CodeBlock } from "@/components/CodeBlock";
import type { ConnectionStatus } from "@/lib/types";
import "./remote-layout.css";
export interface PairInvitation {
id: string;
command: string;
expires: number;
}
export interface PairConnectionPreview {
id: string;
host: string;
hostname: string;
fingerprint: string;
authorized_until: number;
revoke_command: string;
existing_connection?: { id: string; name: string; connected: boolean };
}
export type QuickPairPanel = "command" | "help" | null;
export interface QuickPairSetupState {
request: PairInvitation | null;
preview: PairConnectionPreview | null;
code: string;
saved: boolean;
busy: boolean;
busyVisible: boolean;
error: string;
status: ConnectionStatus;
copied: boolean;
expired: boolean;
manual: boolean;
panel: QuickPairPanel;
returned: boolean;
}
export interface QuickPairSetupViewProps {
state: QuickPairSetupState;
routeSettings: ReactNode;
onStart: () => void;
onReview: () => void;
onConnect: () => void;
onCopyCommand: () => void;
onCodeChange: (code: string) => void;
onManualChange: (manual: boolean) => void;
onPanelChange: (panel: QuickPairPanel) => void;
onBack: () => void;
onCancel: () => void;
onSSH: () => void;
}
export function QuickPairSetupView({
state, routeSettings, onStart, onReview, onConnect, onCopyCommand, onCodeChange, onManualChange,
onPanelChange, onBack, onCancel, onSSH,
}: QuickPairSetupViewProps) {
const { t } = useTranslation();
const { request, preview, code, saved, busy, busyVisible, error, status, copied, expired, manual, panel, returned } = state;
const manualInput = useRef<HTMLTextAreaElement>(null);
const focusManual = useRef(false);
const codeId = useId();
const panelId = useId();
const waitingForLocal = status !== "open";
const pending = busy || (waitingForLocal && !error);
const invalidReturn = ["pair_invalid", "pair_expired", "pair_used"].some((code) => error === `remote.errors.${code}`);
const requestUnavailable = error === "remote.errors.pair_expired" || error === "remote.errors.pair_used";
const restartAvailable = !saved && (expired || requestUnavailable || (!!error && !request?.command && !preview && (!returned || invalidReturn)));
const visiblePreview = restartAvailable ? null : preview;
const reviewingReturn = !!returned && !request?.command && !visiblePreview && !manual && !restartAvailable;
const title = visiblePreview ? visiblePreview.existing_connection ? "remote.sameInstance.title" : "remote.pair.confirmTitle" : reviewingReturn ? "remote.pair.review" : restartAvailable ? "remote.add"
: manual ? "remote.pair.code" : copied ? "remote.pair.copiedTitle" : "remote.add";
const description = visiblePreview || reviewingReturn ? "remote.pair.confirmLinkDescription" : restartAvailable ? "remote.pair.introHint"
: manual ? "remote.pair.codeHint" : copied ? "remote.pair.afterCopyHint" : "remote.pair.introHint";
const showCopied = copied && !manual && !visiblePreview && !restartAvailable;
const showIllustration = !visiblePreview && !manual && !reviewingReturn && !restartAvailable;
const showBusy = pending && busyVisible;
const actionLabel = restartAvailable ? "remote.pair.restart" : reviewingReturn ? error ? "remote.retry" : "remote.pair.review" : visiblePreview ? saved ? "remote.retry" : visiblePreview.existing_connection ? "remote.sameInstance.saveAndOpen" : "remote.connect"
: manual ? "remote.pair.review" : copied ? "remote.pair.copyAgain" : "remote.pair.copy";
const busyLabel = waitingForLocal ? "remote.pair.waitingForLocal" : visiblePreview ? "remote.connecting" : !restartAvailable && (manual || returned)
? "remote.pair.checkingLink" : "remote.pair.preparing";
return <div className="remote-pair flex min-h-0 flex-col">
<div className="-mx-1 min-h-0 overflow-y-auto overscroll-contain px-1">
<DialogHeader className={showIllustration ? "space-y-0 text-center sm:text-center" : "pr-5 text-left"}>
{showIllustration && <RemoteConnectionIllustration />}
<div aria-live="polite" aria-atomic="true" className="space-y-1.5">
<DialogTitle className={showIllustration ? "flex min-h-5 items-center justify-center gap-2 text-xl leading-snug tracking-normal" : "flex min-h-5 items-center gap-2"}>
{showCopied && <Check aria-hidden="true" className="h-5 w-5 shrink-0 motion-safe:animate-in motion-safe:fade-in duration-150" />}
<span className="min-w-0 [overflow-wrap:anywhere]">{t(title)}</span>
</DialogTitle>
<DialogDescription>{t(description)}</DialogDescription>
</div>
</DialogHeader>
{visiblePreview ? <div className="space-y-4 pt-4">
<div className="rounded-2xl bg-muted/50 p-4">
<p className="font-medium [overflow-wrap:anywhere]">{visiblePreview.existing_connection?.name || visiblePreview.hostname}</p>
<p className="mt-1 break-all text-xs text-muted-foreground">{visiblePreview.host}</p>
</div>
{visiblePreview.existing_connection && <p role="status" className="text-xs leading-5 text-muted-foreground">{t("remote.sameInstance.pairHint")}</p>}
<p className="text-[13px] leading-5">{t("remote.pair.access")}</p>
<p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.expiry", { date: new Date(visiblePreview.authorized_until * 1000).toLocaleDateString() })}</p>
<Disclosure className="text-xs text-muted-foreground" summaryClassName="flex min-h-9 items-center gap-2 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{t("remote.pair.security")}</>}>
<p className="my-2 leading-5">{t("remote.pair.fingerprint")}</p><code className="block break-all">{visiblePreview.fingerprint}</code>
<p className="mb-2 mt-4 leading-5">{t("remote.pair.revoke")}</p><CodeBlock language="bash" code={visiblePreview.revoke_command} highlight={false} className="min-w-0 [&_pre]:[overflow-wrap:anywhere]" />
</Disclosure>
{saved && error && <div className="space-y-2"><p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.retryHint")}</p>
<Disclosure summaryClassName="flex min-h-9 items-center gap-2 rounded-xl text-xs text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" contentClassName="pt-2"
summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{t("remote.pair.route")}</>}>{routeSettings}</Disclosure>
</div>}
</div> : restartAvailable ? null : <>
{manual && <div className="space-y-2 pt-4"><label htmlFor={codeId} className="sr-only">{t("remote.pair.code")}</label>
<Textarea ref={manualInput} id={codeId} value={code} onChange={(event) => onCodeChange(event.target.value)} placeholder="nbpc1.…" autoComplete="off" spellCheck={false} disabled={busy || expired} className="min-h-20 resize-none break-all font-mono text-xs" />
</div>}
<div>
<DisclosureContent id={panelId} open={panel === "command" && !!request?.command} className="pt-4">
<div className="rounded-2xl bg-muted/50 p-3">
<code className="block max-h-32 select-text overflow-y-auto text-[11px] leading-5 [overflow-wrap:anywhere]" aria-label={t("remote.pair.command")}>{request?.command}</code>
</div>
</DisclosureContent>
<DisclosureContent open={panel === "help"} className="pt-4">
<div className="space-y-2 rounded-2xl bg-muted/50 p-3 text-xs leading-5 text-muted-foreground">
<p className="font-medium text-foreground">{t("remote.pair.helpTitle")}</p>
<p>{t("remote.pair.requirements")}</p>
<p>{t("remote.pair.runHint")}</p>
<p>{t("remote.pair.validityHint")}</p>
</div>
</DisclosureContent>
</div>
</>}
{expired && !saved && <p role="status" className="mt-4 text-xs leading-5 text-muted-foreground">{t("remote.pair.expired")}</p>}
{error && <p role="alert" className="remote-alert mt-4 items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{t(error, { defaultValue: t("remote.errors.unknown") })}</span></p>}
</div>
<div className={visiblePreview ? "remote-dialog-actions shrink-0 pt-5" : "flex shrink-0 flex-col gap-2 pt-5"}>
{visiblePreview && (!saved ? <Button className="remote-action" variant="ghost" disabled={busy} onClick={onBack}><ArrowLeft className="mr-1 h-4 w-4" />{t("remote.back")}</Button>
: <Button className="remote-action" variant="ghost" onClick={onCancel}>{t("common.cancel")}</Button>
)}
<Button variant={showCopied ? "outline" : "default"} className={showCopied ? "remote-action bg-transparent" : "remote-action"} aria-label={t(showBusy ? busyLabel : actionLabel)} aria-busy={pending} disabled={busy || waitingForLocal || (!restartAvailable && (!request || (!visiblePreview && (manual || reviewingReturn ? !code.trim() : !request.command))))} onClick={() => { if (restartAvailable) onStart(); else if (visiblePreview) onConnect(); else if (manual || reviewingReturn) onReview(); else onCopyCommand(); }}>
{showBusy ? <Loader2 aria-hidden="true" className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" /> : !restartAvailable && !visiblePreview && !manual && !reviewingReturn ? <Copy aria-hidden="true" className="mr-2 h-4 w-4 shrink-0" /> : null}
<span role="status" className="min-w-0">{t(showBusy ? busyLabel : actionLabel)}</span>
</Button>
{!visiblePreview && <div className="remote-pair-alternatives -mx-3 gap-1">
{!restartAvailable && request?.command ? manual ? <Button className="remote-action" variant="ghost" size="sm" disabled={busy} onClick={() => onManualChange(false)}>{t("remote.back")}</Button>
: <Button variant="ghost" size="sm" className="remote-action justify-start text-left text-xs text-muted-foreground" disabled={expired} aria-expanded={panel === "command"} aria-controls={panelId} onClick={() => onPanelChange(panel === "command" ? null : "command")}>{t("remote.pair.showCommand")}</Button> : <span />}
<DropdownMenu>
<DropdownMenuTrigger asChild><Button variant="ghost" size="sm" className="remote-action justify-end text-right text-xs text-muted-foreground">{t("remote.pair.otherWays")}<ChevronDown aria-hidden="true" className="ml-1 h-3.5 w-3.5 shrink-0" /></Button></DropdownMenuTrigger>
<DropdownMenuContent align="end" onCloseAutoFocus={(event) => {
if (focusManual.current) { event.preventDefault(); focusManual.current = false; manualInput.current?.focus(); }
}}>
<DropdownMenuItem disabled={!request || busy || expired || restartAvailable} onSelect={() => { focusManual.current = true; onManualChange(true); }}>{t("remote.pair.pasteInstead")}</DropdownMenuItem>
<DropdownMenuItem onSelect={onSSH}>{t("remote.pair.useSSH")}</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem disabled={restartAvailable} onSelect={() => onPanelChange(panel === "help" ? null : "help")}>{t("remote.pair.helpTitle")}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>}
</div>
</div>;
}
/** Decorative overview, not a live connection-status indicator. */
function RemoteConnectionIllustration() {
return <svg viewBox="0 0 208 88" width="184" height="78" aria-hidden="true" focusable="false" className="mx-auto mb-4 shrink-0 text-foreground/70" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
<path d="M78 51 C111 65 114 28 146 36" className="text-muted-foreground/50" strokeWidth="2.5" />
<rect x="10" y="25" width="68" height="43" rx="3" />
<path d="M4 68 H84 V70 A5 5 0 0 1 79 75 H9 A5 5 0 0 1 4 70 Z" />
<g className="text-muted-foreground">
<rect x="27" y="34" width="34" height="26" rx="2" />
<path d="M32 39 h.01 M36 39 h.01 M40 39 h.01" strokeWidth="2.5" />
</g>
<rect x="146" y="10" width="50" height="70" rx="3" />
<image href="/brand/nanobot_mark.svg" x="155" y="17" width="32" height="32" />
<path d="M146 53 H196 M146 66 H196 M152 60 H177 M152 73 H177 M152 80 V83 H158 V80 M184 80 V83 H190 V80" />
<circle cx="188" cy="60" r="1.8" />
<circle cx="188" cy="73" r="1.8" />
</svg>;
}
+10 -62
View File
@@ -1,31 +1,23 @@
import { useCallback, useEffect, useId, useRef, useState, type RefObject } from "react";
import { Check, RefreshCw, Server } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useClient } from "@/providers/ClientProvider";
import { remoteAction, type SSHDiscovery } from "@/lib/remote-instances";
import { SSHHostPickerView, type SSHHostPickerViewProps } from "./SSHHostPickerView";
type SSHHostPickerProps = Pick<SSHHostPickerViewProps,
"disabled" | "value" | "imported" | "suggestions" | "onChange" | "onBlur" | "inputRef"> & {
configFile: string;
};
/** One address field for both manual entry and existing SSH aliases. */
export function SSHHostPicker({ disabled, value, configFile, imported, suggestions = true, onChange, onBlur, inputRef }: {
disabled: boolean;
value: string;
configFile: string;
imported: boolean;
suggestions?: boolean;
onChange: (host: string) => void;
onBlur: () => void;
inputRef: RefObject<HTMLInputElement>;
}) {
export function SSHHostPicker({ configFile, suggestions = true, ...props }: SSHHostPickerProps) {
const { t } = useTranslation();
const { client } = useClient();
const id = useId();
const [result, setResult] = useState<{ file: string; data: SSHDiscovery } | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const requestId = useRef(0);
const mounted = useRef(true);
const list = useRef<HTMLDivElement>(null);
const file = configFile.trim();
const load = useCallback(async (path: string) => {
const request = ++requestId.current;
@@ -64,50 +56,6 @@ export function SSHHostPicker({ disabled, value, configFile, imported, suggestio
// Never select cached suggestions belonging to a different config file.
const data = suggestions && result?.file === file ? result.data : null;
const matched = (data?.hosts ?? []).filter(({ host }) => host.toLowerCase().includes(value.trim().toLowerCase()));
// A user recovering from a failed user@IP connection may select a custom
// config containing an alias. Keep that alias discoverable without asking
// them to know it already or silently replacing the address they entered.
const hosts = matched.length || !file ? matched : (data?.hosts ?? []);
return <div className="space-y-2.5">
<label htmlFor={id} className="block text-[13px] font-medium">{t("remote.host")}</label>
<Input ref={inputRef} id={id} value={value} required disabled={disabled} autoComplete="off" spellCheck={false}
placeholder={t("remote.hostPlaceholder")} aria-describedby={`${id}-hint`}
onChange={(event) => onChange(event.target.value)}
onBlur={onBlur}
onKeyDown={(event) => {
if (event.key === "ArrowDown" && hosts.length && !busy) {
event.preventDefault(); list.current?.querySelector<HTMLButtonElement>("button")?.focus();
}
}} />
<p id={`${id}-hint`} role={imported ? "status" : undefined} className="text-xs leading-5 text-muted-foreground">{t(imported ? "remote.commandImported" : suggestions ? "remote.commandHint" : "remote.addressHint")}</p>
{suggestions && (!!hosts.length || !!error) && <div className="rounded-2xl bg-muted/40 p-1.5">
<div className="flex min-h-8 items-center justify-between gap-2 px-2">
<span className="text-xs text-muted-foreground">{t("remote.sshHosts")}</span>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 shrink-0" aria-label={t("remote.refreshHosts")}
disabled={busy || disabled} onClick={() => { void load(file); }}>
<RefreshCw className={`h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} />
</Button>
</div>
<div ref={list} className="max-h-36 overflow-y-auto" aria-label={t("remote.sshHosts")}>
{hosts.map((host, index) => <button key={host.host} type="button" disabled={disabled || busy}
title={host.source} aria-label={t("remote.useHost", { host: host.host })}
className="flex min-h-9 w-full items-center gap-2.5 rounded-xl px-2 text-left text-[13px] transition-colors hover:bg-foreground/5 focus-visible:bg-foreground/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50"
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
const next = index + (event.key === "ArrowDown" ? 1 : -1);
if (next < 0) inputRef.current?.focus();
else list.current?.querySelectorAll<HTMLButtonElement>("button")[next]?.focus();
}
}}
onClick={() => { onChange(host.host); inputRef.current?.focus(); }}>
<Server className="h-4 w-4 shrink-0 text-muted-foreground" /><span className="min-w-0 flex-1 truncate">{host.host}</span>
{value === host.host && <Check className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
</button>)}
</div>
{error && <p role="alert" className="px-2 py-1 text-xs leading-5 text-muted-foreground">{error}</p>}
</div>}
{data?.incomplete && <p className="text-xs leading-5 text-muted-foreground">{t("remote.partialHosts")}</p>}
</div>;
return <SSHHostPickerView {...props} suggestions={suggestions} customConfig={!!file}
discovery={data} busy={busy} error={error} onRefresh={() => { void load(file); }} />;
}
@@ -0,0 +1,75 @@
import { useId, useRef, type RefObject } from "react";
import { Check, RefreshCw, Server } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import type { SSHDiscovery } from "@/lib/remote-instances";
export interface SSHHostPickerViewProps {
disabled: boolean;
value: string;
imported: boolean;
suggestions?: boolean;
customConfig?: boolean;
discovery: SSHDiscovery | null;
busy: boolean;
error: string;
onRefresh: () => void;
onChange: (host: string) => void;
onBlur: () => void;
inputRef: RefObject<HTMLInputElement>;
}
export function SSHHostPickerView({ disabled, value, imported, suggestions = true, customConfig = false,
discovery, busy, error, onRefresh, onChange, onBlur, inputRef }: SSHHostPickerViewProps) {
const { t } = useTranslation();
const id = useId();
const list = useRef<HTMLDivElement>(null);
const data = suggestions ? discovery : null;
const matched = (data?.hosts ?? []).filter(({ host }) => host.toLowerCase().includes(value.trim().toLowerCase()));
// A user recovering from a failed user@IP connection may select a custom
// config containing an alias. Keep that alias discoverable without asking
// them to know it already or silently replacing the address they entered.
const hosts = matched.length || !customConfig ? matched : (data?.hosts ?? []);
return <div className="space-y-2.5">
<label htmlFor={id} className="block text-[13px] font-medium">{t("remote.host")}</label>
<Input ref={inputRef} id={id} value={value} required disabled={disabled} autoComplete="off" spellCheck={false}
placeholder={t("remote.hostPlaceholder")} aria-describedby={`${id}-hint`}
onChange={(event) => onChange(event.target.value)}
onBlur={onBlur}
onKeyDown={(event) => {
if (event.key === "ArrowDown" && hosts.length && !busy) {
event.preventDefault(); list.current?.querySelector<HTMLButtonElement>("button")?.focus();
}
}} />
<p id={`${id}-hint`} role={imported ? "status" : undefined} className="text-xs leading-5 text-muted-foreground">{t(imported ? "remote.commandImported" : suggestions ? "remote.commandHint" : "remote.addressHint")}</p>
{suggestions && (!!hosts.length || !!error) && <div className="rounded-2xl bg-muted/40 p-1.5">
<div className="flex min-h-8 items-center justify-between gap-2 px-2">
<span className="text-xs text-muted-foreground">{t("remote.sshHosts")}</span>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7 shrink-0" aria-label={t("remote.refreshHosts")}
disabled={busy || disabled} onClick={onRefresh}>
<RefreshCw className={`h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} />
</Button>
</div>
<div ref={list} className="max-h-36 overflow-y-auto" aria-label={t("remote.sshHosts")}>
{hosts.map((host, index) => <button key={host.host} type="button" disabled={disabled || busy}
title={host.source} aria-label={t("remote.useHost", { host: host.host })}
className="flex min-h-9 w-full items-center gap-2.5 rounded-xl px-2 text-left text-[13px] transition-colors hover:bg-foreground/5 focus-visible:bg-foreground/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50"
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
const next = index + (event.key === "ArrowDown" ? 1 : -1);
if (next < 0) inputRef.current?.focus();
else list.current?.querySelectorAll<HTMLButtonElement>("button")[next]?.focus();
}
}}
onClick={() => { onChange(host.host); inputRef.current?.focus(); }}>
<Server className="h-4 w-4 shrink-0 text-muted-foreground" /><span className="min-w-0 flex-1 truncate">{host.host}</span>
{value === host.host && <Check className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
</button>)}
</div>
{error && <p role="alert" className="px-2 py-1 text-xs leading-5 text-muted-foreground">{error}</p>}
</div>}
{data?.incomplete && <p className="text-xs leading-5 text-muted-foreground">{t("remote.partialHosts")}</p>}
</div>;
}
@@ -0,0 +1,28 @@
import { createContext } from "react";
import type { HostAnchor, EmbeddedHost } from "./host-bridge";
import type { HostConnectionState } from "./remote-context";
export interface HostPicker {
kind: "shell";
name: string;
hostname: string;
localName: string;
currentId: string | null;
profiles: { id: string; name: string; host: string; state: HostConnectionState }[];
recentIds: string[];
pending: { id: string; name: string } | null;
error: string;
offline: boolean;
offlineLabel?: string;
select: (id: string | null) => void;
manage: () => void;
cancel: () => void;
clearError: () => void;
restoreFocus: () => void;
}
export interface EmbeddedPicker extends EmbeddedHost {
kind: "embedded";
open: (anchor: HostAnchor) => void;
}
export const HostNavigationContext = createContext<HostPicker | EmbeddedPicker | null>(null);
@@ -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";
@@ -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";
@@ -1,46 +1,11 @@
import { useRef, useState } from "react";
import {
CalendarClock,
ChevronRight,
CircleAlert,
RefreshCcw,
} from "lucide-react";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import { useCallback, useState } from "react";
import {
AutomationDeleteDialog,
AutomationDetailDialog,
AutomationEditDialog,
} from "@/components/settings/system/AutomationsSettings";
import type { AutomationAction } from "@/components/settings/system/AutomationsSettings";
import { Button } from "@/components/ui/button";
import { formControlFocusClassName } from "@/components/ui/form-control";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { SessionInfoPopoverView } from "@/components/thread/SessionInfoPopoverView";
import { useSessionAutomationJobs } from "@/hooks/useSessionAutomationJobs";
import { currentLocale } from "@/i18n";
import { runAutomationAction, updateAutomation } from "@/lib/api";
import type { WebUIMutationTransport } from "@/lib/api";
import { fmtDateTime } from "@/lib/format-time";
import type {
AutomationUpdatePayload,
SessionAutomationJob,
} from "@/lib/types";
import { cn } from "@/lib/utils";
const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [
[60, "second"],
[60, "minute"],
[24, "hour"],
[7, "day"],
[4.345, "week"],
[12, "month"],
[Number.POSITIVE_INFINITY, "year"],
];
import type { AutomationUpdatePayload, SessionAutomationJob } from "@/lib/types";
interface SessionInfoPopoverProps {
client: WebUIMutationTransport;
@@ -50,286 +15,12 @@ interface SessionInfoPopoverProps {
}
export function SessionInfoPopover({ client, sessionKey, token, title }: SessionInfoPopoverProps) {
const { t } = useTranslation("common");
const [open, setOpen] = useState(false);
const [inspectedJob, setInspectedJob] = useState<SessionAutomationJob | null>(null);
const [detailOpen, setDetailOpen] = useState(false);
const [actionKey, setActionKey] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const [pendingEdit, setPendingEdit] = useState<SessionAutomationJob | null>(null);
const [pendingDelete, setPendingDelete] = useState<SessionAutomationJob | null>(null);
const triggerRef = useRef<HTMLButtonElement | null>(null);
const afterDetailClose = useRef<(() => void) | null>(null);
const surfacesOpen = open || detailOpen || Boolean(pendingEdit) || Boolean(pendingDelete);
const { jobs, loading, loadFailed, now } = useSessionAutomationJobs(
surfacesOpen,
token,
sessionKey,
);
const selectedJob = inspectedJob;
const inspectJob = (job: SessionAutomationJob) => {
setActionError(null);
setInspectedJob(job);
setOpen(false);
setDetailOpen(true);
};
const handOffDetail = (next: () => void) => {
afterDetailClose.current = next;
setDetailOpen(false);
};
const updateInspectedJob = (nextJobs: SessionAutomationJob[], id: string) => {
const nextJob = nextJobs.find((job) => job.id === id);
if (nextJob) setInspectedJob(nextJob);
};
const handleAction = async (action: AutomationAction, job: SessionAutomationJob) => {
const key = `${action}:${job.id}`;
setActionKey(key);
setActionError(null);
try {
const payload = await runAutomationAction(client, action, job.id);
if (action === "delete") {
setPendingDelete(null);
setInspectedJob(null);
} else {
updateInspectedJob(payload.jobs, job.id);
}
} catch (error) {
setActionError(error instanceof Error ? error.message : String(error));
} finally {
setActionKey(null);
}
};
const handleEdit = async (job: SessionAutomationJob, values: AutomationUpdatePayload) => {
const key = `update:${job.id}`;
setActionKey(key);
setActionError(null);
try {
const payload = await updateAutomation(client, job.id, values);
updateInspectedJob(payload.jobs, job.id);
setPendingEdit(null);
} catch (error) {
setActionError(error instanceof Error ? error.message : String(error));
} finally {
setActionKey(null);
}
};
const automationContent = loading ? (
<div className="mx-2 flex items-center gap-2 rounded-floating bg-muted/45 px-3 py-3 text-[12.5px] text-muted-foreground">
<RefreshCcw className="h-3.5 w-3.5 animate-spin" />
{t("thread.sessionInfo.loading")}
</div>
) : loadFailed ? (
<div className="mx-2 flex items-center gap-2 rounded-floating bg-destructive/10 px-3 py-3 text-[12.5px] text-destructive">
<CircleAlert className="h-3.5 w-3.5" />
{t("thread.sessionInfo.loadFailed")}
</div>
) : jobs.length ? (
<div className="space-y-1 px-2">
{jobs.map((job) => (
<AutomationRow key={job.id} job={job} now={now} onSelect={inspectJob} />
))}
</div>
) : (
<div className="mx-2 rounded-floating bg-muted/35 px-3 py-3 text-[12.5px] leading-relaxed text-muted-foreground">
{t("thread.sessionInfo.empty")}
</div>
);
return (
<>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
ref={triggerRef}
variant="ghost"
size="icon"
aria-label={t("thread.header.sessionInfo")}
className={cn(
"host-no-drag h-8 w-8 rounded-control text-muted-foreground/85",
"hover:text-foreground",
)}
>
<CalendarClock className="h-4 w-4 stroke-[1.75]" />
</Button>
</PopoverTrigger>
<PopoverContent
align="end"
sideOffset={8}
className="w-[min(23rem,calc(100vw-1.5rem))] overflow-hidden p-0"
onCloseAutoFocus={(event) => {
if (detailOpen) event.preventDefault();
}}
>
<div className="flex max-h-[min(var(--radix-popover-content-available-height),32rem)] flex-col">
<div className="px-4 pb-3 pt-3.5">
<div className="min-w-0">
<div className="text-[12px] font-normal text-muted-foreground/75">
{t("thread.sessionInfo.title")}
</div>
<div className="mt-0.5 truncate text-[14px] font-medium text-foreground">
{title || t("thread.sessionInfo.untitled")}
</div>
</div>
<div className="mt-3 flex items-center justify-between gap-3 border-t border-border/45 pt-3">
<span className="truncate text-[13px] font-medium text-foreground">
{t("thread.sessionInfo.automations")}
</span>
<span className="rounded-full bg-muted/70 px-2 py-0.5 text-[11px] tabular-nums text-muted-foreground">
{t("thread.sessionInfo.count", { count: jobs.length })}
</span>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain pb-2">
{automationContent}
</div>
<div className="border-t border-border/45 p-2">
<Button asChild variant="ghost" size="sm" className="w-full justify-between px-2 text-[12px] text-muted-foreground">
<a href="#/automations">
{t("thread.sessionInfo.openCalendar")}
<ChevronRight className="h-3.5 w-3.5" aria-hidden />
</a>
</Button>
</div>
</div>
</PopoverContent>
</Popover>
<AutomationDetailDialog
job={selectedJob}
open={detailOpen}
locale={currentLocale()}
actionKey={actionKey}
error={actionError}
onOpenChange={setDetailOpen}
onAction={handleAction}
onRequestEdit={(job) => handOffDetail(() => setPendingEdit(job))}
onRequestDelete={(job) => handOffDetail(() => setPendingDelete(job))}
onCloseAutoFocus={(event) => {
event.preventDefault();
if (detailOpen) return;
setInspectedJob(null);
triggerRef.current?.focus({ preventScroll: true });
const next = afterDetailClose.current;
afterDetailClose.current = null;
next?.();
}}
/>
<AutomationEditDialog
job={pendingEdit}
saving={actionKey === `update:${pendingEdit?.id ?? ""}`}
onOpenChange={(nextOpen) => {
if (!nextOpen) setPendingEdit(null);
}}
onCancel={(job) => {
setInspectedJob(job);
setDetailOpen(true);
}}
onSave={handleEdit}
/>
<AutomationDeleteDialog
job={pendingDelete}
deleting={actionKey === `delete:${pendingDelete?.id ?? ""}`}
onOpenChange={(nextOpen) => {
if (!nextOpen) setPendingDelete(null);
}}
onConfirm={(job) => handleAction("delete", job)}
/>
</>
);
}
function AutomationRow({
job,
now,
onSelect,
}: {
job: SessionAutomationJob;
now: number;
onSelect: (job: SessionAutomationJob) => void;
}) {
const { t } = useTranslation("common");
const nextRun = formatNextRun(job, t, now);
const needsAttention = job.state.last_status === "error" || Boolean(job.state.last_error);
const summary = needsAttention
? t("settings.automations.filters.failed", { defaultValue: "Needs attention" })
: nextRun.label;
const statusClass = job.enabled
? needsAttention
? "bg-destructive"
: "bg-emerald-500"
: "bg-muted-foreground/35";
return (
<button
type="button"
aria-haspopup="dialog"
aria-label={`${job.name || job.id}, ${summary}`}
onClick={() => onSelect(job)}
className={cn(
"grid min-h-12 w-full grid-cols-[0.375rem_minmax(0,1fr)_1rem] items-center gap-2.5 rounded-control px-3 py-2 text-left",
"transition-colors duration-150 settings-hover",
formControlFocusClassName,
)}
>
<span className={cn("h-1.5 w-1.5 shrink-0 rounded-full", statusClass)} aria-hidden />
<span className="min-w-0">
<span className="block truncate text-[13px] font-medium leading-5 text-foreground">
{job.name || job.id}
</span>
<span
className={cn(
"block truncate text-[11.5px] leading-4 text-muted-foreground",
needsAttention && "text-destructive",
)}
title={needsAttention ? summary : nextRun.title}
>
{summary}
</span>
</span>
<ChevronRight className="h-4 w-4 text-muted-foreground/65" aria-hidden />
</button>
);
}
function formatNextRun(job: SessionAutomationJob, t: TFunction, now: number) {
const locale = currentLocale();
if (!job.enabled) {
return { label: t("thread.sessionInfo.next.disabled"), title: "" };
}
if (job.state.pending) {
return { label: t("thread.sessionInfo.next.pending"), title: "" };
}
if (isLocalTriggerAutomation(job)) {
return { label: t("thread.sessionInfo.next.local"), title: "" };
}
const next = job.state.next_run_at_ms;
if (!next) {
return { label: t("thread.sessionInfo.next.none"), title: "" };
}
return {
label: t("thread.sessionInfo.next.label", { time: relativeTimeFrom(next, now, locale) }),
title: fmtDateTime(next, locale),
};
}
function isLocalTriggerAutomation(job: SessionAutomationJob): boolean {
return job.kind === "local_trigger"
|| job.payload.kind === "local_trigger"
|| job.schedule.kind === "local";
}
function relativeTimeFrom(value: number, now: number, locale: string): string {
let delta = (value - now) / 1000;
const formatter = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
for (const [step, unit] of RELATIVE_THRESHOLDS) {
if (Math.abs(delta) < step) {
return formatter.format(Math.round(delta), unit);
}
delta /= step;
}
return formatter.format(Math.round(delta), "year");
const [surfacesOpen, setSurfacesOpen] = useState(false);
const { jobs, loading, loadFailed, now } = useSessionAutomationJobs(surfacesOpen, token, sessionKey);
const act = useCallback(async (action: AutomationAction, job: SessionAutomationJob) =>
(await runAutomationAction(client, action, job.id)).jobs, [client]);
const edit = useCallback(async (job: SessionAutomationJob, values: AutomationUpdatePayload) =>
(await updateAutomation(client, job.id, values)).jobs, [client]);
return <SessionInfoPopoverView title={title} jobs={jobs} loading={loading} loadFailed={loadFailed} now={now}
onAction={act} onEdit={edit} onSurfacesOpenChange={setSurfacesOpen} calendarHref="#/automations" />;
}
@@ -0,0 +1,334 @@
import { useEffect, useRef, useState } from "react";
import {
CalendarClock,
ChevronRight,
CircleAlert,
RefreshCcw,
} from "lucide-react";
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import {
AutomationDeleteDialog,
AutomationDetailDialog,
AutomationEditDialog,
} from "@/components/settings/system/AutomationsSettings";
import type { AutomationAction } from "@/components/settings/system/AutomationsSettings";
import { Button } from "@/components/ui/button";
import { formControlFocusClassName } from "@/components/ui/form-control";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { currentLocale } from "@/i18n";
import { fmtDateTime } from "@/lib/format-time";
import type {
AutomationUpdatePayload,
SessionAutomationJob,
} from "@/lib/types";
import { cn } from "@/lib/utils";
const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [
[60, "second"],
[60, "minute"],
[24, "hour"],
[7, "day"],
[4.345, "week"],
[12, "month"],
[Number.POSITIVE_INFINITY, "year"],
];
export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now, onAction, onEdit,
onSurfacesOpenChange, calendarHref, onOpenCalendar }: {
title: string;
jobs: SessionAutomationJob[];
loading: boolean;
loadFailed: boolean;
now: number;
onAction: (action: AutomationAction, job: SessionAutomationJob) => Promise<SessionAutomationJob[]>;
onEdit: (job: SessionAutomationJob, values: AutomationUpdatePayload) => Promise<SessionAutomationJob[]>;
onSurfacesOpenChange?: (open: boolean) => void;
calendarHref?: string;
onOpenCalendar?: () => void;
}) {
const { t } = useTranslation("common");
const [open, setOpen] = useState(false);
const [inspectedJob, setInspectedJob] = useState<SessionAutomationJob | null>(null);
const [detailOpen, setDetailOpen] = useState(false);
const [actionKey, setActionKey] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const [pendingEdit, setPendingEdit] = useState<SessionAutomationJob | null>(null);
const [pendingDelete, setPendingDelete] = useState<SessionAutomationJob | null>(null);
const triggerRef = useRef<HTMLButtonElement | null>(null);
const afterDetailClose = useRef<(() => void) | null>(null);
const surfacesOpen = open || detailOpen || Boolean(pendingEdit) || Boolean(pendingDelete);
useEffect(() => { onSurfacesOpenChange?.(surfacesOpen); }, [onSurfacesOpenChange, surfacesOpen]);
const selectedJob = inspectedJob;
const inspectJob = (job: SessionAutomationJob) => {
setActionError(null);
setInspectedJob(job);
setOpen(false);
setDetailOpen(true);
};
const handOffDetail = (next: () => void) => {
afterDetailClose.current = next;
setDetailOpen(false);
};
const updateInspectedJob = (nextJobs: SessionAutomationJob[], id: string) => {
const nextJob = nextJobs.find((job) => job.id === id);
if (nextJob) setInspectedJob(nextJob);
};
const handleAction = async (action: AutomationAction, job: SessionAutomationJob) => {
const key = `${action}:${job.id}`;
setActionKey(key);
setActionError(null);
try {
const nextJobs = await onAction(action, job);
if (action === "delete") {
setPendingDelete(null);
setInspectedJob(null);
} else {
updateInspectedJob(nextJobs, job.id);
}
} catch (error) {
setActionError(error instanceof Error ? error.message : String(error));
} finally {
setActionKey(null);
}
};
const handleEdit = async (job: SessionAutomationJob, values: AutomationUpdatePayload) => {
const key = `update:${job.id}`;
setActionKey(key);
setActionError(null);
try {
const nextJobs = await onEdit(job, values);
updateInspectedJob(nextJobs, job.id);
setPendingEdit(null);
} catch (error) {
setActionError(error instanceof Error ? error.message : String(error));
} finally {
setActionKey(null);
}
};
const automationContent = loading ? (
<div className="mx-2 flex items-center gap-2 rounded-floating bg-muted/45 px-3 py-3 text-[12.5px] text-muted-foreground">
<RefreshCcw className="h-3.5 w-3.5 animate-spin" />
{t("thread.sessionInfo.loading")}
</div>
) : loadFailed ? (
<div className="mx-2 flex items-center gap-2 rounded-floating bg-destructive/10 px-3 py-3 text-[12.5px] text-destructive">
<CircleAlert className="h-3.5 w-3.5" />
{t("thread.sessionInfo.loadFailed")}
</div>
) : jobs.length ? (
<div className="space-y-1 px-2">
{jobs.map((job) => (
<AutomationRow key={job.id} job={job} now={now} onSelect={inspectJob} />
))}
</div>
) : (
<div className="mx-2 rounded-floating bg-muted/35 px-3 py-3 text-[12.5px] leading-relaxed text-muted-foreground">
{t("thread.sessionInfo.empty")}
</div>
);
return (
<>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
ref={triggerRef}
variant="ghost"
size="icon"
aria-label={t("thread.header.sessionInfo")}
className={cn(
"host-no-drag h-8 w-8 rounded-control text-muted-foreground/85",
"hover:text-foreground",
)}
>
<CalendarClock className="h-4 w-4 stroke-[1.75]" />
</Button>
</PopoverTrigger>
<PopoverContent
align="end"
sideOffset={8}
className="w-[min(23rem,calc(100vw-1.5rem))] overflow-hidden p-0"
onCloseAutoFocus={(event) => {
if (detailOpen) event.preventDefault();
}}
>
<div className="flex max-h-[min(var(--radix-popover-content-available-height),32rem)] flex-col">
<div className="px-4 pb-3 pt-3.5">
<div className="min-w-0">
<div className="text-[12px] font-normal text-muted-foreground/75">
{t("thread.sessionInfo.title")}
</div>
<div className="mt-0.5 truncate text-[14px] font-medium text-foreground">
{title || t("thread.sessionInfo.untitled")}
</div>
</div>
<div className="mt-3 flex items-center justify-between gap-3 border-t border-border/45 pt-3">
<span className="truncate text-[13px] font-medium text-foreground">
{t("thread.sessionInfo.automations")}
</span>
<span className="rounded-full bg-muted/70 px-2 py-0.5 text-[11px] tabular-nums text-muted-foreground">
{t("thread.sessionInfo.count", { count: jobs.length })}
</span>
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain pb-2">
{automationContent}
</div>
<div className="border-t border-border/45 p-2">
<Button asChild={!!calendarHref} variant="ghost" size="sm" onClick={onOpenCalendar}
className="w-full justify-between px-2 text-[12px] text-muted-foreground">
{calendarHref ? <a href={calendarHref}>
{t("thread.sessionInfo.openCalendar")}
<ChevronRight className="h-3.5 w-3.5" aria-hidden />
</a> : <>{t("thread.sessionInfo.openCalendar")}<ChevronRight className="h-3.5 w-3.5" aria-hidden /></>}
</Button>
</div>
</div>
</PopoverContent>
</Popover>
<AutomationDetailDialog
job={selectedJob}
open={detailOpen}
locale={currentLocale()}
actionKey={actionKey}
error={actionError}
onOpenChange={setDetailOpen}
onAction={handleAction}
onRequestEdit={(job) => handOffDetail(() => setPendingEdit(job))}
onRequestDelete={(job) => handOffDetail(() => setPendingDelete(job))}
onCloseAutoFocus={(event) => {
event.preventDefault();
if (detailOpen) return;
setInspectedJob(null);
triggerRef.current?.focus({ preventScroll: true });
const next = afterDetailClose.current;
afterDetailClose.current = null;
next?.();
}}
/>
<AutomationEditDialog
job={pendingEdit}
saving={actionKey === `update:${pendingEdit?.id ?? ""}`}
onOpenChange={(nextOpen) => {
if (!nextOpen) setPendingEdit(null);
}}
onCancel={(job) => {
setInspectedJob(job);
setDetailOpen(true);
}}
onSave={handleEdit}
/>
<AutomationDeleteDialog
job={pendingDelete}
deleting={actionKey === `delete:${pendingDelete?.id ?? ""}`}
onOpenChange={(nextOpen) => {
if (!nextOpen) setPendingDelete(null);
}}
onConfirm={(job) => handleAction("delete", job)}
/>
</>
);
}
function AutomationRow({
job,
now,
onSelect,
}: {
job: SessionAutomationJob;
now: number;
onSelect: (job: SessionAutomationJob) => void;
}) {
const { t } = useTranslation("common");
const nextRun = formatNextRun(job, t, now);
const needsAttention = job.state.last_status === "error" || Boolean(job.state.last_error);
const summary = needsAttention
? t("settings.automations.filters.failed", { defaultValue: "Needs attention" })
: nextRun.label;
const statusClass = job.enabled
? needsAttention
? "bg-destructive"
: "bg-emerald-500"
: "bg-muted-foreground/35";
return (
<button
type="button"
aria-haspopup="dialog"
aria-label={`${job.name || job.id}, ${summary}`}
onClick={() => onSelect(job)}
className={cn(
"grid min-h-12 w-full grid-cols-[0.375rem_minmax(0,1fr)_1rem] items-center gap-2.5 rounded-control px-3 py-2 text-left",
"transition-colors duration-150 settings-hover",
formControlFocusClassName,
)}
>
<span className={cn("h-1.5 w-1.5 shrink-0 rounded-full", statusClass)} aria-hidden />
<span className="min-w-0">
<span className="block truncate text-[13px] font-medium leading-5 text-foreground">
{job.name || job.id}
</span>
<span
className={cn(
"block truncate text-[11.5px] leading-4 text-muted-foreground",
needsAttention && "text-destructive",
)}
title={needsAttention ? summary : nextRun.title}
>
{summary}
</span>
</span>
<ChevronRight className="h-4 w-4 text-muted-foreground/65" aria-hidden />
</button>
);
}
function formatNextRun(job: SessionAutomationJob, t: TFunction, now: number) {
const locale = currentLocale();
if (!job.enabled) {
return { label: t("thread.sessionInfo.next.disabled"), title: "" };
}
if (job.state.pending) {
return { label: t("thread.sessionInfo.next.pending"), title: "" };
}
if (isLocalTriggerAutomation(job)) {
return { label: t("thread.sessionInfo.next.local"), title: "" };
}
const next = job.state.next_run_at_ms;
if (!next) {
return { label: t("thread.sessionInfo.next.none"), title: "" };
}
return {
label: t("thread.sessionInfo.next.label", { time: relativeTimeFrom(next, now, locale) }),
title: fmtDateTime(next, locale),
};
}
function isLocalTriggerAutomation(job: SessionAutomationJob): boolean {
return job.kind === "local_trigger"
|| job.payload.kind === "local_trigger"
|| job.schedule.kind === "local";
}
function relativeTimeFrom(value: number, now: number, locale: string): string {
let delta = (value - now) / 1000;
const formatter = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
for (const [step, unit] of RELATIVE_THRESHOLDS) {
if (Math.abs(delta) < step) {
return formatter.format(Math.round(delta), unit);
}
delta /= step;
}
return formatter.format(Math.round(delta), "year");
}
+6 -65
View File
@@ -1,14 +1,6 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { LoaderCircle } from "lucide-react";
import { useTranslation } from "react-i18next";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { Button } from "@/components/ui/button";
import { usePageVisibility } from "@/hooks/usePageVisibility";
import { fetchSubagentThread } from "@/lib/api";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { projectThreadEvents } from "@/lib/thread-event-projection";
import type { SubagentTaskSnapshot, UIMessage, WebuiThreadPersistedPayload } from "@/lib/types";
import { SubagentThreadView } from "@/components/thread/SubagentThreadView";
import { useSubagentThread } from "@/components/thread/useSubagentThread";
import type { SubagentTaskSnapshot } from "@/lib/types";
interface SubagentThreadProps {
token: string;
@@ -19,58 +11,7 @@ interface SubagentThreadProps {
}
export function SubagentThread({ token, sessionKey, task, historyEnabled, isStreaming }: SubagentThreadProps) {
const { t } = useTranslation();
const pageVisible = usePageVisibility();
const [thread, setThread] = useState<WebuiThreadPersistedPayload | null>(null);
const [failed, setFailed] = useState(false);
const refreshRef = useRef<(() => void) | null>(null);
const taskId = task.task_id;
useEffect(() => {
if (!historyEnabled || !pageVisible) return;
let cancelled = false;
let refreshing = false;
let pending = false;
const controller = new AbortController();
const refresh = async () => {
if (refreshing) { pending = true; return; }
refreshing = true;
try {
const payload = await fetchSubagentThread(token, sessionKey, taskId, controller.signal);
if (!cancelled) { setThread(payload); setFailed(false); }
} catch {
if (!cancelled) setFailed(true);
} finally {
refreshing = false;
if (pending && !cancelled) { pending = false; void refresh(); }
}
};
refreshRef.current = () => { void refresh(); };
return () => { cancelled = true; refreshRef.current = null; controller.abort(); };
}, [historyEnabled, pageVisible, sessionKey, taskId, token]);
// Task revisions already arrive through the owning chat's event stream.
useEffect(() => {
refreshRef.current?.();
}, [historyEnabled, pageVisible, sessionKey, taskId, task.revision, token]);
const messages = useMemo(() => {
if (historyEnabled) return thread ? projectWebuiThreadMessages(projectThreadEvents(thread.events)) : [];
// Protocol 1 hosts without history still expose a task description and result.
const summary: UIMessage[] = [{ id: `${taskId}-description`, role: "user", content: task.task_description, createdAt: task.created_at * 1000 }];
if (task.result) summary.push({ id: `${taskId}-result`, role: "assistant", content: task.result,
createdAt: (task.completed_at ?? task.created_at) * 1000 });
return summary;
}, [historyEnabled, taskId, task.task_description, task.created_at, task.completed_at, task.result, thread]);
return <>
{failed ? <div role="alert" className="mb-4 flex items-center gap-2 px-5 text-sm text-destructive">
<span>{t("thread.history.error")}</span>
<Button type="button" variant="ghost" size="sm" onClick={() => refreshRef.current?.()}>{t("thread.history.retry")}</Button>
</div> : historyEnabled && thread === null ? <p role="status" className="flex items-center gap-2 px-5 text-sm text-muted-foreground">
<LoaderCircle className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />{t("chat.loading")}
</p> : null}
<ThreadMessages messages={messages} isStreaming={isStreaming} activeTurnId={thread?.active_turn_id}
runStartedAt={task.created_at} />
</>;
const { messages, loading, failed, activeTurnId, retry } = useSubagentThread({ token, sessionKey, task, historyEnabled });
return <SubagentThreadView messages={messages} loading={loading} failed={failed} isStreaming={isStreaming}
activeTurnId={activeTurnId} runStartedAt={task.created_at} onRetry={retry} />;
}
@@ -0,0 +1,27 @@
import { LoaderCircle } from "lucide-react";
import { useTranslation } from "react-i18next";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { Button } from "@/components/ui/button";
import type { UIMessage } from "@/lib/types";
export function SubagentThreadView({ messages, loading, failed, isStreaming, activeTurnId, runStartedAt, onRetry }: {
messages: UIMessage[];
loading: boolean;
failed: boolean;
isStreaming: boolean;
activeTurnId?: string | null;
runStartedAt: number;
onRetry: () => void;
}) {
const { t } = useTranslation();
return <>
{failed ? <div role="alert" className="mb-4 flex items-center gap-2 px-5 text-sm text-destructive">
<span>{t("thread.history.error")}</span>
<Button type="button" variant="ghost" size="sm" onClick={onRetry}>{t("thread.history.retry")}</Button>
</div> : loading ? <p role="status" className="flex items-center gap-2 px-5 text-sm text-muted-foreground">
<LoaderCircle className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />{t("chat.loading")}
</p> : null}
<ThreadMessages messages={messages} isStreaming={isStreaming} activeTurnId={activeTurnId} runStartedAt={runStartedAt} />
</>;
}
@@ -3,7 +3,7 @@ import type { HTMLAttributes, ReactElement } from "react";
import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { ArrowLeft, ArrowRight, Check, ChevronRight, FolderSearch, History, Search, Star } from "lucide-react";
import { useTranslation } from "react-i18next";
import { ToggleButton } from "@/components/settings/ToggleButton";
import { ToggleButton } from "@/components/ui/toggle-button";
import { Button } from "@/components/ui/button";
import { floatingItemClassName, floatingItemFocusClassName } from "@/components/ui/floating-surface";
import { HoverHint } from "@/components/ui/tooltip";
@@ -0,0 +1,60 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { usePageVisibility } from "@/hooks/usePageVisibility";
import { fetchSubagentThread } from "@/lib/api";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { projectThreadEvents } from "@/lib/thread-event-projection";
import type { SubagentTaskSnapshot, UIMessage, WebuiThreadPersistedPayload } from "@/lib/types";
export function useSubagentThread({ token, sessionKey, task, historyEnabled }: {
token: string;
sessionKey: string;
task: SubagentTaskSnapshot;
historyEnabled: boolean;
}) {
const pageVisible = usePageVisibility();
const [thread, setThread] = useState<WebuiThreadPersistedPayload | null>(null);
const [failed, setFailed] = useState(false);
const refreshRef = useRef<(() => void) | null>(null);
const taskId = task.task_id;
useEffect(() => {
if (!historyEnabled || !pageVisible) return;
let cancelled = false;
let refreshing = false;
let pending = false;
const controller = new AbortController();
const refresh = async () => {
if (refreshing) { pending = true; return; }
refreshing = true;
try {
const payload = await fetchSubagentThread(token, sessionKey, taskId, controller.signal);
if (!cancelled) { setThread(payload); setFailed(false); }
} catch {
if (!cancelled) setFailed(true);
} finally {
refreshing = false;
if (pending && !cancelled) { pending = false; void refresh(); }
}
};
refreshRef.current = () => { void refresh(); };
return () => { cancelled = true; refreshRef.current = null; controller.abort(); };
}, [historyEnabled, pageVisible, sessionKey, taskId, token]);
// Task revisions already arrive through the owning chat's event stream.
useEffect(() => {
refreshRef.current?.();
}, [historyEnabled, pageVisible, sessionKey, taskId, task.revision, token]);
const messages = useMemo(() => {
if (historyEnabled) return thread ? projectWebuiThreadMessages(projectThreadEvents(thread.events)) : [];
// Protocol 1 hosts without history still expose a task description and result.
const summary: UIMessage[] = [{ id: `${taskId}-description`, role: "user", content: task.task_description, createdAt: task.created_at * 1000 }];
if (task.result) summary.push({ id: `${taskId}-result`, role: "assistant", content: task.result,
createdAt: (task.completed_at ?? task.created_at) * 1000 });
return summary;
}, [historyEnabled, taskId, task.task_description, task.created_at, task.completed_at, task.result, thread]);
const retry = useCallback(() => refreshRef.current?.(), []);
return { messages, failed, loading: historyEnabled && thread === null, activeTurnId: thread?.active_turn_id, retry };
}